babylon.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243
  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. var KeyboardEventTypes = /** @class */ (function () {
  1269. function KeyboardEventTypes() {
  1270. }
  1271. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1272. get: function () {
  1273. return KeyboardEventTypes._KEYDOWN;
  1274. },
  1275. enumerable: true,
  1276. configurable: true
  1277. });
  1278. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1279. get: function () {
  1280. return KeyboardEventTypes._KEYUP;
  1281. },
  1282. enumerable: true,
  1283. configurable: true
  1284. });
  1285. KeyboardEventTypes._KEYDOWN = 0x01;
  1286. KeyboardEventTypes._KEYUP = 0x02;
  1287. return KeyboardEventTypes;
  1288. }());
  1289. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1290. var KeyboardInfo = /** @class */ (function () {
  1291. function KeyboardInfo(type, event) {
  1292. this.type = type;
  1293. this.event = event;
  1294. }
  1295. return KeyboardInfo;
  1296. }());
  1297. BABYLON.KeyboardInfo = KeyboardInfo;
  1298. /**
  1299. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1300. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1301. */
  1302. var KeyboardInfoPre = /** @class */ (function (_super) {
  1303. __extends(KeyboardInfoPre, _super);
  1304. function KeyboardInfoPre(type, event) {
  1305. var _this = _super.call(this, type, event) || this;
  1306. _this.skipOnPointerObservable = false;
  1307. return _this;
  1308. }
  1309. return KeyboardInfoPre;
  1310. }(KeyboardInfo));
  1311. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1312. })(BABYLON || (BABYLON = {}));
  1313. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1314. var BABYLON;
  1315. (function (BABYLON) {
  1316. var PointerEventTypes = /** @class */ (function () {
  1317. function PointerEventTypes() {
  1318. }
  1319. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1320. get: function () {
  1321. return PointerEventTypes._POINTERDOWN;
  1322. },
  1323. enumerable: true,
  1324. configurable: true
  1325. });
  1326. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1327. get: function () {
  1328. return PointerEventTypes._POINTERUP;
  1329. },
  1330. enumerable: true,
  1331. configurable: true
  1332. });
  1333. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1334. get: function () {
  1335. return PointerEventTypes._POINTERMOVE;
  1336. },
  1337. enumerable: true,
  1338. configurable: true
  1339. });
  1340. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1341. get: function () {
  1342. return PointerEventTypes._POINTERWHEEL;
  1343. },
  1344. enumerable: true,
  1345. configurable: true
  1346. });
  1347. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1348. get: function () {
  1349. return PointerEventTypes._POINTERPICK;
  1350. },
  1351. enumerable: true,
  1352. configurable: true
  1353. });
  1354. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1355. get: function () {
  1356. return PointerEventTypes._POINTERTAP;
  1357. },
  1358. enumerable: true,
  1359. configurable: true
  1360. });
  1361. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1362. get: function () {
  1363. return PointerEventTypes._POINTERDOUBLETAP;
  1364. },
  1365. enumerable: true,
  1366. configurable: true
  1367. });
  1368. PointerEventTypes._POINTERDOWN = 0x01;
  1369. PointerEventTypes._POINTERUP = 0x02;
  1370. PointerEventTypes._POINTERMOVE = 0x04;
  1371. PointerEventTypes._POINTERWHEEL = 0x08;
  1372. PointerEventTypes._POINTERPICK = 0x10;
  1373. PointerEventTypes._POINTERTAP = 0x20;
  1374. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1375. return PointerEventTypes;
  1376. }());
  1377. BABYLON.PointerEventTypes = PointerEventTypes;
  1378. var PointerInfoBase = /** @class */ (function () {
  1379. function PointerInfoBase(type, event) {
  1380. this.type = type;
  1381. this.event = event;
  1382. }
  1383. return PointerInfoBase;
  1384. }());
  1385. BABYLON.PointerInfoBase = PointerInfoBase;
  1386. /**
  1387. * This class is used to store pointer related info for the onPrePointerObservable event.
  1388. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1389. */
  1390. var PointerInfoPre = /** @class */ (function (_super) {
  1391. __extends(PointerInfoPre, _super);
  1392. function PointerInfoPre(type, event, localX, localY) {
  1393. var _this = _super.call(this, type, event) || this;
  1394. /**
  1395. * Ray from a pointer if availible (eg. 6dof controller)
  1396. */
  1397. _this.ray = null;
  1398. _this.skipOnPointerObservable = false;
  1399. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1400. return _this;
  1401. }
  1402. return PointerInfoPre;
  1403. }(PointerInfoBase));
  1404. BABYLON.PointerInfoPre = PointerInfoPre;
  1405. /**
  1406. * This type contains all the data related to a pointer event in Babylon.js.
  1407. * 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.
  1408. */
  1409. var PointerInfo = /** @class */ (function (_super) {
  1410. __extends(PointerInfo, _super);
  1411. function PointerInfo(type, event, pickInfo) {
  1412. var _this = _super.call(this, type, event) || this;
  1413. _this.pickInfo = pickInfo;
  1414. return _this;
  1415. }
  1416. return PointerInfo;
  1417. }(PointerInfoBase));
  1418. BABYLON.PointerInfo = PointerInfo;
  1419. })(BABYLON || (BABYLON = {}));
  1420. //# sourceMappingURL=babylon.pointerEvents.js.map
  1421. var BABYLON;
  1422. (function (BABYLON) {
  1423. BABYLON.ToGammaSpace = 1 / 2.2;
  1424. BABYLON.ToLinearSpace = 2.2;
  1425. BABYLON.Epsilon = 0.001;
  1426. /**
  1427. * Class used to hold a RBG color
  1428. */
  1429. var Color3 = /** @class */ (function () {
  1430. /**
  1431. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1432. * @param r defines the red component (between 0 and 1, default is 0)
  1433. * @param g defines the green component (between 0 and 1, default is 0)
  1434. * @param b defines the blue component (between 0 and 1, default is 0)
  1435. */
  1436. function Color3(
  1437. /**
  1438. * Defines the red component (between 0 and 1, default is 0)
  1439. */
  1440. r,
  1441. /**
  1442. * Defines the green component (between 0 and 1, default is 0)
  1443. */
  1444. g,
  1445. /**
  1446. * Defines the blue component (between 0 and 1, default is 0)
  1447. */
  1448. b) {
  1449. if (r === void 0) { r = 0; }
  1450. if (g === void 0) { g = 0; }
  1451. if (b === void 0) { b = 0; }
  1452. this.r = r;
  1453. this.g = g;
  1454. this.b = b;
  1455. }
  1456. /**
  1457. * Creates a string with the Color3 current values
  1458. * @returns the string representation of the Color3 object
  1459. */
  1460. Color3.prototype.toString = function () {
  1461. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1462. };
  1463. /**
  1464. * Returns the string "Color3"
  1465. * @returns "Color3"
  1466. */
  1467. Color3.prototype.getClassName = function () {
  1468. return "Color3";
  1469. };
  1470. /**
  1471. * Compute the Color3 hash code
  1472. * @returns an unique number that can be used to hash Color3 objects
  1473. */
  1474. Color3.prototype.getHashCode = function () {
  1475. var hash = this.r || 0;
  1476. hash = (hash * 397) ^ (this.g || 0);
  1477. hash = (hash * 397) ^ (this.b || 0);
  1478. return hash;
  1479. };
  1480. // Operators
  1481. /**
  1482. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1483. * @param array defines the array where to store the r,g,b components
  1484. * @param index defines an optional index in the target array to define where to start storing values
  1485. * @returns the current Color3 object
  1486. */
  1487. Color3.prototype.toArray = function (array, index) {
  1488. if (index === undefined) {
  1489. index = 0;
  1490. }
  1491. array[index] = this.r;
  1492. array[index + 1] = this.g;
  1493. array[index + 2] = this.b;
  1494. return this;
  1495. };
  1496. /**
  1497. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1498. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1499. * @returns a new {BABYLON.Color4} object
  1500. */
  1501. Color3.prototype.toColor4 = function (alpha) {
  1502. if (alpha === void 0) { alpha = 1; }
  1503. return new Color4(this.r, this.g, this.b, alpha);
  1504. };
  1505. /**
  1506. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1507. * @returns the new array
  1508. */
  1509. Color3.prototype.asArray = function () {
  1510. var result = new Array();
  1511. this.toArray(result, 0);
  1512. return result;
  1513. };
  1514. /**
  1515. * Returns the luminance value
  1516. * @returns a float value
  1517. */
  1518. Color3.prototype.toLuminance = function () {
  1519. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1520. };
  1521. /**
  1522. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1523. * @param otherColor defines the second operand
  1524. * @returns the new Color3 object
  1525. */
  1526. Color3.prototype.multiply = function (otherColor) {
  1527. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1528. };
  1529. /**
  1530. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1531. * @param otherColor defines the second operand
  1532. * @param result defines the Color3 object where to store the result
  1533. * @returns the current Color3
  1534. */
  1535. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1536. result.r = this.r * otherColor.r;
  1537. result.g = this.g * otherColor.g;
  1538. result.b = this.b * otherColor.b;
  1539. return this;
  1540. };
  1541. /**
  1542. * Determines equality between Color3 objects
  1543. * @param otherColor defines the second operand
  1544. * @returns true if the rgb values are equal to the given ones
  1545. */
  1546. Color3.prototype.equals = function (otherColor) {
  1547. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1548. };
  1549. /**
  1550. * Determines equality between the current Color3 object and a set of r,b,g values
  1551. * @param r defines the red component to check
  1552. * @param g defines the green component to check
  1553. * @param b defines the blue component to check
  1554. * @returns true if the rgb values are equal to the given ones
  1555. */
  1556. Color3.prototype.equalsFloats = function (r, g, b) {
  1557. return this.r === r && this.g === g && this.b === b;
  1558. };
  1559. /**
  1560. * Multiplies in place each rgb value by scale
  1561. * @param scale defines the scaling factor
  1562. * @returns the updated Color3
  1563. */
  1564. Color3.prototype.scale = function (scale) {
  1565. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1566. };
  1567. /**
  1568. * Multiplies the rgb values by scale and stores the result into "result"
  1569. * @param scale defines the scaling factor
  1570. * @param result defines the Color3 object where to store the result
  1571. * @returns the unmodified current Color3
  1572. */
  1573. Color3.prototype.scaleToRef = function (scale, result) {
  1574. result.r = this.r * scale;
  1575. result.g = this.g * scale;
  1576. result.b = this.b * scale;
  1577. return this;
  1578. };
  1579. /**
  1580. * Scale the current Color3 values by a factor and add the result to a given Color3
  1581. * @param scale defines the scale factor
  1582. * @param result defines color to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1586. result.r += this.r * scale;
  1587. result.g += this.g * scale;
  1588. result.b += this.b * scale;
  1589. return this;
  1590. };
  1591. /**
  1592. * Clamps the rgb values by the min and max values and stores the result into "result"
  1593. * @param min defines minimum clamping value (default is 0)
  1594. * @param max defines maximum clamping value (default is 1)
  1595. * @param result defines color to store the result into
  1596. * @returns the original Color3
  1597. */
  1598. Color3.prototype.clampToRef = function (min, max, result) {
  1599. if (min === void 0) { min = 0; }
  1600. if (max === void 0) { max = 1; }
  1601. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1602. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1603. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1604. return this;
  1605. };
  1606. /**
  1607. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1608. * @param otherColor defines the second operand
  1609. * @returns the new Color3
  1610. */
  1611. Color3.prototype.add = function (otherColor) {
  1612. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1613. };
  1614. /**
  1615. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1616. * @param otherColor defines the second operand
  1617. * @param result defines Color3 object to store the result into
  1618. * @returns the unmodified current Color3
  1619. */
  1620. Color3.prototype.addToRef = function (otherColor, result) {
  1621. result.r = this.r + otherColor.r;
  1622. result.g = this.g + otherColor.g;
  1623. result.b = this.b + otherColor.b;
  1624. return this;
  1625. };
  1626. /**
  1627. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1628. * @param otherColor defines the second operand
  1629. * @returns the new Color3
  1630. */
  1631. Color3.prototype.subtract = function (otherColor) {
  1632. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1633. };
  1634. /**
  1635. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1636. * @param otherColor defines the second operand
  1637. * @param result defines Color3 object to store the result into
  1638. * @returns the unmodified current Color3
  1639. */
  1640. Color3.prototype.subtractToRef = function (otherColor, result) {
  1641. result.r = this.r - otherColor.r;
  1642. result.g = this.g - otherColor.g;
  1643. result.b = this.b - otherColor.b;
  1644. return this;
  1645. };
  1646. /**
  1647. * Copy the current object
  1648. * @returns a new Color3 copied the current one
  1649. */
  1650. Color3.prototype.clone = function () {
  1651. return new Color3(this.r, this.g, this.b);
  1652. };
  1653. /**
  1654. * Copies the rgb values from the source in the current Color3
  1655. * @param source defines the source Color3 object
  1656. * @returns the updated Color3 object
  1657. */
  1658. Color3.prototype.copyFrom = function (source) {
  1659. this.r = source.r;
  1660. this.g = source.g;
  1661. this.b = source.b;
  1662. return this;
  1663. };
  1664. /**
  1665. * Updates the Color3 rgb values from the given floats
  1666. * @param r defines the red component to read from
  1667. * @param g defines the green component to read from
  1668. * @param b defines the blue component to read from
  1669. * @returns the current Color3 object
  1670. */
  1671. Color3.prototype.copyFromFloats = function (r, g, b) {
  1672. this.r = r;
  1673. this.g = g;
  1674. this.b = b;
  1675. return this;
  1676. };
  1677. /**
  1678. * Updates the Color3 rgb values from the given floats
  1679. * @param r defines the red component to read from
  1680. * @param g defines the green component to read from
  1681. * @param b defines the blue component to read from
  1682. * @returns the current Color3 object
  1683. */
  1684. Color3.prototype.set = function (r, g, b) {
  1685. return this.copyFromFloats(r, g, b);
  1686. };
  1687. /**
  1688. * Compute the Color3 hexadecimal code as a string
  1689. * @returns a string containing the hexadecimal representation of the Color3 object
  1690. */
  1691. Color3.prototype.toHexString = function () {
  1692. var intR = (this.r * 255) | 0;
  1693. var intG = (this.g * 255) | 0;
  1694. var intB = (this.b * 255) | 0;
  1695. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1696. };
  1697. /**
  1698. * Computes a new Color3 converted from the current one to linear space
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.prototype.toLinearSpace = function () {
  1702. var convertedColor = new Color3();
  1703. this.toLinearSpaceToRef(convertedColor);
  1704. return convertedColor;
  1705. };
  1706. /**
  1707. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1708. * @param convertedColor defines the Color3 object where to store the linear space version
  1709. * @returns the unmodified Color3
  1710. */
  1711. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1712. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1713. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1714. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1715. return this;
  1716. };
  1717. /**
  1718. * Computes a new Color3 converted from the current one to gamma space
  1719. * @returns a new Color3 object
  1720. */
  1721. Color3.prototype.toGammaSpace = function () {
  1722. var convertedColor = new Color3();
  1723. this.toGammaSpaceToRef(convertedColor);
  1724. return convertedColor;
  1725. };
  1726. /**
  1727. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1728. * @param convertedColor defines the Color3 object where to store the gamma space version
  1729. * @returns the unmodified Color3
  1730. */
  1731. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1732. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1733. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1734. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1735. return this;
  1736. };
  1737. // Statics
  1738. /**
  1739. * Creates a new Color3 from the string containing valid hexadecimal values
  1740. * @param hex defines a string containing valid hexadecimal values
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromHexString = function (hex) {
  1744. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1745. return new Color3(0, 0, 0);
  1746. }
  1747. var r = parseInt(hex.substring(1, 3), 16);
  1748. var g = parseInt(hex.substring(3, 5), 16);
  1749. var b = parseInt(hex.substring(5, 7), 16);
  1750. return Color3.FromInts(r, g, b);
  1751. };
  1752. /**
  1753. * Creates a new Vector3 from the starting index of the given array
  1754. * @param array defines the source array
  1755. * @param offset defines an offset in the source array
  1756. * @returns a new Color3 object
  1757. */
  1758. Color3.FromArray = function (array, offset) {
  1759. if (offset === void 0) { offset = 0; }
  1760. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1761. };
  1762. /**
  1763. * Creates a new Color3 from integer values (< 256)
  1764. * @param r defines the red component to read from (value between 0 and 255)
  1765. * @param g defines the green component to read from (value between 0 and 255)
  1766. * @param b defines the blue component to read from (value between 0 and 255)
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.FromInts = function (r, g, b) {
  1770. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1771. };
  1772. /**
  1773. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1774. * @param start defines the start Color3 value
  1775. * @param end defines the end Color3 value
  1776. * @param amount defines the gradient value between start and end
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Lerp = function (start, end, amount) {
  1780. var result = new Color3(0.0, 0.0, 0.0);
  1781. Color3.LerpToRef(start, end, amount, result);
  1782. return result;
  1783. };
  1784. /**
  1785. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1786. * @param left defines the start value
  1787. * @param right defines the end value
  1788. * @param amount defines the gradient factor
  1789. * @param result defines the Color3 object where to store the result
  1790. */
  1791. Color3.LerpToRef = function (left, right, amount, result) {
  1792. result.r = left.r + ((right.r - left.r) * amount);
  1793. result.g = left.g + ((right.g - left.g) * amount);
  1794. result.b = left.b + ((right.b - left.b) * amount);
  1795. };
  1796. /**
  1797. * Returns a Color3 value containing a red color
  1798. * @returns a new Color3 object
  1799. */
  1800. Color3.Red = function () { return new Color3(1, 0, 0); };
  1801. /**
  1802. * Returns a Color3 value containing a green color
  1803. * @returns a new Color3 object
  1804. */
  1805. Color3.Green = function () { return new Color3(0, 1, 0); };
  1806. /**
  1807. * Returns a Color3 value containing a blue color
  1808. * @returns a new Color3 object
  1809. */
  1810. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1811. /**
  1812. * Returns a Color3 value containing a black color
  1813. * @returns a new Color3 object
  1814. */
  1815. Color3.Black = function () { return new Color3(0, 0, 0); };
  1816. /**
  1817. * Returns a Color3 value containing a white color
  1818. * @returns a new Color3 object
  1819. */
  1820. Color3.White = function () { return new Color3(1, 1, 1); };
  1821. /**
  1822. * Returns a Color3 value containing a purple color
  1823. * @returns a new Color3 object
  1824. */
  1825. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1826. /**
  1827. * Returns a Color3 value containing a magenta color
  1828. * @returns a new Color3 object
  1829. */
  1830. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1831. /**
  1832. * Returns a Color3 value containing a yellow color
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1836. /**
  1837. * Returns a Color3 value containing a gray color
  1838. * @returns a new Color3 object
  1839. */
  1840. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1841. /**
  1842. * Returns a Color3 value containing a teal color
  1843. * @returns a new Color3 object
  1844. */
  1845. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1846. /**
  1847. * Returns a Color3 value containing a random color
  1848. * @returns a new Color3 object
  1849. */
  1850. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1851. return Color3;
  1852. }());
  1853. BABYLON.Color3 = Color3;
  1854. /**
  1855. * Class used to hold a RBGA color
  1856. */
  1857. var Color4 = /** @class */ (function () {
  1858. /**
  1859. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1860. * @param r defines the red component (between 0 and 1, default is 0)
  1861. * @param g defines the green component (between 0 and 1, default is 0)
  1862. * @param b defines the blue component (between 0 and 1, default is 0)
  1863. * @param a defines the alpha component (between 0 and 1, default is 1)
  1864. */
  1865. function Color4(
  1866. /**
  1867. * Defines the red component (between 0 and 1, default is 0)
  1868. */
  1869. r,
  1870. /**
  1871. * Defines the green component (between 0 and 1, default is 0)
  1872. */
  1873. g,
  1874. /**
  1875. * Defines the blue component (between 0 and 1, default is 0)
  1876. */
  1877. b,
  1878. /**
  1879. * Defines the alpha component (between 0 and 1, default is 1)
  1880. */
  1881. a) {
  1882. if (r === void 0) { r = 0; }
  1883. if (g === void 0) { g = 0; }
  1884. if (b === void 0) { b = 0; }
  1885. if (a === void 0) { a = 1; }
  1886. this.r = r;
  1887. this.g = g;
  1888. this.b = b;
  1889. this.a = a;
  1890. }
  1891. // Operators
  1892. /**
  1893. * Adds in place the given Color4 values to the current Color4 object
  1894. * @param right defines the second operand
  1895. * @returns the current updated Color4 object
  1896. */
  1897. Color4.prototype.addInPlace = function (right) {
  1898. this.r += right.r;
  1899. this.g += right.g;
  1900. this.b += right.b;
  1901. this.a += right.a;
  1902. return this;
  1903. };
  1904. /**
  1905. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1906. * @returns the new array
  1907. */
  1908. Color4.prototype.asArray = function () {
  1909. var result = new Array();
  1910. this.toArray(result, 0);
  1911. return result;
  1912. };
  1913. /**
  1914. * Stores from the starting index in the given array the Color4 successive values
  1915. * @param array defines the array where to store the r,g,b components
  1916. * @param index defines an optional index in the target array to define where to start storing values
  1917. * @returns the current Color4 object
  1918. */
  1919. Color4.prototype.toArray = function (array, index) {
  1920. if (index === undefined) {
  1921. index = 0;
  1922. }
  1923. array[index] = this.r;
  1924. array[index + 1] = this.g;
  1925. array[index + 2] = this.b;
  1926. array[index + 3] = this.a;
  1927. return this;
  1928. };
  1929. /**
  1930. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1931. * @param right defines the second operand
  1932. * @returns a new Color4 object
  1933. */
  1934. Color4.prototype.add = function (right) {
  1935. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1936. };
  1937. /**
  1938. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1939. * @param right defines the second operand
  1940. * @returns a new Color4 object
  1941. */
  1942. Color4.prototype.subtract = function (right) {
  1943. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1944. };
  1945. /**
  1946. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1947. * @param right defines the second operand
  1948. * @param result defines the Color4 object where to store the result
  1949. * @returns the current Color4 object
  1950. */
  1951. Color4.prototype.subtractToRef = function (right, result) {
  1952. result.r = this.r - right.r;
  1953. result.g = this.g - right.g;
  1954. result.b = this.b - right.b;
  1955. result.a = this.a - right.a;
  1956. return this;
  1957. };
  1958. /**
  1959. * Creates a new Color4 with the current Color4 values multiplied by scale
  1960. * @param scale defines the scaling factor to apply
  1961. * @returns a new Color4 object
  1962. */
  1963. Color4.prototype.scale = function (scale) {
  1964. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1965. };
  1966. /**
  1967. * Multiplies the current Color4 values by scale and stores the result in "result"
  1968. * @param scale defines the scaling factor to apply
  1969. * @param result defines the Color4 object where to store the result
  1970. * @returns the current unmodified Color4
  1971. */
  1972. Color4.prototype.scaleToRef = function (scale, result) {
  1973. result.r = this.r * scale;
  1974. result.g = this.g * scale;
  1975. result.b = this.b * scale;
  1976. result.a = this.a * scale;
  1977. return this;
  1978. };
  1979. /**
  1980. * Scale the current Color4 values by a factor and add the result to a given Color4
  1981. * @param scale defines the scale factor
  1982. * @param result defines the Color4 object where to store the result
  1983. * @returns the unmodified current Color4
  1984. */
  1985. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1986. result.r += this.r * scale;
  1987. result.g += this.g * scale;
  1988. result.b += this.b * scale;
  1989. result.a += this.a * scale;
  1990. return this;
  1991. };
  1992. /**
  1993. * Clamps the rgb values by the min and max values and stores the result into "result"
  1994. * @param min defines minimum clamping value (default is 0)
  1995. * @param max defines maximum clamping value (default is 1)
  1996. * @param result defines color to store the result into.
  1997. * @returns the cuurent Color4
  1998. */
  1999. Color4.prototype.clampToRef = function (min, max, result) {
  2000. if (min === void 0) { min = 0; }
  2001. if (max === void 0) { max = 1; }
  2002. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2003. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2004. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2005. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2006. return this;
  2007. };
  2008. /**
  2009. * Multipy an Color4 value by another and return a new Color4 object
  2010. * @param color defines the Color4 value to multiply by
  2011. * @returns a new Color4 object
  2012. */
  2013. Color4.prototype.multiply = function (color) {
  2014. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2015. };
  2016. /**
  2017. * Multipy a Color4 value by another and push the result in a reference value
  2018. * @param color defines the Color4 value to multiply by
  2019. * @param result defines the Color4 to fill the result in
  2020. * @returns the result Color4
  2021. */
  2022. Color4.prototype.multiplyToRef = function (color, result) {
  2023. result.r = this.r * color.r;
  2024. result.g = this.g * color.g;
  2025. result.b = this.b * color.b;
  2026. result.a = this.a * color.a;
  2027. return result;
  2028. };
  2029. /**
  2030. * Creates a string with the Color4 current values
  2031. * @returns the string representation of the Color4 object
  2032. */
  2033. Color4.prototype.toString = function () {
  2034. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2035. };
  2036. /**
  2037. * Returns the string "Color4"
  2038. * @returns "Color4"
  2039. */
  2040. Color4.prototype.getClassName = function () {
  2041. return "Color4";
  2042. };
  2043. /**
  2044. * Compute the Color4 hash code
  2045. * @returns an unique number that can be used to hash Color4 objects
  2046. */
  2047. Color4.prototype.getHashCode = function () {
  2048. var hash = this.r || 0;
  2049. hash = (hash * 397) ^ (this.g || 0);
  2050. hash = (hash * 397) ^ (this.b || 0);
  2051. hash = (hash * 397) ^ (this.a || 0);
  2052. return hash;
  2053. };
  2054. /**
  2055. * Creates a new Color4 copied from the current one
  2056. * @returns a new Color4 object
  2057. */
  2058. Color4.prototype.clone = function () {
  2059. return new Color4(this.r, this.g, this.b, this.a);
  2060. };
  2061. /**
  2062. * Copies the given Color4 values into the current one
  2063. * @param source defines the source Color4 object
  2064. * @returns the current updated Color4 object
  2065. */
  2066. Color4.prototype.copyFrom = function (source) {
  2067. this.r = source.r;
  2068. this.g = source.g;
  2069. this.b = source.b;
  2070. this.a = source.a;
  2071. return this;
  2072. };
  2073. /**
  2074. * Copies the given float values into the current one
  2075. * @param r defines the red component to read from
  2076. * @param g defines the green component to read from
  2077. * @param b defines the blue component to read from
  2078. * @param a defines the alpha component to read from
  2079. * @returns the current updated Color4 object
  2080. */
  2081. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2082. this.r = r;
  2083. this.g = g;
  2084. this.b = b;
  2085. this.a = a;
  2086. return this;
  2087. };
  2088. /**
  2089. * Copies the given float values into the current one
  2090. * @param r defines the red component to read from
  2091. * @param g defines the green component to read from
  2092. * @param b defines the blue component to read from
  2093. * @param a defines the alpha component to read from
  2094. * @returns the current updated Color4 object
  2095. */
  2096. Color4.prototype.set = function (r, g, b, a) {
  2097. return this.copyFromFloats(r, g, b, a);
  2098. };
  2099. /**
  2100. * Compute the Color4 hexadecimal code as a string
  2101. * @returns a string containing the hexadecimal representation of the Color4 object
  2102. */
  2103. Color4.prototype.toHexString = function () {
  2104. var intR = (this.r * 255) | 0;
  2105. var intG = (this.g * 255) | 0;
  2106. var intB = (this.b * 255) | 0;
  2107. var intA = (this.a * 255) | 0;
  2108. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2109. };
  2110. /**
  2111. * Computes a new Color4 converted from the current one to linear space
  2112. * @returns a new Color4 object
  2113. */
  2114. Color4.prototype.toLinearSpace = function () {
  2115. var convertedColor = new Color4();
  2116. this.toLinearSpaceToRef(convertedColor);
  2117. return convertedColor;
  2118. };
  2119. /**
  2120. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2121. * @param convertedColor defines the Color4 object where to store the linear space version
  2122. * @returns the unmodified Color4
  2123. */
  2124. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2125. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2126. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2127. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2128. convertedColor.a = this.a;
  2129. return this;
  2130. };
  2131. /**
  2132. * Computes a new Color4 converted from the current one to gamma space
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.prototype.toGammaSpace = function () {
  2136. var convertedColor = new Color4();
  2137. this.toGammaSpaceToRef(convertedColor);
  2138. return convertedColor;
  2139. };
  2140. /**
  2141. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2142. * @param convertedColor defines the Color4 object where to store the gamma space version
  2143. * @returns the unmodified Color4
  2144. */
  2145. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2146. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2147. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2148. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2149. convertedColor.a = this.a;
  2150. return this;
  2151. };
  2152. // Statics
  2153. /**
  2154. * Creates a new Color4 from the string containing valid hexadecimal values
  2155. * @param hex defines a string containing valid hexadecimal values
  2156. * @returns a new Color4 object
  2157. */
  2158. Color4.FromHexString = function (hex) {
  2159. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2160. return new Color4(0.0, 0.0, 0.0, 0.0);
  2161. }
  2162. var r = parseInt(hex.substring(1, 3), 16);
  2163. var g = parseInt(hex.substring(3, 5), 16);
  2164. var b = parseInt(hex.substring(5, 7), 16);
  2165. var a = parseInt(hex.substring(7, 9), 16);
  2166. return Color4.FromInts(r, g, b, a);
  2167. };
  2168. /**
  2169. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2170. * @param left defines the start value
  2171. * @param right defines the end value
  2172. * @param amount defines the gradient factor
  2173. * @returns a new Color4 object
  2174. */
  2175. Color4.Lerp = function (left, right, amount) {
  2176. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2177. Color4.LerpToRef(left, right, amount, result);
  2178. return result;
  2179. };
  2180. /**
  2181. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2182. * @param left defines the start value
  2183. * @param right defines the end value
  2184. * @param amount defines the gradient factor
  2185. * @param result defines the Color4 object where to store data
  2186. */
  2187. Color4.LerpToRef = function (left, right, amount, result) {
  2188. result.r = left.r + (right.r - left.r) * amount;
  2189. result.g = left.g + (right.g - left.g) * amount;
  2190. result.b = left.b + (right.b - left.b) * amount;
  2191. result.a = left.a + (right.a - left.a) * amount;
  2192. };
  2193. /**
  2194. * Creates a new Color4 from a Color3 and an alpha value
  2195. * @param color3 defines the source Color3 to read from
  2196. * @param alpha defines the alpha component (1.0 by default)
  2197. * @returns a new Color4 object
  2198. */
  2199. Color4.FromColor3 = function (color3, alpha) {
  2200. if (alpha === void 0) { alpha = 1.0; }
  2201. return new Color4(color3.r, color3.g, color3.b, alpha);
  2202. };
  2203. /**
  2204. * Creates a new Color4 from the starting index element of the given array
  2205. * @param array defines the source array to read from
  2206. * @param offset defines the offset in the source array
  2207. * @returns a new Color4 object
  2208. */
  2209. Color4.FromArray = function (array, offset) {
  2210. if (offset === void 0) { offset = 0; }
  2211. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2212. };
  2213. /**
  2214. * Creates a new Color3 from integer values (< 256)
  2215. * @param r defines the red component to read from (value between 0 and 255)
  2216. * @param g defines the green component to read from (value between 0 and 255)
  2217. * @param b defines the blue component to read from (value between 0 and 255)
  2218. * @param a defines the alpha component to read from (value between 0 and 255)
  2219. * @returns a new Color3 object
  2220. */
  2221. Color4.FromInts = function (r, g, b, a) {
  2222. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2223. };
  2224. /**
  2225. * Check the content of a given array and convert it to an array containing RGBA data
  2226. * If the original array was already containing count * 4 values then it is returned directly
  2227. * @param colors defines the array to check
  2228. * @param count defines the number of RGBA data to expect
  2229. * @returns an array containing count * 4 values (RGBA)
  2230. */
  2231. Color4.CheckColors4 = function (colors, count) {
  2232. // Check if color3 was used
  2233. if (colors.length === count * 3) {
  2234. var colors4 = [];
  2235. for (var index = 0; index < colors.length; index += 3) {
  2236. var newIndex = (index / 3) * 4;
  2237. colors4[newIndex] = colors[index];
  2238. colors4[newIndex + 1] = colors[index + 1];
  2239. colors4[newIndex + 2] = colors[index + 2];
  2240. colors4[newIndex + 3] = 1.0;
  2241. }
  2242. return colors4;
  2243. }
  2244. return colors;
  2245. };
  2246. return Color4;
  2247. }());
  2248. BABYLON.Color4 = Color4;
  2249. /**
  2250. * Class representing a vector containing 2 coordinates
  2251. */
  2252. var Vector2 = /** @class */ (function () {
  2253. /**
  2254. * Creates a new Vector2 from the given x and y coordinates
  2255. * @param x defines the first coordinate
  2256. * @param y defines the second coordinate
  2257. */
  2258. function Vector2(
  2259. /** defines the first coordinate */
  2260. x,
  2261. /** defines the second coordinate */
  2262. y) {
  2263. if (x === void 0) { x = 0; }
  2264. if (y === void 0) { y = 0; }
  2265. this.x = x;
  2266. this.y = y;
  2267. }
  2268. /**
  2269. * Gets a string with the Vector2 coordinates
  2270. * @returns a string with the Vector2 coordinates
  2271. */
  2272. Vector2.prototype.toString = function () {
  2273. return "{X: " + this.x + " Y:" + this.y + "}";
  2274. };
  2275. /**
  2276. * Gets class name
  2277. * @returns the string "Vector2"
  2278. */
  2279. Vector2.prototype.getClassName = function () {
  2280. return "Vector2";
  2281. };
  2282. /**
  2283. * Gets current vector hash code
  2284. * @returns the Vector2 hash code as a number
  2285. */
  2286. Vector2.prototype.getHashCode = function () {
  2287. var hash = this.x || 0;
  2288. hash = (hash * 397) ^ (this.y || 0);
  2289. return hash;
  2290. };
  2291. // Operators
  2292. /**
  2293. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2294. * @param array defines the source array
  2295. * @param index defines the offset in source array
  2296. * @returns the current Vector2
  2297. */
  2298. Vector2.prototype.toArray = function (array, index) {
  2299. if (index === void 0) { index = 0; }
  2300. array[index] = this.x;
  2301. array[index + 1] = this.y;
  2302. return this;
  2303. };
  2304. /**
  2305. * Copy the current vector to an array
  2306. * @returns a new array with 2 elements: the Vector2 coordinates.
  2307. */
  2308. Vector2.prototype.asArray = function () {
  2309. var result = new Array();
  2310. this.toArray(result, 0);
  2311. return result;
  2312. };
  2313. /**
  2314. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2315. * @param source defines the source Vector2
  2316. * @returns the current updated Vector2
  2317. */
  2318. Vector2.prototype.copyFrom = function (source) {
  2319. this.x = source.x;
  2320. this.y = source.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Sets the Vector2 coordinates with the given floats
  2325. * @param x defines the first coordinate
  2326. * @param y defines the second coordinate
  2327. * @returns the current updated Vector2
  2328. */
  2329. Vector2.prototype.copyFromFloats = function (x, y) {
  2330. this.x = x;
  2331. this.y = y;
  2332. return this;
  2333. };
  2334. /**
  2335. * Sets the Vector2 coordinates with the given floats
  2336. * @param x defines the first coordinate
  2337. * @param y defines the second coordinate
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.set = function (x, y) {
  2341. return this.copyFromFloats(x, y);
  2342. };
  2343. /**
  2344. * Add another vector with the current one
  2345. * @param otherVector defines the other vector
  2346. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2347. */
  2348. Vector2.prototype.add = function (otherVector) {
  2349. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2350. };
  2351. /**
  2352. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2353. * @param otherVector defines the other vector
  2354. * @param result defines the target vector
  2355. * @returns the unmodified current Vector2
  2356. */
  2357. Vector2.prototype.addToRef = function (otherVector, result) {
  2358. result.x = this.x + otherVector.x;
  2359. result.y = this.y + otherVector.y;
  2360. return this;
  2361. };
  2362. /**
  2363. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2364. * @param otherVector defines the other vector
  2365. * @returns the current updated Vector2
  2366. */
  2367. Vector2.prototype.addInPlace = function (otherVector) {
  2368. this.x += otherVector.x;
  2369. this.y += otherVector.y;
  2370. return this;
  2371. };
  2372. /**
  2373. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2374. * @param otherVector defines the other vector
  2375. * @returns a new Vector2
  2376. */
  2377. Vector2.prototype.addVector3 = function (otherVector) {
  2378. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2379. };
  2380. /**
  2381. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2382. * @param otherVector defines the other vector
  2383. * @returns a new Vector2
  2384. */
  2385. Vector2.prototype.subtract = function (otherVector) {
  2386. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2387. };
  2388. /**
  2389. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2390. * @param otherVector defines the other vector
  2391. * @param result defines the target vector
  2392. * @returns the unmodified current Vector2
  2393. */
  2394. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2395. result.x = this.x - otherVector.x;
  2396. result.y = this.y - otherVector.y;
  2397. return this;
  2398. };
  2399. /**
  2400. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2401. * @param otherVector defines the other vector
  2402. * @returns the current updated Vector2
  2403. */
  2404. Vector2.prototype.subtractInPlace = function (otherVector) {
  2405. this.x -= otherVector.x;
  2406. this.y -= otherVector.y;
  2407. return this;
  2408. };
  2409. /**
  2410. * Multiplies in place the current Vector2 coordinates by the given ones
  2411. * @param otherVector defines the other vector
  2412. * @returns the current updated Vector2
  2413. */
  2414. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2415. this.x *= otherVector.x;
  2416. this.y *= otherVector.y;
  2417. return this;
  2418. };
  2419. /**
  2420. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2421. * @param otherVector defines the other vector
  2422. * @returns a new Vector2
  2423. */
  2424. Vector2.prototype.multiply = function (otherVector) {
  2425. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2426. };
  2427. /**
  2428. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2429. * @param otherVector defines the other vector
  2430. * @param result defines the target vector
  2431. * @returns the unmodified current Vector2
  2432. */
  2433. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2434. result.x = this.x * otherVector.x;
  2435. result.y = this.y * otherVector.y;
  2436. return this;
  2437. };
  2438. /**
  2439. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2440. * @param x defines the first coordinate
  2441. * @param y defines the second coordinate
  2442. * @returns a new Vector2
  2443. */
  2444. Vector2.prototype.multiplyByFloats = function (x, y) {
  2445. return new Vector2(this.x * x, this.y * y);
  2446. };
  2447. /**
  2448. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2449. * @param otherVector defines the other vector
  2450. * @returns a new Vector2
  2451. */
  2452. Vector2.prototype.divide = function (otherVector) {
  2453. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2454. };
  2455. /**
  2456. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2457. * @param otherVector defines the other vector
  2458. * @param result defines the target vector
  2459. * @returns the unmodified current Vector2
  2460. */
  2461. Vector2.prototype.divideToRef = function (otherVector, result) {
  2462. result.x = this.x / otherVector.x;
  2463. result.y = this.y / otherVector.y;
  2464. return this;
  2465. };
  2466. /**
  2467. * Divides the current Vector2 coordinates by the given ones
  2468. * @param otherVector defines the other vector
  2469. * @returns the current updated Vector2
  2470. */
  2471. Vector2.prototype.divideInPlace = function (otherVector) {
  2472. return this.divideToRef(otherVector, this);
  2473. };
  2474. /**
  2475. * Gets a new Vector2 with current Vector2 negated coordinates
  2476. * @returns a new Vector2
  2477. */
  2478. Vector2.prototype.negate = function () {
  2479. return new Vector2(-this.x, -this.y);
  2480. };
  2481. /**
  2482. * Multiply the Vector2 coordinates by scale
  2483. * @param scale defines the scaling factor
  2484. * @returns the current updated Vector2
  2485. */
  2486. Vector2.prototype.scaleInPlace = function (scale) {
  2487. this.x *= scale;
  2488. this.y *= scale;
  2489. return this;
  2490. };
  2491. /**
  2492. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2493. * @param scale defines the scaling factor
  2494. * @returns a new Vector2
  2495. */
  2496. Vector2.prototype.scale = function (scale) {
  2497. var result = new Vector2(0, 0);
  2498. this.scaleToRef(scale, result);
  2499. return result;
  2500. };
  2501. /**
  2502. * Scale the current Vector2 values by a factor to a given Vector2
  2503. * @param scale defines the scale factor
  2504. * @param result defines the Vector2 object where to store the result
  2505. * @returns the unmodified current Vector2
  2506. */
  2507. Vector2.prototype.scaleToRef = function (scale, result) {
  2508. result.x = this.x * scale;
  2509. result.y = this.y * scale;
  2510. return this;
  2511. };
  2512. /**
  2513. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2514. * @param scale defines the scale factor
  2515. * @param result defines the Vector2 object where to store the result
  2516. * @returns the unmodified current Vector2
  2517. */
  2518. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2519. result.x += this.x * scale;
  2520. result.y += this.y * scale;
  2521. return this;
  2522. };
  2523. /**
  2524. * Gets a boolean if two vectors are equals
  2525. * @param otherVector defines the other vector
  2526. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2527. */
  2528. Vector2.prototype.equals = function (otherVector) {
  2529. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2530. };
  2531. /**
  2532. * Gets a boolean if two vectors are equals (using an epsilon value)
  2533. * @param otherVector defines the other vector
  2534. * @param epsilon defines the minimal distance to consider equality
  2535. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2536. */
  2537. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2538. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2539. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2540. };
  2541. /**
  2542. * Gets a new Vector2 from current Vector2 floored values
  2543. * @returns a new Vector2
  2544. */
  2545. Vector2.prototype.floor = function () {
  2546. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2547. };
  2548. /**
  2549. * Gets a new Vector2 from current Vector2 floored values
  2550. * @returns a new Vector2
  2551. */
  2552. Vector2.prototype.fract = function () {
  2553. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2554. };
  2555. // Properties
  2556. /**
  2557. * Gets the length of the vector
  2558. * @returns the vector length (float)
  2559. */
  2560. Vector2.prototype.length = function () {
  2561. return Math.sqrt(this.x * this.x + this.y * this.y);
  2562. };
  2563. /**
  2564. * Gets the vector squared length
  2565. * @returns the vector squared length (float)
  2566. */
  2567. Vector2.prototype.lengthSquared = function () {
  2568. return (this.x * this.x + this.y * this.y);
  2569. };
  2570. // Methods
  2571. /**
  2572. * Normalize the vector
  2573. * @returns the current updated Vector2
  2574. */
  2575. Vector2.prototype.normalize = function () {
  2576. var len = this.length();
  2577. if (len === 0)
  2578. return this;
  2579. var num = 1.0 / len;
  2580. this.x *= num;
  2581. this.y *= num;
  2582. return this;
  2583. };
  2584. /**
  2585. * Gets a new Vector2 copied from the Vector2
  2586. * @returns a new Vector2
  2587. */
  2588. Vector2.prototype.clone = function () {
  2589. return new Vector2(this.x, this.y);
  2590. };
  2591. // Statics
  2592. /**
  2593. * Gets a new Vector2(0, 0)
  2594. * @returns a new Vector2
  2595. */
  2596. Vector2.Zero = function () {
  2597. return new Vector2(0, 0);
  2598. };
  2599. /**
  2600. * Gets a new Vector2(1, 1)
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.One = function () {
  2604. return new Vector2(1, 1);
  2605. };
  2606. /**
  2607. * Gets a new Vector2 set from the given index element of the given array
  2608. * @param array defines the data source
  2609. * @param offset defines the offset in the data source
  2610. * @returns a new Vector2
  2611. */
  2612. Vector2.FromArray = function (array, offset) {
  2613. if (offset === void 0) { offset = 0; }
  2614. return new Vector2(array[offset], array[offset + 1]);
  2615. };
  2616. /**
  2617. * Sets "result" from the given index element of the given array
  2618. * @param array defines the data source
  2619. * @param offset defines the offset in the data source
  2620. * @param result defines the target vector
  2621. */
  2622. Vector2.FromArrayToRef = function (array, offset, result) {
  2623. result.x = array[offset];
  2624. result.y = array[offset + 1];
  2625. };
  2626. /**
  2627. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2628. * @param value1 defines 1st point of control
  2629. * @param value2 defines 2nd point of control
  2630. * @param value3 defines 3rd point of control
  2631. * @param value4 defines 4th point of control
  2632. * @param amount defines the interpolation factor
  2633. * @returns a new Vector2
  2634. */
  2635. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2636. var squared = amount * amount;
  2637. var cubed = amount * squared;
  2638. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2639. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2640. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2641. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2642. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2643. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2644. return new Vector2(x, y);
  2645. };
  2646. /**
  2647. * 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".
  2648. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2649. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2650. * @param value defines the value to clamp
  2651. * @param min defines the lower limit
  2652. * @param max defines the upper limit
  2653. * @returns a new Vector2
  2654. */
  2655. Vector2.Clamp = function (value, min, max) {
  2656. var x = value.x;
  2657. x = (x > max.x) ? max.x : x;
  2658. x = (x < min.x) ? min.x : x;
  2659. var y = value.y;
  2660. y = (y > max.y) ? max.y : y;
  2661. y = (y < min.y) ? min.y : y;
  2662. return new Vector2(x, y);
  2663. };
  2664. /**
  2665. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2666. * @param value1 defines the 1st control point
  2667. * @param tangent1 defines the outgoing tangent
  2668. * @param value2 defines the 2nd control point
  2669. * @param tangent2 defines the incoming tangent
  2670. * @param amount defines the interpolation factor
  2671. * @returns a new Vector2
  2672. */
  2673. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2674. var squared = amount * amount;
  2675. var cubed = amount * squared;
  2676. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2677. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2678. var part3 = (cubed - (2.0 * squared)) + amount;
  2679. var part4 = cubed - squared;
  2680. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2681. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2682. return new Vector2(x, y);
  2683. };
  2684. /**
  2685. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2686. * @param start defines the start vector
  2687. * @param end defines the end vector
  2688. * @param amount defines the interpolation factor
  2689. * @returns a new Vector2
  2690. */
  2691. Vector2.Lerp = function (start, end, amount) {
  2692. var x = start.x + ((end.x - start.x) * amount);
  2693. var y = start.y + ((end.y - start.y) * amount);
  2694. return new Vector2(x, y);
  2695. };
  2696. /**
  2697. * Gets the dot product of the vector "left" and the vector "right"
  2698. * @param left defines first vector
  2699. * @param right defines second vector
  2700. * @returns the dot product (float)
  2701. */
  2702. Vector2.Dot = function (left, right) {
  2703. return left.x * right.x + left.y * right.y;
  2704. };
  2705. /**
  2706. * Returns a new Vector2 equal to the normalized given vector
  2707. * @param vector defines the vector to normalize
  2708. * @returns a new Vector2
  2709. */
  2710. Vector2.Normalize = function (vector) {
  2711. var newVector = vector.clone();
  2712. newVector.normalize();
  2713. return newVector;
  2714. };
  2715. /**
  2716. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2717. * @param left defines 1st vector
  2718. * @param right defines 2nd vector
  2719. * @returns a new Vector2
  2720. */
  2721. Vector2.Minimize = function (left, right) {
  2722. var x = (left.x < right.x) ? left.x : right.x;
  2723. var y = (left.y < right.y) ? left.y : right.y;
  2724. return new Vector2(x, y);
  2725. };
  2726. /**
  2727. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2728. * @param left defines 1st vector
  2729. * @param right defines 2nd vector
  2730. * @returns a new Vector2
  2731. */
  2732. Vector2.Maximize = function (left, right) {
  2733. var x = (left.x > right.x) ? left.x : right.x;
  2734. var y = (left.y > right.y) ? left.y : right.y;
  2735. return new Vector2(x, y);
  2736. };
  2737. /**
  2738. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2739. * @param vector defines the vector to transform
  2740. * @param transformation defines the matrix to apply
  2741. * @returns a new Vector2
  2742. */
  2743. Vector2.Transform = function (vector, transformation) {
  2744. var r = Vector2.Zero();
  2745. Vector2.TransformToRef(vector, transformation, r);
  2746. return r;
  2747. };
  2748. /**
  2749. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2750. * @param vector defines the vector to transform
  2751. * @param transformation defines the matrix to apply
  2752. * @param result defines the target vector
  2753. */
  2754. Vector2.TransformToRef = function (vector, transformation, result) {
  2755. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2756. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2757. result.x = x;
  2758. result.y = y;
  2759. };
  2760. /**
  2761. * Determines if a given vector is included in a triangle
  2762. * @param p defines the vector to test
  2763. * @param p0 defines 1st triangle point
  2764. * @param p1 defines 2nd triangle point
  2765. * @param p2 defines 3rd triangle point
  2766. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2767. */
  2768. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2769. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2770. var sign = a < 0 ? -1 : 1;
  2771. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2772. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2773. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2774. };
  2775. /**
  2776. * Gets the distance between the vectors "value1" and "value2"
  2777. * @param value1 defines first vector
  2778. * @param value2 defines second vector
  2779. * @returns the distance between vectors
  2780. */
  2781. Vector2.Distance = function (value1, value2) {
  2782. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2783. };
  2784. /**
  2785. * Returns the squared distance between the vectors "value1" and "value2"
  2786. * @param value1 defines first vector
  2787. * @param value2 defines second vector
  2788. * @returns the squared distance between vectors
  2789. */
  2790. Vector2.DistanceSquared = function (value1, value2) {
  2791. var x = value1.x - value2.x;
  2792. var y = value1.y - value2.y;
  2793. return (x * x) + (y * y);
  2794. };
  2795. /**
  2796. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2797. * @param value1 defines first vector
  2798. * @param value2 defines second vector
  2799. * @returns a new Vector2
  2800. */
  2801. Vector2.Center = function (value1, value2) {
  2802. var center = value1.add(value2);
  2803. center.scaleInPlace(0.5);
  2804. return center;
  2805. };
  2806. /**
  2807. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2808. * @param p defines the middle point
  2809. * @param segA defines one point of the segment
  2810. * @param segB defines the other point of the segment
  2811. * @returns the shortest distance
  2812. */
  2813. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2814. var l2 = Vector2.DistanceSquared(segA, segB);
  2815. if (l2 === 0.0) {
  2816. return Vector2.Distance(p, segA);
  2817. }
  2818. var v = segB.subtract(segA);
  2819. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2820. var proj = segA.add(v.multiplyByFloats(t, t));
  2821. return Vector2.Distance(p, proj);
  2822. };
  2823. return Vector2;
  2824. }());
  2825. BABYLON.Vector2 = Vector2;
  2826. /**
  2827. * Classed used to store (x,y,z) vector representation
  2828. * A Vector3 is the main object used in 3D geometry
  2829. * It can represent etiher the coordinates of a point the space, either a direction
  2830. * Reminder: Babylon.js uses a left handed forward facing system
  2831. */
  2832. var Vector3 = /** @class */ (function () {
  2833. /**
  2834. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2835. * @param x defines the first coordinates (on X axis)
  2836. * @param y defines the second coordinates (on Y axis)
  2837. * @param z defines the third coordinates (on Z axis)
  2838. */
  2839. function Vector3(
  2840. /**
  2841. * Defines the first coordinates (on X axis)
  2842. */
  2843. x,
  2844. /**
  2845. * Defines the second coordinates (on Y axis)
  2846. */
  2847. y,
  2848. /**
  2849. * Defines the third coordinates (on Z axis)
  2850. */
  2851. z) {
  2852. if (x === void 0) { x = 0; }
  2853. if (y === void 0) { y = 0; }
  2854. if (z === void 0) { z = 0; }
  2855. this.x = x;
  2856. this.y = y;
  2857. this.z = z;
  2858. }
  2859. /**
  2860. * Creates a string representation of the Vector3
  2861. * @returns a string with the Vector3 coordinates.
  2862. */
  2863. Vector3.prototype.toString = function () {
  2864. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2865. };
  2866. /**
  2867. * Gets the class name
  2868. * @returns the string "Vector3"
  2869. */
  2870. Vector3.prototype.getClassName = function () {
  2871. return "Vector3";
  2872. };
  2873. /**
  2874. * Creates the Vector3 hash code
  2875. * @returns a number which tends to be unique between Vector3 instances
  2876. */
  2877. Vector3.prototype.getHashCode = function () {
  2878. var hash = this.x || 0;
  2879. hash = (hash * 397) ^ (this.y || 0);
  2880. hash = (hash * 397) ^ (this.z || 0);
  2881. return hash;
  2882. };
  2883. // Operators
  2884. /**
  2885. * Creates an array containing three elements : the coordinates of the Vector3
  2886. * @returns a new array of numbers
  2887. */
  2888. Vector3.prototype.asArray = function () {
  2889. var result = [];
  2890. this.toArray(result, 0);
  2891. return result;
  2892. };
  2893. /**
  2894. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2895. * @param array defines the destination array
  2896. * @param index defines the offset in the destination array
  2897. * @returns the current Vector3
  2898. */
  2899. Vector3.prototype.toArray = function (array, index) {
  2900. if (index === void 0) { index = 0; }
  2901. array[index] = this.x;
  2902. array[index + 1] = this.y;
  2903. array[index + 2] = this.z;
  2904. return this;
  2905. };
  2906. /**
  2907. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2908. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2909. */
  2910. Vector3.prototype.toQuaternion = function () {
  2911. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2912. };
  2913. /**
  2914. * Adds the given vector to the current Vector3
  2915. * @param otherVector defines the second operand
  2916. * @returns the current updated Vector3
  2917. */
  2918. Vector3.prototype.addInPlace = function (otherVector) {
  2919. this.x += otherVector.x;
  2920. this.y += otherVector.y;
  2921. this.z += otherVector.z;
  2922. return this;
  2923. };
  2924. /**
  2925. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2926. * @param otherVector defines the second operand
  2927. * @returns the resulting Vector3
  2928. */
  2929. Vector3.prototype.add = function (otherVector) {
  2930. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2931. };
  2932. /**
  2933. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2934. * @param otherVector defines the second operand
  2935. * @param result defines the Vector3 object where to store the result
  2936. * @returns the current Vector3
  2937. */
  2938. Vector3.prototype.addToRef = function (otherVector, result) {
  2939. result.x = this.x + otherVector.x;
  2940. result.y = this.y + otherVector.y;
  2941. result.z = this.z + otherVector.z;
  2942. return this;
  2943. };
  2944. /**
  2945. * Subtract the given vector from the current Vector3
  2946. * @param otherVector defines the second operand
  2947. * @returns the current updated Vector3
  2948. */
  2949. Vector3.prototype.subtractInPlace = function (otherVector) {
  2950. this.x -= otherVector.x;
  2951. this.y -= otherVector.y;
  2952. this.z -= otherVector.z;
  2953. return this;
  2954. };
  2955. /**
  2956. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2957. * @param otherVector defines the second operand
  2958. * @returns the resulting Vector3
  2959. */
  2960. Vector3.prototype.subtract = function (otherVector) {
  2961. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2962. };
  2963. /**
  2964. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2965. * @param otherVector defines the second operand
  2966. * @param result defines the Vector3 object where to store the result
  2967. * @returns the current Vector3
  2968. */
  2969. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2970. result.x = this.x - otherVector.x;
  2971. result.y = this.y - otherVector.y;
  2972. result.z = this.z - otherVector.z;
  2973. return this;
  2974. };
  2975. /**
  2976. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2977. * @param x defines the x coordinate of the operand
  2978. * @param y defines the y coordinate of the operand
  2979. * @param z defines the z coordinate of the operand
  2980. * @returns the resulting Vector3
  2981. */
  2982. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2983. return new Vector3(this.x - x, this.y - y, this.z - z);
  2984. };
  2985. /**
  2986. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2987. * @param x defines the x coordinate of the operand
  2988. * @param y defines the y coordinate of the operand
  2989. * @param z defines the z coordinate of the operand
  2990. * @param result defines the Vector3 object where to store the result
  2991. * @returns the current Vector3
  2992. */
  2993. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2994. result.x = this.x - x;
  2995. result.y = this.y - y;
  2996. result.z = this.z - z;
  2997. return this;
  2998. };
  2999. /**
  3000. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3001. * @returns a new Vector3
  3002. */
  3003. Vector3.prototype.negate = function () {
  3004. return new Vector3(-this.x, -this.y, -this.z);
  3005. };
  3006. /**
  3007. * Multiplies the Vector3 coordinates by the float "scale"
  3008. * @param scale defines the multiplier factor
  3009. * @returns the current updated Vector3
  3010. */
  3011. Vector3.prototype.scaleInPlace = function (scale) {
  3012. this.x *= scale;
  3013. this.y *= scale;
  3014. this.z *= scale;
  3015. return this;
  3016. };
  3017. /**
  3018. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3019. * @param scale defines the multiplier factor
  3020. * @returns a new Vector3
  3021. */
  3022. Vector3.prototype.scale = function (scale) {
  3023. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3024. };
  3025. /**
  3026. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3027. * @param scale defines the multiplier factor
  3028. * @param result defines the Vector3 object where to store the result
  3029. * @returns the current Vector3
  3030. */
  3031. Vector3.prototype.scaleToRef = function (scale, result) {
  3032. result.x = this.x * scale;
  3033. result.y = this.y * scale;
  3034. result.z = this.z * scale;
  3035. return this;
  3036. };
  3037. /**
  3038. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3039. * @param scale defines the scale factor
  3040. * @param result defines the Vector3 object where to store the result
  3041. * @returns the unmodified current Vector3
  3042. */
  3043. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3044. result.x += this.x * scale;
  3045. result.y += this.y * scale;
  3046. result.z += this.z * scale;
  3047. return this;
  3048. };
  3049. /**
  3050. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3051. * @param otherVector defines the second operand
  3052. * @returns true if both vectors are equals
  3053. */
  3054. Vector3.prototype.equals = function (otherVector) {
  3055. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3056. };
  3057. /**
  3058. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3059. * @param otherVector defines the second operand
  3060. * @param epsilon defines the minimal distance to define values as equals
  3061. * @returns true if both vectors are distant less than epsilon
  3062. */
  3063. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3064. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3065. 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);
  3066. };
  3067. /**
  3068. * Returns true if the current Vector3 coordinates equals the given floats
  3069. * @param x defines the x coordinate of the operand
  3070. * @param y defines the y coordinate of the operand
  3071. * @param z defines the z coordinate of the operand
  3072. * @returns true if both vectors are equals
  3073. */
  3074. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3075. return this.x === x && this.y === y && this.z === z;
  3076. };
  3077. /**
  3078. * Multiplies the current Vector3 coordinates by the given ones
  3079. * @param otherVector defines the second operand
  3080. * @returns the current updated Vector3
  3081. */
  3082. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3083. this.x *= otherVector.x;
  3084. this.y *= otherVector.y;
  3085. this.z *= otherVector.z;
  3086. return this;
  3087. };
  3088. /**
  3089. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3090. * @param otherVector defines the second operand
  3091. * @returns the new Vector3
  3092. */
  3093. Vector3.prototype.multiply = function (otherVector) {
  3094. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3095. };
  3096. /**
  3097. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3098. * @param otherVector defines the second operand
  3099. * @param result defines the Vector3 object where to store the result
  3100. * @returns the current Vector3
  3101. */
  3102. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3103. result.x = this.x * otherVector.x;
  3104. result.y = this.y * otherVector.y;
  3105. result.z = this.z * otherVector.z;
  3106. return this;
  3107. };
  3108. /**
  3109. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3110. * @param x defines the x coordinate of the operand
  3111. * @param y defines the y coordinate of the operand
  3112. * @param z defines the z coordinate of the operand
  3113. * @returns the new Vector3
  3114. */
  3115. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3116. return new Vector3(this.x * x, this.y * y, this.z * z);
  3117. };
  3118. /**
  3119. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3120. * @param otherVector defines the second operand
  3121. * @returns the new Vector3
  3122. */
  3123. Vector3.prototype.divide = function (otherVector) {
  3124. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3125. };
  3126. /**
  3127. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3128. * @param otherVector defines the second operand
  3129. * @param result defines the Vector3 object where to store the result
  3130. * @returns the current Vector3
  3131. */
  3132. Vector3.prototype.divideToRef = function (otherVector, result) {
  3133. result.x = this.x / otherVector.x;
  3134. result.y = this.y / otherVector.y;
  3135. result.z = this.z / otherVector.z;
  3136. return this;
  3137. };
  3138. /**
  3139. * Divides the current Vector3 coordinates by the given ones.
  3140. * @param otherVector defines the second operand
  3141. * @returns the current updated Vector3
  3142. */
  3143. Vector3.prototype.divideInPlace = function (otherVector) {
  3144. return this.divideToRef(otherVector, this);
  3145. };
  3146. /**
  3147. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3148. * @param other defines the second operand
  3149. * @returns the current updated Vector3
  3150. */
  3151. Vector3.prototype.minimizeInPlace = function (other) {
  3152. if (other.x < this.x)
  3153. this.x = other.x;
  3154. if (other.y < this.y)
  3155. this.y = other.y;
  3156. if (other.z < this.z)
  3157. this.z = other.z;
  3158. return this;
  3159. };
  3160. /**
  3161. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3162. * @param other defines the second operand
  3163. * @returns the current updated Vector3
  3164. */
  3165. Vector3.prototype.maximizeInPlace = function (other) {
  3166. if (other.x > this.x)
  3167. this.x = other.x;
  3168. if (other.y > this.y)
  3169. this.y = other.y;
  3170. if (other.z > this.z)
  3171. this.z = other.z;
  3172. return this;
  3173. };
  3174. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3175. /**
  3176. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3177. */
  3178. get: function () {
  3179. var absX = Math.abs(this.x);
  3180. var absY = Math.abs(this.y);
  3181. if (absX !== absY) {
  3182. return true;
  3183. }
  3184. var absZ = Math.abs(this.z);
  3185. if (absX !== absZ) {
  3186. return true;
  3187. }
  3188. if (absY !== absZ) {
  3189. return true;
  3190. }
  3191. return false;
  3192. },
  3193. enumerable: true,
  3194. configurable: true
  3195. });
  3196. /**
  3197. * Gets a new Vector3 from current Vector3 floored values
  3198. * @returns a new Vector3
  3199. */
  3200. Vector3.prototype.floor = function () {
  3201. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3202. };
  3203. /**
  3204. * Gets a new Vector3 from current Vector3 floored values
  3205. * @returns a new Vector3
  3206. */
  3207. Vector3.prototype.fract = function () {
  3208. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3209. };
  3210. // Properties
  3211. /**
  3212. * Gets the length of the Vector3
  3213. * @returns the length of the Vecto3
  3214. */
  3215. Vector3.prototype.length = function () {
  3216. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3217. };
  3218. /**
  3219. * Gets the squared length of the Vector3
  3220. * @returns squared length of the Vector3
  3221. */
  3222. Vector3.prototype.lengthSquared = function () {
  3223. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3224. };
  3225. /**
  3226. * Normalize the current Vector3.
  3227. * Please note that this is an in place operation.
  3228. * @returns the current updated Vector3
  3229. */
  3230. Vector3.prototype.normalize = function () {
  3231. var len = this.length();
  3232. if (len === 0 || len === 1.0)
  3233. return this;
  3234. var num = 1.0 / len;
  3235. this.x *= num;
  3236. this.y *= num;
  3237. this.z *= num;
  3238. return this;
  3239. };
  3240. /**
  3241. * Normalize the current Vector3 to a new vector
  3242. * @returns the new Vector3
  3243. */
  3244. Vector3.prototype.normalizeToNew = function () {
  3245. var normalized = new Vector3(0, 0, 0);
  3246. this.normalizeToRef(normalized);
  3247. return normalized;
  3248. };
  3249. /**
  3250. * Normalize the current Vector3 to the reference
  3251. * @param reference define the Vector3 to update
  3252. * @returns the updated Vector3
  3253. */
  3254. Vector3.prototype.normalizeToRef = function (reference) {
  3255. var len = this.length();
  3256. if (len === 0 || len === 1.0) {
  3257. reference.set(this.x, this.y, this.z);
  3258. return reference;
  3259. }
  3260. var scale = 1.0 / len;
  3261. this.scaleToRef(scale, reference);
  3262. return reference;
  3263. };
  3264. /**
  3265. * Creates a new Vector3 copied from the current Vector3
  3266. * @returns the new Vector3
  3267. */
  3268. Vector3.prototype.clone = function () {
  3269. return new Vector3(this.x, this.y, this.z);
  3270. };
  3271. /**
  3272. * Copies the given vector coordinates to the current Vector3 ones
  3273. * @param source defines the source Vector3
  3274. * @returns the current updated Vector3
  3275. */
  3276. Vector3.prototype.copyFrom = function (source) {
  3277. this.x = source.x;
  3278. this.y = source.y;
  3279. this.z = source.z;
  3280. return this;
  3281. };
  3282. /**
  3283. * Copies the given floats to the current Vector3 coordinates
  3284. * @param x defines the x coordinate of the operand
  3285. * @param y defines the y coordinate of the operand
  3286. * @param z defines the z coordinate of the operand
  3287. * @returns the current updated Vector3
  3288. */
  3289. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3290. this.x = x;
  3291. this.y = y;
  3292. this.z = z;
  3293. return this;
  3294. };
  3295. /**
  3296. * Copies the given floats to the current Vector3 coordinates
  3297. * @param x defines the x coordinate of the operand
  3298. * @param y defines the y coordinate of the operand
  3299. * @param z defines the z coordinate of the operand
  3300. * @returns the current updated Vector3
  3301. */
  3302. Vector3.prototype.set = function (x, y, z) {
  3303. return this.copyFromFloats(x, y, z);
  3304. };
  3305. // Statics
  3306. /**
  3307. * Get the clip factor between two vectors
  3308. * @param vector0 defines the first operand
  3309. * @param vector1 defines the second operand
  3310. * @param axis defines the axis to use
  3311. * @param size defines the size along the axis
  3312. * @returns the clip factor
  3313. */
  3314. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3315. var d0 = Vector3.Dot(vector0, axis) - size;
  3316. var d1 = Vector3.Dot(vector1, axis) - size;
  3317. var s = d0 / (d0 - d1);
  3318. return s;
  3319. };
  3320. /**
  3321. * Get angle between two vectors
  3322. * @param vector0 angle between vector0 and vector1
  3323. * @param vector1 angle between vector0 and vector1
  3324. * @param normal direction of the normal
  3325. * @return the angle between vector0 and vector1
  3326. */
  3327. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3328. var v0 = vector0.clone().normalize();
  3329. var v1 = vector1.clone().normalize();
  3330. var dot = Vector3.Dot(v0, v1);
  3331. var n = Vector3.Cross(v0, v1);
  3332. if (Vector3.Dot(n, normal) > 0) {
  3333. return Math.acos(dot);
  3334. }
  3335. return -Math.acos(dot);
  3336. };
  3337. /**
  3338. * Returns a new Vector3 set from the index "offset" of the given array
  3339. * @param array defines the source array
  3340. * @param offset defines the offset in the source array
  3341. * @returns the new Vector3
  3342. */
  3343. Vector3.FromArray = function (array, offset) {
  3344. if (!offset) {
  3345. offset = 0;
  3346. }
  3347. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3348. };
  3349. /**
  3350. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3351. * This function is deprecated. Use FromArray instead
  3352. * @param array defines the source array
  3353. * @param offset defines the offset in the source array
  3354. * @returns the new Vector3
  3355. */
  3356. Vector3.FromFloatArray = function (array, offset) {
  3357. return Vector3.FromArray(array, offset);
  3358. };
  3359. /**
  3360. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3361. * @param array defines the source array
  3362. * @param offset defines the offset in the source array
  3363. * @param result defines the Vector3 where to store the result
  3364. */
  3365. Vector3.FromArrayToRef = function (array, offset, result) {
  3366. result.x = array[offset];
  3367. result.y = array[offset + 1];
  3368. result.z = array[offset + 2];
  3369. };
  3370. /**
  3371. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3372. * This function is deprecated. Use FromArrayToRef instead.
  3373. * @param array defines the source array
  3374. * @param offset defines the offset in the source array
  3375. * @param result defines the Vector3 where to store the result
  3376. */
  3377. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3378. return Vector3.FromArrayToRef(array, offset, result);
  3379. };
  3380. /**
  3381. * Sets the given vector "result" with the given floats.
  3382. * @param x defines the x coordinate of the source
  3383. * @param y defines the y coordinate of the source
  3384. * @param z defines the z coordinate of the source
  3385. * @param result defines the Vector3 where to store the result
  3386. */
  3387. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3388. result.x = x;
  3389. result.y = y;
  3390. result.z = z;
  3391. };
  3392. /**
  3393. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3394. * @returns a new empty Vector3
  3395. */
  3396. Vector3.Zero = function () {
  3397. return new Vector3(0.0, 0.0, 0.0);
  3398. };
  3399. /**
  3400. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3401. * @returns a new unit Vector3
  3402. */
  3403. Vector3.One = function () {
  3404. return new Vector3(1.0, 1.0, 1.0);
  3405. };
  3406. /**
  3407. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3408. * @returns a new up Vector3
  3409. */
  3410. Vector3.Up = function () {
  3411. return new Vector3(0.0, 1.0, 0.0);
  3412. };
  3413. /**
  3414. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3415. * @returns a new down Vector3
  3416. */
  3417. Vector3.Down = function () {
  3418. return new Vector3(0.0, -1.0, 0.0);
  3419. };
  3420. /**
  3421. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3422. * @returns a new forward Vector3
  3423. */
  3424. Vector3.Forward = function () {
  3425. return new Vector3(0.0, 0.0, 1.0);
  3426. };
  3427. /**
  3428. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3429. * @returns a new right Vector3
  3430. */
  3431. Vector3.Right = function () {
  3432. return new Vector3(1.0, 0.0, 0.0);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3436. * @returns a new left Vector3
  3437. */
  3438. Vector3.Left = function () {
  3439. return new Vector3(-1.0, 0.0, 0.0);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3443. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3444. * @param vector defines the Vector3 to transform
  3445. * @param transformation defines the transformation matrix
  3446. * @returns the transformed Vector3
  3447. */
  3448. Vector3.TransformCoordinates = function (vector, transformation) {
  3449. var result = Vector3.Zero();
  3450. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3451. return result;
  3452. };
  3453. /**
  3454. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3455. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3456. * @param vector defines the Vector3 to transform
  3457. * @param transformation defines the transformation matrix
  3458. * @param result defines the Vector3 where to store the result
  3459. */
  3460. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3461. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3462. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3463. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3464. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3465. result.x = x / w;
  3466. result.y = y / w;
  3467. result.z = z / w;
  3468. };
  3469. /**
  3470. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3471. * This method computes tranformed coordinates only, not transformed direction vectors
  3472. * @param x define the x coordinate of the source vector
  3473. * @param y define the y coordinate of the source vector
  3474. * @param z define the z coordinate of the source vector
  3475. * @param transformation defines the transformation matrix
  3476. * @param result defines the Vector3 where to store the result
  3477. */
  3478. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3479. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3480. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3481. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3482. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3483. result.x = rx / rw;
  3484. result.y = ry / rw;
  3485. result.z = rz / rw;
  3486. };
  3487. /**
  3488. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3489. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3490. * @param vector defines the Vector3 to transform
  3491. * @param transformation defines the transformation matrix
  3492. * @returns the new Vector3
  3493. */
  3494. Vector3.TransformNormal = function (vector, transformation) {
  3495. var result = Vector3.Zero();
  3496. Vector3.TransformNormalToRef(vector, transformation, result);
  3497. return result;
  3498. };
  3499. /**
  3500. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3501. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3502. * @param vector defines the Vector3 to transform
  3503. * @param transformation defines the transformation matrix
  3504. * @param result defines the Vector3 where to store the result
  3505. */
  3506. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3507. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3508. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3509. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3510. result.x = x;
  3511. result.y = y;
  3512. result.z = z;
  3513. };
  3514. /**
  3515. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3516. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3517. * @param x define the x coordinate of the source vector
  3518. * @param y define the y coordinate of the source vector
  3519. * @param z define the z coordinate of the source vector
  3520. * @param transformation defines the transformation matrix
  3521. * @param result defines the Vector3 where to store the result
  3522. */
  3523. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3524. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3525. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3526. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3527. };
  3528. /**
  3529. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3530. * @param value1 defines the first control point
  3531. * @param value2 defines the second control point
  3532. * @param value3 defines the third control point
  3533. * @param value4 defines the fourth control point
  3534. * @param amount defines the amount on the spline to use
  3535. * @returns the new Vector3
  3536. */
  3537. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3538. var squared = amount * amount;
  3539. var cubed = amount * squared;
  3540. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3541. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3542. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3543. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3544. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3545. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3546. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3547. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3548. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3549. return new Vector3(x, y, z);
  3550. };
  3551. /**
  3552. * 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"
  3553. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3554. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3555. * @param value defines the current value
  3556. * @param min defines the lower range value
  3557. * @param max defines the upper range value
  3558. * @returns the new Vector3
  3559. */
  3560. Vector3.Clamp = function (value, min, max) {
  3561. var x = value.x;
  3562. x = (x > max.x) ? max.x : x;
  3563. x = (x < min.x) ? min.x : x;
  3564. var y = value.y;
  3565. y = (y > max.y) ? max.y : y;
  3566. y = (y < min.y) ? min.y : y;
  3567. var z = value.z;
  3568. z = (z > max.z) ? max.z : z;
  3569. z = (z < min.z) ? min.z : z;
  3570. return new Vector3(x, y, z);
  3571. };
  3572. /**
  3573. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3574. * @param value1 defines the first control point
  3575. * @param tangent1 defines the first tangent vector
  3576. * @param value2 defines the second control point
  3577. * @param tangent2 defines the second tangent vector
  3578. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3579. * @returns the new Vector3
  3580. */
  3581. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3582. var squared = amount * amount;
  3583. var cubed = amount * squared;
  3584. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3585. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3586. var part3 = (cubed - (2.0 * squared)) + amount;
  3587. var part4 = cubed - squared;
  3588. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3589. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3590. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3591. return new Vector3(x, y, z);
  3592. };
  3593. /**
  3594. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3595. * @param start defines the start value
  3596. * @param end defines the end value
  3597. * @param amount max defines amount between both (between 0 and 1)
  3598. * @returns the new Vector3
  3599. */
  3600. Vector3.Lerp = function (start, end, amount) {
  3601. var result = new Vector3(0, 0, 0);
  3602. Vector3.LerpToRef(start, end, amount, result);
  3603. return result;
  3604. };
  3605. /**
  3606. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3607. * @param start defines the start value
  3608. * @param end defines the end value
  3609. * @param amount max defines amount between both (between 0 and 1)
  3610. * @param result defines the Vector3 where to store the result
  3611. */
  3612. Vector3.LerpToRef = function (start, end, amount, result) {
  3613. result.x = start.x + ((end.x - start.x) * amount);
  3614. result.y = start.y + ((end.y - start.y) * amount);
  3615. result.z = start.z + ((end.z - start.z) * amount);
  3616. };
  3617. /**
  3618. * Returns the dot product (float) between the vectors "left" and "right"
  3619. * @param left defines the left operand
  3620. * @param right defines the right operand
  3621. * @returns the dot product
  3622. */
  3623. Vector3.Dot = function (left, right) {
  3624. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3625. };
  3626. /**
  3627. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3628. * The cross product is then orthogonal to both "left" and "right"
  3629. * @param left defines the left operand
  3630. * @param right defines the right operand
  3631. * @returns the cross product
  3632. */
  3633. Vector3.Cross = function (left, right) {
  3634. var result = Vector3.Zero();
  3635. Vector3.CrossToRef(left, right, result);
  3636. return result;
  3637. };
  3638. /**
  3639. * Sets the given vector "result" with the cross product of "left" and "right"
  3640. * The cross product is then orthogonal to both "left" and "right"
  3641. * @param left defines the left operand
  3642. * @param right defines the right operand
  3643. * @param result defines the Vector3 where to store the result
  3644. */
  3645. Vector3.CrossToRef = function (left, right, result) {
  3646. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3647. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3648. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3649. result.copyFrom(MathTmp.Vector3[0]);
  3650. };
  3651. /**
  3652. * Returns a new Vector3 as the normalization of the given vector
  3653. * @param vector defines the Vector3 to normalize
  3654. * @returns the new Vector3
  3655. */
  3656. Vector3.Normalize = function (vector) {
  3657. var result = Vector3.Zero();
  3658. Vector3.NormalizeToRef(vector, result);
  3659. return result;
  3660. };
  3661. /**
  3662. * Sets the given vector "result" with the normalization of the given first vector
  3663. * @param vector defines the Vector3 to normalize
  3664. * @param result defines the Vector3 where to store the result
  3665. */
  3666. Vector3.NormalizeToRef = function (vector, result) {
  3667. result.copyFrom(vector);
  3668. result.normalize();
  3669. };
  3670. /**
  3671. * Project a Vector3 onto screen space
  3672. * @param vector defines the Vector3 to project
  3673. * @param world defines the world matrix to use
  3674. * @param transform defines the transform (view x projection) matrix to use
  3675. * @param viewport defines the screen viewport to use
  3676. * @returns the new Vector3
  3677. */
  3678. Vector3.Project = function (vector, world, transform, viewport) {
  3679. var cw = viewport.width;
  3680. var ch = viewport.height;
  3681. var cx = viewport.x;
  3682. var cy = viewport.y;
  3683. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3684. 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);
  3685. var matrix = MathTmp.Matrix[0];
  3686. world.multiplyToRef(transform, matrix);
  3687. matrix.multiplyToRef(viewportMatrix, matrix);
  3688. return Vector3.TransformCoordinates(vector, matrix);
  3689. };
  3690. /**
  3691. * Unproject from screen space to object space
  3692. * @param source defines the screen space Vector3 to use
  3693. * @param viewportWidth defines the current width of the viewport
  3694. * @param viewportHeight defines the current height of the viewport
  3695. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3696. * @param transform defines the transform (view x projection) matrix to use
  3697. * @returns the new Vector3
  3698. */
  3699. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3700. var matrix = MathTmp.Matrix[0];
  3701. world.multiplyToRef(transform, matrix);
  3702. matrix.invert();
  3703. source.x = source.x / viewportWidth * 2 - 1;
  3704. source.y = -(source.y / viewportHeight * 2 - 1);
  3705. var vector = Vector3.TransformCoordinates(source, matrix);
  3706. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3707. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3708. vector = vector.scale(1.0 / num);
  3709. }
  3710. return vector;
  3711. };
  3712. /**
  3713. * Unproject from screen space to object space
  3714. * @param source defines the screen space Vector3 to use
  3715. * @param viewportWidth defines the current width of the viewport
  3716. * @param viewportHeight defines the current height of the viewport
  3717. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3718. * @param view defines the view matrix to use
  3719. * @param projection defines the projection matrix to use
  3720. * @returns the new Vector3
  3721. */
  3722. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3723. var result = Vector3.Zero();
  3724. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3725. return result;
  3726. };
  3727. /**
  3728. * Unproject from screen space to object space
  3729. * @param source defines the screen space Vector3 to use
  3730. * @param viewportWidth defines the current width of the viewport
  3731. * @param viewportHeight defines the current height of the viewport
  3732. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3733. * @param view defines the view matrix to use
  3734. * @param projection defines the projection matrix to use
  3735. * @param result defines the Vector3 where to store the result
  3736. */
  3737. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3738. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3739. };
  3740. /**
  3741. * Unproject from screen space to object space
  3742. * @param sourceX defines the screen space x coordinate to use
  3743. * @param sourceY defines the screen space y coordinate to use
  3744. * @param sourceZ defines the screen space z coordinate to use
  3745. * @param viewportWidth defines the current width of the viewport
  3746. * @param viewportHeight defines the current height of the viewport
  3747. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3748. * @param view defines the view matrix to use
  3749. * @param projection defines the projection matrix to use
  3750. * @param result defines the Vector3 where to store the result
  3751. */
  3752. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3753. var matrix = MathTmp.Matrix[0];
  3754. world.multiplyToRef(view, matrix);
  3755. matrix.multiplyToRef(projection, matrix);
  3756. matrix.invert();
  3757. var screenSource = MathTmp.Vector3[0];
  3758. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3759. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3760. screenSource.z = 2 * sourceZ - 1.0;
  3761. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3762. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3763. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3764. result.scaleInPlace(1.0 / num);
  3765. }
  3766. };
  3767. /**
  3768. * Gets the minimal coordinate values between two Vector3
  3769. * @param left defines the first operand
  3770. * @param right defines the second operand
  3771. * @returns the new Vector3
  3772. */
  3773. Vector3.Minimize = function (left, right) {
  3774. var min = left.clone();
  3775. min.minimizeInPlace(right);
  3776. return min;
  3777. };
  3778. /**
  3779. * Gets the maximal coordinate values between two Vector3
  3780. * @param left defines the first operand
  3781. * @param right defines the second operand
  3782. * @returns the new Vector3
  3783. */
  3784. Vector3.Maximize = function (left, right) {
  3785. var max = left.clone();
  3786. max.maximizeInPlace(right);
  3787. return max;
  3788. };
  3789. /**
  3790. * Returns the distance between the vectors "value1" and "value2"
  3791. * @param value1 defines the first operand
  3792. * @param value2 defines the second operand
  3793. * @returns the distance
  3794. */
  3795. Vector3.Distance = function (value1, value2) {
  3796. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3797. };
  3798. /**
  3799. * Returns the squared distance between the vectors "value1" and "value2"
  3800. * @param value1 defines the first operand
  3801. * @param value2 defines the second operand
  3802. * @returns the squared distance
  3803. */
  3804. Vector3.DistanceSquared = function (value1, value2) {
  3805. var x = value1.x - value2.x;
  3806. var y = value1.y - value2.y;
  3807. var z = value1.z - value2.z;
  3808. return (x * x) + (y * y) + (z * z);
  3809. };
  3810. /**
  3811. * Returns a new Vector3 located at the center between "value1" and "value2"
  3812. * @param value1 defines the first operand
  3813. * @param value2 defines the second operand
  3814. * @returns the new Vector3
  3815. */
  3816. Vector3.Center = function (value1, value2) {
  3817. var center = value1.add(value2);
  3818. center.scaleInPlace(0.5);
  3819. return center;
  3820. };
  3821. /**
  3822. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3823. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3824. * to something in order to rotate it from its local system to the given target system
  3825. * Note: axis1, axis2 and axis3 are normalized during this operation
  3826. * @param axis1 defines the first axis
  3827. * @param axis2 defines the second axis
  3828. * @param axis3 defines the third axis
  3829. * @returns a new Vector3
  3830. */
  3831. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3832. var rotation = Vector3.Zero();
  3833. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3834. return rotation;
  3835. };
  3836. /**
  3837. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3838. * @param axis1 defines the first axis
  3839. * @param axis2 defines the second axis
  3840. * @param axis3 defines the third axis
  3841. * @param ref defines the Vector3 where to store the result
  3842. */
  3843. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3844. var quat = MathTmp.Quaternion[0];
  3845. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3846. quat.toEulerAnglesToRef(ref);
  3847. };
  3848. return Vector3;
  3849. }());
  3850. BABYLON.Vector3 = Vector3;
  3851. //Vector4 class created for EulerAngle class conversion to Quaternion
  3852. var Vector4 = /** @class */ (function () {
  3853. /**
  3854. * Creates a Vector4 object from the given floats.
  3855. */
  3856. function Vector4(x, y, z, w) {
  3857. this.x = x;
  3858. this.y = y;
  3859. this.z = z;
  3860. this.w = w;
  3861. }
  3862. /**
  3863. * Returns the string with the Vector4 coordinates.
  3864. */
  3865. Vector4.prototype.toString = function () {
  3866. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3867. };
  3868. /**
  3869. * Returns the string "Vector4".
  3870. */
  3871. Vector4.prototype.getClassName = function () {
  3872. return "Vector4";
  3873. };
  3874. /**
  3875. * Returns the Vector4 hash code.
  3876. */
  3877. Vector4.prototype.getHashCode = function () {
  3878. var hash = this.x || 0;
  3879. hash = (hash * 397) ^ (this.y || 0);
  3880. hash = (hash * 397) ^ (this.z || 0);
  3881. hash = (hash * 397) ^ (this.w || 0);
  3882. return hash;
  3883. };
  3884. // Operators
  3885. /**
  3886. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3887. */
  3888. Vector4.prototype.asArray = function () {
  3889. var result = new Array();
  3890. this.toArray(result, 0);
  3891. return result;
  3892. };
  3893. /**
  3894. * Populates the given array from the given index with the Vector4 coordinates.
  3895. * Returns the Vector4.
  3896. */
  3897. Vector4.prototype.toArray = function (array, index) {
  3898. if (index === undefined) {
  3899. index = 0;
  3900. }
  3901. array[index] = this.x;
  3902. array[index + 1] = this.y;
  3903. array[index + 2] = this.z;
  3904. array[index + 3] = this.w;
  3905. return this;
  3906. };
  3907. /**
  3908. * Adds the given vector to the current Vector4.
  3909. * Returns the updated Vector4.
  3910. */
  3911. Vector4.prototype.addInPlace = function (otherVector) {
  3912. this.x += otherVector.x;
  3913. this.y += otherVector.y;
  3914. this.z += otherVector.z;
  3915. this.w += otherVector.w;
  3916. return this;
  3917. };
  3918. /**
  3919. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3920. */
  3921. Vector4.prototype.add = function (otherVector) {
  3922. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3923. };
  3924. /**
  3925. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3926. * Returns the current Vector4.
  3927. */
  3928. Vector4.prototype.addToRef = function (otherVector, result) {
  3929. result.x = this.x + otherVector.x;
  3930. result.y = this.y + otherVector.y;
  3931. result.z = this.z + otherVector.z;
  3932. result.w = this.w + otherVector.w;
  3933. return this;
  3934. };
  3935. /**
  3936. * Subtract in place the given vector from the current Vector4.
  3937. * Returns the updated Vector4.
  3938. */
  3939. Vector4.prototype.subtractInPlace = function (otherVector) {
  3940. this.x -= otherVector.x;
  3941. this.y -= otherVector.y;
  3942. this.z -= otherVector.z;
  3943. this.w -= otherVector.w;
  3944. return this;
  3945. };
  3946. /**
  3947. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3948. */
  3949. Vector4.prototype.subtract = function (otherVector) {
  3950. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3951. };
  3952. /**
  3953. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3954. * Returns the current Vector4.
  3955. */
  3956. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3957. result.x = this.x - otherVector.x;
  3958. result.y = this.y - otherVector.y;
  3959. result.z = this.z - otherVector.z;
  3960. result.w = this.w - otherVector.w;
  3961. return this;
  3962. };
  3963. /**
  3964. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3965. */
  3966. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3967. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3968. };
  3969. /**
  3970. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3971. * Returns the current Vector4.
  3972. */
  3973. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3974. result.x = this.x - x;
  3975. result.y = this.y - y;
  3976. result.z = this.z - z;
  3977. result.w = this.w - w;
  3978. return this;
  3979. };
  3980. /**
  3981. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3982. */
  3983. Vector4.prototype.negate = function () {
  3984. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3985. };
  3986. /**
  3987. * Multiplies the current Vector4 coordinates by scale (float).
  3988. * Returns the updated Vector4.
  3989. */
  3990. Vector4.prototype.scaleInPlace = function (scale) {
  3991. this.x *= scale;
  3992. this.y *= scale;
  3993. this.z *= scale;
  3994. this.w *= scale;
  3995. return this;
  3996. };
  3997. /**
  3998. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3999. */
  4000. Vector4.prototype.scale = function (scale) {
  4001. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4002. };
  4003. /**
  4004. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4005. * Returns the current Vector4.
  4006. */
  4007. Vector4.prototype.scaleToRef = function (scale, result) {
  4008. result.x = this.x * scale;
  4009. result.y = this.y * scale;
  4010. result.z = this.z * scale;
  4011. result.w = this.w * scale;
  4012. return this;
  4013. };
  4014. /**
  4015. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4016. * @param scale defines the scale factor
  4017. * @param result defines the Vector4 object where to store the result
  4018. * @returns the unmodified current Vector4
  4019. */
  4020. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4021. result.x += this.x * scale;
  4022. result.y += this.y * scale;
  4023. result.z += this.z * scale;
  4024. result.w += this.w * scale;
  4025. return this;
  4026. };
  4027. /**
  4028. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4029. */
  4030. Vector4.prototype.equals = function (otherVector) {
  4031. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4032. };
  4033. /**
  4034. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4035. */
  4036. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4037. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4038. return otherVector
  4039. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4040. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4041. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4042. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4043. };
  4044. /**
  4045. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4046. */
  4047. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4048. return this.x === x && this.y === y && this.z === z && this.w === w;
  4049. };
  4050. /**
  4051. * Multiplies in place the current Vector4 by the given one.
  4052. * Returns the updated Vector4.
  4053. */
  4054. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4055. this.x *= otherVector.x;
  4056. this.y *= otherVector.y;
  4057. this.z *= otherVector.z;
  4058. this.w *= otherVector.w;
  4059. return this;
  4060. };
  4061. /**
  4062. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4063. */
  4064. Vector4.prototype.multiply = function (otherVector) {
  4065. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4066. };
  4067. /**
  4068. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4069. * Returns the current Vector4.
  4070. */
  4071. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4072. result.x = this.x * otherVector.x;
  4073. result.y = this.y * otherVector.y;
  4074. result.z = this.z * otherVector.z;
  4075. result.w = this.w * otherVector.w;
  4076. return this;
  4077. };
  4078. /**
  4079. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4080. */
  4081. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4082. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4083. };
  4084. /**
  4085. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4086. */
  4087. Vector4.prototype.divide = function (otherVector) {
  4088. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4089. };
  4090. /**
  4091. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4092. * Returns the current Vector4.
  4093. */
  4094. Vector4.prototype.divideToRef = function (otherVector, result) {
  4095. result.x = this.x / otherVector.x;
  4096. result.y = this.y / otherVector.y;
  4097. result.z = this.z / otherVector.z;
  4098. result.w = this.w / otherVector.w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Divides the current Vector3 coordinates by the given ones.
  4103. * @returns the updated Vector3.
  4104. */
  4105. Vector4.prototype.divideInPlace = function (otherVector) {
  4106. return this.divideToRef(otherVector, this);
  4107. };
  4108. /**
  4109. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4110. * @param other defines the second operand
  4111. * @returns the current updated Vector4
  4112. */
  4113. Vector4.prototype.minimizeInPlace = function (other) {
  4114. if (other.x < this.x)
  4115. this.x = other.x;
  4116. if (other.y < this.y)
  4117. this.y = other.y;
  4118. if (other.z < this.z)
  4119. this.z = other.z;
  4120. if (other.w < this.w)
  4121. this.w = other.w;
  4122. return this;
  4123. };
  4124. /**
  4125. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4126. * @param other defines the second operand
  4127. * @returns the current updated Vector4
  4128. */
  4129. Vector4.prototype.maximizeInPlace = function (other) {
  4130. if (other.x > this.x)
  4131. this.x = other.x;
  4132. if (other.y > this.y)
  4133. this.y = other.y;
  4134. if (other.z > this.z)
  4135. this.z = other.z;
  4136. if (other.w > this.w)
  4137. this.w = other.w;
  4138. return this;
  4139. };
  4140. /**
  4141. * Gets a new Vector4 from current Vector4 floored values
  4142. * @returns a new Vector4
  4143. */
  4144. Vector4.prototype.floor = function () {
  4145. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4146. };
  4147. /**
  4148. * Gets a new Vector4 from current Vector3 floored values
  4149. * @returns a new Vector4
  4150. */
  4151. Vector4.prototype.fract = function () {
  4152. 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));
  4153. };
  4154. // Properties
  4155. /**
  4156. * Returns the Vector4 length (float).
  4157. */
  4158. Vector4.prototype.length = function () {
  4159. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4160. };
  4161. /**
  4162. * Returns the Vector4 squared length (float).
  4163. */
  4164. Vector4.prototype.lengthSquared = function () {
  4165. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4166. };
  4167. // Methods
  4168. /**
  4169. * Normalizes in place the Vector4.
  4170. * Returns the updated Vector4.
  4171. */
  4172. Vector4.prototype.normalize = function () {
  4173. var len = this.length();
  4174. if (len === 0)
  4175. return this;
  4176. var num = 1.0 / len;
  4177. this.x *= num;
  4178. this.y *= num;
  4179. this.z *= num;
  4180. this.w *= num;
  4181. return this;
  4182. };
  4183. /**
  4184. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4185. */
  4186. Vector4.prototype.toVector3 = function () {
  4187. return new Vector3(this.x, this.y, this.z);
  4188. };
  4189. /**
  4190. * Returns a new Vector4 copied from the current one.
  4191. */
  4192. Vector4.prototype.clone = function () {
  4193. return new Vector4(this.x, this.y, this.z, this.w);
  4194. };
  4195. /**
  4196. * Updates the current Vector4 with the given one coordinates.
  4197. * Returns the updated Vector4.
  4198. */
  4199. Vector4.prototype.copyFrom = function (source) {
  4200. this.x = source.x;
  4201. this.y = source.y;
  4202. this.z = source.z;
  4203. this.w = source.w;
  4204. return this;
  4205. };
  4206. /**
  4207. * Updates the current Vector4 coordinates with the given floats.
  4208. * Returns the updated Vector4.
  4209. */
  4210. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4211. this.x = x;
  4212. this.y = y;
  4213. this.z = z;
  4214. this.w = w;
  4215. return this;
  4216. };
  4217. /**
  4218. * Updates the current Vector4 coordinates with the given floats.
  4219. * Returns the updated Vector4.
  4220. */
  4221. Vector4.prototype.set = function (x, y, z, w) {
  4222. return this.copyFromFloats(x, y, z, w);
  4223. };
  4224. // Statics
  4225. /**
  4226. * Returns a new Vector4 set from the starting index of the given array.
  4227. */
  4228. Vector4.FromArray = function (array, offset) {
  4229. if (!offset) {
  4230. offset = 0;
  4231. }
  4232. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4233. };
  4234. /**
  4235. * Updates the given vector "result" from the starting index of the given array.
  4236. */
  4237. Vector4.FromArrayToRef = function (array, offset, result) {
  4238. result.x = array[offset];
  4239. result.y = array[offset + 1];
  4240. result.z = array[offset + 2];
  4241. result.w = array[offset + 3];
  4242. };
  4243. /**
  4244. * Updates the given vector "result" from the starting index of the given Float32Array.
  4245. */
  4246. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4247. Vector4.FromArrayToRef(array, offset, result);
  4248. };
  4249. /**
  4250. * Updates the given vector "result" coordinates from the given floats.
  4251. */
  4252. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4253. result.x = x;
  4254. result.y = y;
  4255. result.z = z;
  4256. result.w = w;
  4257. };
  4258. /**
  4259. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4260. */
  4261. Vector4.Zero = function () {
  4262. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4263. };
  4264. /**
  4265. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4266. */
  4267. Vector4.One = function () {
  4268. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4269. };
  4270. /**
  4271. * Returns a new normalized Vector4 from the given one.
  4272. */
  4273. Vector4.Normalize = function (vector) {
  4274. var result = Vector4.Zero();
  4275. Vector4.NormalizeToRef(vector, result);
  4276. return result;
  4277. };
  4278. /**
  4279. * Updates the given vector "result" from the normalization of the given one.
  4280. */
  4281. Vector4.NormalizeToRef = function (vector, result) {
  4282. result.copyFrom(vector);
  4283. result.normalize();
  4284. };
  4285. Vector4.Minimize = function (left, right) {
  4286. var min = left.clone();
  4287. min.minimizeInPlace(right);
  4288. return min;
  4289. };
  4290. Vector4.Maximize = function (left, right) {
  4291. var max = left.clone();
  4292. max.maximizeInPlace(right);
  4293. return max;
  4294. };
  4295. /**
  4296. * Returns the distance (float) between the vectors "value1" and "value2".
  4297. */
  4298. Vector4.Distance = function (value1, value2) {
  4299. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4300. };
  4301. /**
  4302. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4303. */
  4304. Vector4.DistanceSquared = function (value1, value2) {
  4305. var x = value1.x - value2.x;
  4306. var y = value1.y - value2.y;
  4307. var z = value1.z - value2.z;
  4308. var w = value1.w - value2.w;
  4309. return (x * x) + (y * y) + (z * z) + (w * w);
  4310. };
  4311. /**
  4312. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4313. */
  4314. Vector4.Center = function (value1, value2) {
  4315. var center = value1.add(value2);
  4316. center.scaleInPlace(0.5);
  4317. return center;
  4318. };
  4319. /**
  4320. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4321. * This methods computes transformed normalized direction vectors only.
  4322. */
  4323. Vector4.TransformNormal = function (vector, transformation) {
  4324. var result = Vector4.Zero();
  4325. Vector4.TransformNormalToRef(vector, transformation, result);
  4326. return result;
  4327. };
  4328. /**
  4329. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4330. * This methods computes transformed normalized direction vectors only.
  4331. */
  4332. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4333. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4334. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4335. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4336. result.x = x;
  4337. result.y = y;
  4338. result.z = z;
  4339. result.w = vector.w;
  4340. };
  4341. /**
  4342. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4343. * This methods computes transformed normalized direction vectors only.
  4344. */
  4345. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4346. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4347. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4348. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4349. result.w = w;
  4350. };
  4351. return Vector4;
  4352. }());
  4353. BABYLON.Vector4 = Vector4;
  4354. var Size = /** @class */ (function () {
  4355. /**
  4356. * Creates a Size object from the given width and height (floats).
  4357. */
  4358. function Size(width, height) {
  4359. this.width = width;
  4360. this.height = height;
  4361. }
  4362. // Returns a string with the Size width and height.
  4363. Size.prototype.toString = function () {
  4364. return "{W: " + this.width + ", H: " + this.height + "}";
  4365. };
  4366. /**
  4367. * Returns the string "Size"
  4368. */
  4369. Size.prototype.getClassName = function () {
  4370. return "Size";
  4371. };
  4372. /**
  4373. * Returns the Size hash code.
  4374. */
  4375. Size.prototype.getHashCode = function () {
  4376. var hash = this.width || 0;
  4377. hash = (hash * 397) ^ (this.height || 0);
  4378. return hash;
  4379. };
  4380. /**
  4381. * Updates the current size from the given one.
  4382. * Returns the updated Size.
  4383. */
  4384. Size.prototype.copyFrom = function (src) {
  4385. this.width = src.width;
  4386. this.height = src.height;
  4387. };
  4388. /**
  4389. * Updates in place the current Size from the given floats.
  4390. * Returns the updated Size.
  4391. */
  4392. Size.prototype.copyFromFloats = function (width, height) {
  4393. this.width = width;
  4394. this.height = height;
  4395. return this;
  4396. };
  4397. /**
  4398. * Updates in place the current Size from the given floats.
  4399. * Returns the updated Size.
  4400. */
  4401. Size.prototype.set = function (width, height) {
  4402. return this.copyFromFloats(width, height);
  4403. };
  4404. /**
  4405. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4406. */
  4407. Size.prototype.multiplyByFloats = function (w, h) {
  4408. return new Size(this.width * w, this.height * h);
  4409. };
  4410. /**
  4411. * Returns a new Size copied from the given one.
  4412. */
  4413. Size.prototype.clone = function () {
  4414. return new Size(this.width, this.height);
  4415. };
  4416. /**
  4417. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4418. */
  4419. Size.prototype.equals = function (other) {
  4420. if (!other) {
  4421. return false;
  4422. }
  4423. return (this.width === other.width) && (this.height === other.height);
  4424. };
  4425. Object.defineProperty(Size.prototype, "surface", {
  4426. /**
  4427. * Returns the surface of the Size : width * height (float).
  4428. */
  4429. get: function () {
  4430. return this.width * this.height;
  4431. },
  4432. enumerable: true,
  4433. configurable: true
  4434. });
  4435. /**
  4436. * Returns a new Size set to (0.0, 0.0)
  4437. */
  4438. Size.Zero = function () {
  4439. return new Size(0.0, 0.0);
  4440. };
  4441. /**
  4442. * Returns a new Size set as the addition result of the current Size and the given one.
  4443. */
  4444. Size.prototype.add = function (otherSize) {
  4445. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4446. return r;
  4447. };
  4448. /**
  4449. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4450. */
  4451. Size.prototype.subtract = function (otherSize) {
  4452. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4453. return r;
  4454. };
  4455. /**
  4456. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4457. */
  4458. Size.Lerp = function (start, end, amount) {
  4459. var w = start.width + ((end.width - start.width) * amount);
  4460. var h = start.height + ((end.height - start.height) * amount);
  4461. return new Size(w, h);
  4462. };
  4463. return Size;
  4464. }());
  4465. BABYLON.Size = Size;
  4466. /**
  4467. * Class used to store quaternion data
  4468. * @see https://en.wikipedia.org/wiki/Quaternion
  4469. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4470. */
  4471. var Quaternion = /** @class */ (function () {
  4472. /**
  4473. * Creates a new Quaternion from the given floats
  4474. * @param x defines the first component (0 by default)
  4475. * @param y defines the second component (0 by default)
  4476. * @param z defines the third component (0 by default)
  4477. * @param w defines the fourth component (1.0 by default)
  4478. */
  4479. function Quaternion(
  4480. /** defines the first component (0 by default) */
  4481. x,
  4482. /** defines the second component (0 by default) */
  4483. y,
  4484. /** defines the third component (0 by default) */
  4485. z,
  4486. /** defines the fourth component (1.0 by default) */
  4487. w) {
  4488. if (x === void 0) { x = 0.0; }
  4489. if (y === void 0) { y = 0.0; }
  4490. if (z === void 0) { z = 0.0; }
  4491. if (w === void 0) { w = 1.0; }
  4492. this.x = x;
  4493. this.y = y;
  4494. this.z = z;
  4495. this.w = w;
  4496. }
  4497. /**
  4498. * Gets a string representation for the current quaternion
  4499. * @returns a string with the Quaternion coordinates
  4500. */
  4501. Quaternion.prototype.toString = function () {
  4502. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4503. };
  4504. /**
  4505. * Gets the class name of the quaternion
  4506. * @returns the string "Quaternion"
  4507. */
  4508. Quaternion.prototype.getClassName = function () {
  4509. return "Quaternion";
  4510. };
  4511. /**
  4512. * Gets a hash code for this quaternion
  4513. * @returns the quaternion hash code
  4514. */
  4515. Quaternion.prototype.getHashCode = function () {
  4516. var hash = this.x || 0;
  4517. hash = (hash * 397) ^ (this.y || 0);
  4518. hash = (hash * 397) ^ (this.z || 0);
  4519. hash = (hash * 397) ^ (this.w || 0);
  4520. return hash;
  4521. };
  4522. /**
  4523. * Copy the quaternion to an array
  4524. * @returns a new array populated with 4 elements from the quaternion coordinates
  4525. */
  4526. Quaternion.prototype.asArray = function () {
  4527. return [this.x, this.y, this.z, this.w];
  4528. };
  4529. /**
  4530. * Check if two quaternions are equals
  4531. * @param otherQuaternion defines the second operand
  4532. * @return true if the current quaternion and the given one coordinates are strictly equals
  4533. */
  4534. Quaternion.prototype.equals = function (otherQuaternion) {
  4535. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4536. };
  4537. /**
  4538. * Clone the current quaternion
  4539. * @returns a new quaternion copied from the current one
  4540. */
  4541. Quaternion.prototype.clone = function () {
  4542. return new Quaternion(this.x, this.y, this.z, this.w);
  4543. };
  4544. /**
  4545. * Copy a quaternion to the current one
  4546. * @param other defines the other quaternion
  4547. * @returns the updated current quaternion
  4548. */
  4549. Quaternion.prototype.copyFrom = function (other) {
  4550. this.x = other.x;
  4551. this.y = other.y;
  4552. this.z = other.z;
  4553. this.w = other.w;
  4554. return this;
  4555. };
  4556. /**
  4557. * Updates the current quaternion with the given float coordinates
  4558. * @param x defines the x coordinate
  4559. * @param y defines the y coordinate
  4560. * @param z defines the z coordinate
  4561. * @param w defines the w coordinate
  4562. * @returns the updated current quaternion
  4563. */
  4564. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4565. this.x = x;
  4566. this.y = y;
  4567. this.z = z;
  4568. this.w = w;
  4569. return this;
  4570. };
  4571. /**
  4572. * Updates the current quaternion from the given float coordinates
  4573. * @param x defines the x coordinate
  4574. * @param y defines the y coordinate
  4575. * @param z defines the z coordinate
  4576. * @param w defines the w coordinate
  4577. * @returns the updated current quaternion
  4578. */
  4579. Quaternion.prototype.set = function (x, y, z, w) {
  4580. return this.copyFromFloats(x, y, z, w);
  4581. };
  4582. /**
  4583. * Adds two quaternions
  4584. * @param other defines the second operand
  4585. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4586. */
  4587. Quaternion.prototype.add = function (other) {
  4588. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4589. };
  4590. /**
  4591. * Add a quaternion to the current one
  4592. * @param other defines the quaternion to add
  4593. * @returns the current quaternion
  4594. */
  4595. Quaternion.prototype.addInPlace = function (other) {
  4596. this.x += other.x;
  4597. this.y += other.y;
  4598. this.z += other.z;
  4599. this.w += other.w;
  4600. return this;
  4601. };
  4602. /**
  4603. * Subtract two quaternions
  4604. * @param other defines the second operand
  4605. * @returns a new quaternion as the subtraction result of the given one from the current one
  4606. */
  4607. Quaternion.prototype.subtract = function (other) {
  4608. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4609. };
  4610. /**
  4611. * Multiplies the current quaternion by a scale factor
  4612. * @param value defines the scale factor
  4613. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4614. */
  4615. Quaternion.prototype.scale = function (value) {
  4616. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4617. };
  4618. /**
  4619. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4620. * @param scale defines the scale factor
  4621. * @param result defines the Quaternion object where to store the result
  4622. * @returns the unmodified current quaternion
  4623. */
  4624. Quaternion.prototype.scaleToRef = function (scale, result) {
  4625. result.x = this.x * scale;
  4626. result.y = this.y * scale;
  4627. result.z = this.z * scale;
  4628. result.w = this.w * scale;
  4629. return this;
  4630. };
  4631. /**
  4632. * Multiplies in place the current quaternion by a scale factor
  4633. * @param value defines the scale factor
  4634. * @returns the current modified quaternion
  4635. */
  4636. Quaternion.prototype.scaleInPlace = function (value) {
  4637. this.x *= value;
  4638. this.y *= value;
  4639. this.z *= value;
  4640. this.w *= value;
  4641. return this;
  4642. };
  4643. /**
  4644. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4645. * @param scale defines the scale factor
  4646. * @param result defines the Quaternion object where to store the result
  4647. * @returns the unmodified current quaternion
  4648. */
  4649. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4650. result.x += this.x * scale;
  4651. result.y += this.y * scale;
  4652. result.z += this.z * scale;
  4653. result.w += this.w * scale;
  4654. return this;
  4655. };
  4656. /**
  4657. * Multiplies two quaternions
  4658. * @param q1 defines the second operand
  4659. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4660. */
  4661. Quaternion.prototype.multiply = function (q1) {
  4662. var result = new Quaternion(0, 0, 0, 1.0);
  4663. this.multiplyToRef(q1, result);
  4664. return result;
  4665. };
  4666. /**
  4667. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4668. * @param q1 defines the second operand
  4669. * @param result defines the target quaternion
  4670. * @returns the current quaternion
  4671. */
  4672. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4673. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4674. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4675. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4676. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4677. result.copyFromFloats(x, y, z, w);
  4678. return this;
  4679. };
  4680. /**
  4681. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4682. * @param q1 defines the second operand
  4683. * @returns the currentupdated quaternion
  4684. */
  4685. Quaternion.prototype.multiplyInPlace = function (q1) {
  4686. this.multiplyToRef(q1, this);
  4687. return this;
  4688. };
  4689. /**
  4690. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4691. * @param ref defines the target quaternion
  4692. * @returns the current quaternion
  4693. */
  4694. Quaternion.prototype.conjugateToRef = function (ref) {
  4695. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4696. return this;
  4697. };
  4698. /**
  4699. * Conjugates in place (1-q) the current quaternion
  4700. * @returns the current updated quaternion
  4701. */
  4702. Quaternion.prototype.conjugateInPlace = function () {
  4703. this.x *= -1;
  4704. this.y *= -1;
  4705. this.z *= -1;
  4706. return this;
  4707. };
  4708. /**
  4709. * Conjugates in place (1-q) the current quaternion
  4710. * @returns a new quaternion
  4711. */
  4712. Quaternion.prototype.conjugate = function () {
  4713. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4714. return result;
  4715. };
  4716. /**
  4717. * Gets length of current quaternion
  4718. * @returns the quaternion length (float)
  4719. */
  4720. Quaternion.prototype.length = function () {
  4721. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4722. };
  4723. /**
  4724. * Normalize in place the current quaternion
  4725. * @returns the current updated quaternion
  4726. */
  4727. Quaternion.prototype.normalize = function () {
  4728. var length = 1.0 / this.length();
  4729. this.x *= length;
  4730. this.y *= length;
  4731. this.z *= length;
  4732. this.w *= length;
  4733. return this;
  4734. };
  4735. /**
  4736. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4737. * @param order is a reserved parameter and is ignore for now
  4738. * @returns a new Vector3 containing the Euler angles
  4739. */
  4740. Quaternion.prototype.toEulerAngles = function (order) {
  4741. if (order === void 0) { order = "YZX"; }
  4742. var result = Vector3.Zero();
  4743. this.toEulerAnglesToRef(result, order);
  4744. return result;
  4745. };
  4746. /**
  4747. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4748. * @param result defines the vector which will be filled with the Euler angles
  4749. * @param order is a reserved parameter and is ignore for now
  4750. * @returns the current unchanged quaternion
  4751. */
  4752. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4753. if (order === void 0) { order = "YZX"; }
  4754. var qz = this.z;
  4755. var qx = this.x;
  4756. var qy = this.y;
  4757. var qw = this.w;
  4758. var sqw = qw * qw;
  4759. var sqz = qz * qz;
  4760. var sqx = qx * qx;
  4761. var sqy = qy * qy;
  4762. var zAxisY = qy * qz - qx * qw;
  4763. var limit = .4999999;
  4764. if (zAxisY < -limit) {
  4765. result.y = 2 * Math.atan2(qy, qw);
  4766. result.x = Math.PI / 2;
  4767. result.z = 0;
  4768. }
  4769. else if (zAxisY > limit) {
  4770. result.y = 2 * Math.atan2(qy, qw);
  4771. result.x = -Math.PI / 2;
  4772. result.z = 0;
  4773. }
  4774. else {
  4775. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4776. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4777. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4778. }
  4779. return this;
  4780. };
  4781. /**
  4782. * Updates the given rotation matrix with the current quaternion values
  4783. * @param result defines the target matrix
  4784. * @returns the current unchanged quaternion
  4785. */
  4786. Quaternion.prototype.toRotationMatrix = function (result) {
  4787. var xx = this.x * this.x;
  4788. var yy = this.y * this.y;
  4789. var zz = this.z * this.z;
  4790. var xy = this.x * this.y;
  4791. var zw = this.z * this.w;
  4792. var zx = this.z * this.x;
  4793. var yw = this.y * this.w;
  4794. var yz = this.y * this.z;
  4795. var xw = this.x * this.w;
  4796. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4797. result.m[1] = 2.0 * (xy + zw);
  4798. result.m[2] = 2.0 * (zx - yw);
  4799. result.m[3] = 0;
  4800. result.m[4] = 2.0 * (xy - zw);
  4801. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4802. result.m[6] = 2.0 * (yz + xw);
  4803. result.m[7] = 0;
  4804. result.m[8] = 2.0 * (zx + yw);
  4805. result.m[9] = 2.0 * (yz - xw);
  4806. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4807. result.m[11] = 0;
  4808. result.m[12] = 0;
  4809. result.m[13] = 0;
  4810. result.m[14] = 0;
  4811. result.m[15] = 1.0;
  4812. result._markAsUpdated();
  4813. return this;
  4814. };
  4815. /**
  4816. * Updates the current quaternion from the given rotation matrix values
  4817. * @param matrix defines the source matrix
  4818. * @returns the current updated quaternion
  4819. */
  4820. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4821. Quaternion.FromRotationMatrixToRef(matrix, this);
  4822. return this;
  4823. };
  4824. // Statics
  4825. /**
  4826. * Creates a new quaternion from a rotation matrix
  4827. * @param matrix defines the source matrix
  4828. * @returns a new quaternion created from the given rotation matrix values
  4829. */
  4830. Quaternion.FromRotationMatrix = function (matrix) {
  4831. var result = new Quaternion();
  4832. Quaternion.FromRotationMatrixToRef(matrix, result);
  4833. return result;
  4834. };
  4835. /**
  4836. * Updates the given quaternion with the given rotation matrix values
  4837. * @param matrix defines the source matrix
  4838. * @param result defines the target quaternion
  4839. */
  4840. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4841. var data = matrix.m;
  4842. var m11 = data[0], m12 = data[4], m13 = data[8];
  4843. var m21 = data[1], m22 = data[5], m23 = data[9];
  4844. var m31 = data[2], m32 = data[6], m33 = data[10];
  4845. var trace = m11 + m22 + m33;
  4846. var s;
  4847. if (trace > 0) {
  4848. s = 0.5 / Math.sqrt(trace + 1.0);
  4849. result.w = 0.25 / s;
  4850. result.x = (m32 - m23) * s;
  4851. result.y = (m13 - m31) * s;
  4852. result.z = (m21 - m12) * s;
  4853. }
  4854. else if (m11 > m22 && m11 > m33) {
  4855. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4856. result.w = (m32 - m23) / s;
  4857. result.x = 0.25 * s;
  4858. result.y = (m12 + m21) / s;
  4859. result.z = (m13 + m31) / s;
  4860. }
  4861. else if (m22 > m33) {
  4862. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4863. result.w = (m13 - m31) / s;
  4864. result.x = (m12 + m21) / s;
  4865. result.y = 0.25 * s;
  4866. result.z = (m23 + m32) / s;
  4867. }
  4868. else {
  4869. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4870. result.w = (m21 - m12) / s;
  4871. result.x = (m13 + m31) / s;
  4872. result.y = (m23 + m32) / s;
  4873. result.z = 0.25 * s;
  4874. }
  4875. };
  4876. /**
  4877. * Returns the dot product (float) between the quaternions "left" and "right"
  4878. * @param left defines the left operand
  4879. * @param right defines the right operand
  4880. * @returns the dot product
  4881. */
  4882. Quaternion.Dot = function (left, right) {
  4883. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4884. };
  4885. /**
  4886. * Checks if the two quaternions are close to each other
  4887. * @param quat0 defines the first quaternion to check
  4888. * @param quat1 defines the second quaternion to check
  4889. * @returns true if the two quaternions are close to each other
  4890. */
  4891. Quaternion.AreClose = function (quat0, quat1) {
  4892. var dot = Quaternion.Dot(quat0, quat1);
  4893. return dot >= 0;
  4894. };
  4895. /**
  4896. * Creates an empty quaternion
  4897. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4898. */
  4899. Quaternion.Zero = function () {
  4900. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4901. };
  4902. /**
  4903. * Inverse a given quaternion
  4904. * @param q defines the source quaternion
  4905. * @returns a new quaternion as the inverted current quaternion
  4906. */
  4907. Quaternion.Inverse = function (q) {
  4908. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4909. };
  4910. /**
  4911. * Creates an identity quaternion
  4912. * @returns the identity quaternion
  4913. */
  4914. Quaternion.Identity = function () {
  4915. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4916. };
  4917. /**
  4918. * Gets a boolean indicating if the given quaternion is identity
  4919. * @param quaternion defines the quaternion to check
  4920. * @returns true if the quaternion is identity
  4921. */
  4922. Quaternion.IsIdentity = function (quaternion) {
  4923. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4924. };
  4925. /**
  4926. * Creates a quaternion from a rotation around an axis
  4927. * @param axis defines the axis to use
  4928. * @param angle defines the angle to use
  4929. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4930. */
  4931. Quaternion.RotationAxis = function (axis, angle) {
  4932. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4933. };
  4934. /**
  4935. * Creates a rotation around an axis and stores it into the given quaternion
  4936. * @param axis defines the axis to use
  4937. * @param angle defines the angle to use
  4938. * @param result defines the target quaternion
  4939. * @returns the target quaternion
  4940. */
  4941. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4942. var sin = Math.sin(angle / 2);
  4943. axis.normalize();
  4944. result.w = Math.cos(angle / 2);
  4945. result.x = axis.x * sin;
  4946. result.y = axis.y * sin;
  4947. result.z = axis.z * sin;
  4948. return result;
  4949. };
  4950. /**
  4951. * Creates a new quaternion from data stored into an array
  4952. * @param array defines the data source
  4953. * @param offset defines the offset in the source array where the data starts
  4954. * @returns a new quaternion
  4955. */
  4956. Quaternion.FromArray = function (array, offset) {
  4957. if (!offset) {
  4958. offset = 0;
  4959. }
  4960. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4961. };
  4962. /**
  4963. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4964. * @param yaw defines the rotation around Y axis
  4965. * @param pitch defines the rotation around X axis
  4966. * @param roll defines the rotation around Z axis
  4967. * @returns the new quaternion
  4968. */
  4969. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4970. var q = new Quaternion();
  4971. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4972. return q;
  4973. };
  4974. /**
  4975. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4976. * @param yaw defines the rotation around Y axis
  4977. * @param pitch defines the rotation around X axis
  4978. * @param roll defines the rotation around Z axis
  4979. * @param result defines the target quaternion
  4980. */
  4981. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4982. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4983. var halfRoll = roll * 0.5;
  4984. var halfPitch = pitch * 0.5;
  4985. var halfYaw = yaw * 0.5;
  4986. var sinRoll = Math.sin(halfRoll);
  4987. var cosRoll = Math.cos(halfRoll);
  4988. var sinPitch = Math.sin(halfPitch);
  4989. var cosPitch = Math.cos(halfPitch);
  4990. var sinYaw = Math.sin(halfYaw);
  4991. var cosYaw = Math.cos(halfYaw);
  4992. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4993. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4994. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4995. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4996. };
  4997. /**
  4998. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4999. * @param alpha defines the rotation around first axis
  5000. * @param beta defines the rotation around second axis
  5001. * @param gamma defines the rotation around third axis
  5002. * @returns the new quaternion
  5003. */
  5004. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5005. var result = new Quaternion();
  5006. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5007. return result;
  5008. };
  5009. /**
  5010. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5011. * @param alpha defines the rotation around first axis
  5012. * @param beta defines the rotation around second axis
  5013. * @param gamma defines the rotation around third axis
  5014. * @param result defines the target quaternion
  5015. */
  5016. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5017. // Produces a quaternion from Euler angles in the z-x-z orientation
  5018. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5019. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5020. var halfBeta = beta * 0.5;
  5021. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5022. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5023. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5024. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5025. };
  5026. /**
  5027. * 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)
  5028. * @param axis1 defines the first axis
  5029. * @param axis2 defines the second axis
  5030. * @param axis3 defines the third axis
  5031. * @returns the new quaternion
  5032. */
  5033. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5034. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5035. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5036. return quat;
  5037. };
  5038. /**
  5039. * 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
  5040. * @param axis1 defines the first axis
  5041. * @param axis2 defines the second axis
  5042. * @param axis3 defines the third axis
  5043. * @param ref defines the target quaternion
  5044. */
  5045. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5046. var rotMat = MathTmp.Matrix[0];
  5047. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5048. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5049. };
  5050. /**
  5051. * Interpolates between two quaternions
  5052. * @param left defines first quaternion
  5053. * @param right defines second quaternion
  5054. * @param amount defines the gradient to use
  5055. * @returns the new interpolated quaternion
  5056. */
  5057. Quaternion.Slerp = function (left, right, amount) {
  5058. var result = Quaternion.Identity();
  5059. Quaternion.SlerpToRef(left, right, amount, result);
  5060. return result;
  5061. };
  5062. /**
  5063. * Interpolates between two quaternions and stores it into a target quaternion
  5064. * @param left defines first quaternion
  5065. * @param right defines second quaternion
  5066. * @param amount defines the gradient to use
  5067. * @param result defines the target quaternion
  5068. */
  5069. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5070. var num2;
  5071. var num3;
  5072. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5073. var flag = false;
  5074. if (num4 < 0) {
  5075. flag = true;
  5076. num4 = -num4;
  5077. }
  5078. if (num4 > 0.999999) {
  5079. num3 = 1 - amount;
  5080. num2 = flag ? -amount : amount;
  5081. }
  5082. else {
  5083. var num5 = Math.acos(num4);
  5084. var num6 = (1.0 / Math.sin(num5));
  5085. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5086. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5087. }
  5088. result.x = (num3 * left.x) + (num2 * right.x);
  5089. result.y = (num3 * left.y) + (num2 * right.y);
  5090. result.z = (num3 * left.z) + (num2 * right.z);
  5091. result.w = (num3 * left.w) + (num2 * right.w);
  5092. };
  5093. /**
  5094. * Interpolate between two quaternions using Hermite interpolation
  5095. * @param value1 defines first quaternion
  5096. * @param tangent1 defines the incoming tangent
  5097. * @param value2 defines second quaternion
  5098. * @param tangent2 defines the outgoing tangent
  5099. * @param amount defines the target quaternion
  5100. * @returns the new interpolated quaternion
  5101. */
  5102. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5103. var squared = amount * amount;
  5104. var cubed = amount * squared;
  5105. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5106. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5107. var part3 = (cubed - (2.0 * squared)) + amount;
  5108. var part4 = cubed - squared;
  5109. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5110. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5111. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5112. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5113. return new Quaternion(x, y, z, w);
  5114. };
  5115. return Quaternion;
  5116. }());
  5117. BABYLON.Quaternion = Quaternion;
  5118. /**
  5119. * Class used to store matrix data (4x4)
  5120. */
  5121. var Matrix = /** @class */ (function () {
  5122. /**
  5123. * Creates an empty matrix (filled with zeros)
  5124. */
  5125. function Matrix() {
  5126. this._isIdentity = false;
  5127. this._isIdentityDirty = true;
  5128. /**
  5129. * Gets or sets the internal data of the matrix
  5130. */
  5131. this.m = new Float32Array(16);
  5132. this._markAsUpdated();
  5133. }
  5134. /** @hidden */
  5135. Matrix.prototype._markAsUpdated = function () {
  5136. this.updateFlag = Matrix._updateFlagSeed++;
  5137. this._isIdentityDirty = true;
  5138. };
  5139. // Properties
  5140. /**
  5141. * Check if the current matrix is indentity
  5142. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5143. * @returns true is the matrix is the identity matrix
  5144. */
  5145. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5146. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5147. if (this._isIdentityDirty) {
  5148. this._isIdentityDirty = false;
  5149. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5150. this._isIdentity = false;
  5151. }
  5152. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5153. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5154. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5155. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5156. this._isIdentity = false;
  5157. }
  5158. else {
  5159. this._isIdentity = true;
  5160. }
  5161. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5162. this._isIdentity = false;
  5163. }
  5164. }
  5165. return this._isIdentity;
  5166. };
  5167. /**
  5168. * Gets the determinant of the matrix
  5169. * @returns the matrix determinant
  5170. */
  5171. Matrix.prototype.determinant = function () {
  5172. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5173. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5174. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5175. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5176. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5177. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5178. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5179. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5180. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5181. };
  5182. // Methods
  5183. /**
  5184. * Returns the matrix as a Float32Array
  5185. * @returns the matrix underlying array
  5186. */
  5187. Matrix.prototype.toArray = function () {
  5188. return this.m;
  5189. };
  5190. /**
  5191. * Returns the matrix as a Float32Array
  5192. * @returns the matrix underlying array.
  5193. */
  5194. Matrix.prototype.asArray = function () {
  5195. return this.toArray();
  5196. };
  5197. /**
  5198. * Inverts the current matrix in place
  5199. * @returns the current inverted matrix
  5200. */
  5201. Matrix.prototype.invert = function () {
  5202. this.invertToRef(this);
  5203. return this;
  5204. };
  5205. /**
  5206. * Sets all the matrix elements to zero
  5207. * @returns the current matrix
  5208. */
  5209. Matrix.prototype.reset = function () {
  5210. for (var index = 0; index < 16; index++) {
  5211. this.m[index] = 0.0;
  5212. }
  5213. this._markAsUpdated();
  5214. return this;
  5215. };
  5216. /**
  5217. * Adds the current matrix with a second one
  5218. * @param other defines the matrix to add
  5219. * @returns a new matrix as the addition of the current matrix and the given one
  5220. */
  5221. Matrix.prototype.add = function (other) {
  5222. var result = new Matrix();
  5223. this.addToRef(other, result);
  5224. return result;
  5225. };
  5226. /**
  5227. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5228. * @param other defines the matrix to add
  5229. * @param result defines the target matrix
  5230. * @returns the current matrix
  5231. */
  5232. Matrix.prototype.addToRef = function (other, result) {
  5233. for (var index = 0; index < 16; index++) {
  5234. result.m[index] = this.m[index] + other.m[index];
  5235. }
  5236. result._markAsUpdated();
  5237. return this;
  5238. };
  5239. /**
  5240. * Adds in place the given matrix to the current matrix
  5241. * @param other defines the second operand
  5242. * @returns the current updated matrix
  5243. */
  5244. Matrix.prototype.addToSelf = function (other) {
  5245. for (var index = 0; index < 16; index++) {
  5246. this.m[index] += other.m[index];
  5247. }
  5248. this._markAsUpdated();
  5249. return this;
  5250. };
  5251. /**
  5252. * Sets the given matrix to the current inverted Matrix
  5253. * @param other defines the target matrix
  5254. * @returns the unmodified current matrix
  5255. */
  5256. Matrix.prototype.invertToRef = function (other) {
  5257. var l1 = this.m[0];
  5258. var l2 = this.m[1];
  5259. var l3 = this.m[2];
  5260. var l4 = this.m[3];
  5261. var l5 = this.m[4];
  5262. var l6 = this.m[5];
  5263. var l7 = this.m[6];
  5264. var l8 = this.m[7];
  5265. var l9 = this.m[8];
  5266. var l10 = this.m[9];
  5267. var l11 = this.m[10];
  5268. var l12 = this.m[11];
  5269. var l13 = this.m[12];
  5270. var l14 = this.m[13];
  5271. var l15 = this.m[14];
  5272. var l16 = this.m[15];
  5273. var l17 = (l11 * l16) - (l12 * l15);
  5274. var l18 = (l10 * l16) - (l12 * l14);
  5275. var l19 = (l10 * l15) - (l11 * l14);
  5276. var l20 = (l9 * l16) - (l12 * l13);
  5277. var l21 = (l9 * l15) - (l11 * l13);
  5278. var l22 = (l9 * l14) - (l10 * l13);
  5279. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5280. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5281. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5282. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5283. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5284. var l28 = (l7 * l16) - (l8 * l15);
  5285. var l29 = (l6 * l16) - (l8 * l14);
  5286. var l30 = (l6 * l15) - (l7 * l14);
  5287. var l31 = (l5 * l16) - (l8 * l13);
  5288. var l32 = (l5 * l15) - (l7 * l13);
  5289. var l33 = (l5 * l14) - (l6 * l13);
  5290. var l34 = (l7 * l12) - (l8 * l11);
  5291. var l35 = (l6 * l12) - (l8 * l10);
  5292. var l36 = (l6 * l11) - (l7 * l10);
  5293. var l37 = (l5 * l12) - (l8 * l9);
  5294. var l38 = (l5 * l11) - (l7 * l9);
  5295. var l39 = (l5 * l10) - (l6 * l9);
  5296. other.m[0] = l23 * l27;
  5297. other.m[4] = l24 * l27;
  5298. other.m[8] = l25 * l27;
  5299. other.m[12] = l26 * l27;
  5300. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5301. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5302. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5303. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5304. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5305. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5306. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5307. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5308. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5309. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5310. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5311. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5312. other._markAsUpdated();
  5313. return this;
  5314. };
  5315. /**
  5316. * Inserts the translation vector (using 3 floats) in the current matrix
  5317. * @param x defines the 1st component of the translation
  5318. * @param y defines the 2nd component of the translation
  5319. * @param z defines the 3rd component of the translation
  5320. * @returns the current updated matrix
  5321. */
  5322. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5323. this.m[12] = x;
  5324. this.m[13] = y;
  5325. this.m[14] = z;
  5326. this._markAsUpdated();
  5327. return this;
  5328. };
  5329. /**
  5330. * Inserts the translation vector in the current matrix
  5331. * @param vector3 defines the translation to insert
  5332. * @returns the current updated matrix
  5333. */
  5334. Matrix.prototype.setTranslation = function (vector3) {
  5335. this.m[12] = vector3.x;
  5336. this.m[13] = vector3.y;
  5337. this.m[14] = vector3.z;
  5338. this._markAsUpdated();
  5339. return this;
  5340. };
  5341. /**
  5342. * Gets the translation value of the current matrix
  5343. * @returns a new Vector3 as the extracted translation from the matrix
  5344. */
  5345. Matrix.prototype.getTranslation = function () {
  5346. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5347. };
  5348. /**
  5349. * Fill a Vector3 with the extracted translation from the matrix
  5350. * @param result defines the Vector3 where to store the translation
  5351. * @returns the current matrix
  5352. */
  5353. Matrix.prototype.getTranslationToRef = function (result) {
  5354. result.x = this.m[12];
  5355. result.y = this.m[13];
  5356. result.z = this.m[14];
  5357. return this;
  5358. };
  5359. /**
  5360. * Remove rotation and scaling part from the matrix
  5361. * @returns the updated matrix
  5362. */
  5363. Matrix.prototype.removeRotationAndScaling = function () {
  5364. this.setRowFromFloats(0, 1, 0, 0, 0);
  5365. this.setRowFromFloats(1, 0, 1, 0, 0);
  5366. this.setRowFromFloats(2, 0, 0, 1, 0);
  5367. return this;
  5368. };
  5369. /**
  5370. * Multiply two matrices
  5371. * @param other defines the second operand
  5372. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5373. */
  5374. Matrix.prototype.multiply = function (other) {
  5375. var result = new Matrix();
  5376. this.multiplyToRef(other, result);
  5377. return result;
  5378. };
  5379. /**
  5380. * Copy the current matrix from the given one
  5381. * @param other defines the source matrix
  5382. * @returns the current updated matrix
  5383. */
  5384. Matrix.prototype.copyFrom = function (other) {
  5385. for (var index = 0; index < 16; index++) {
  5386. this.m[index] = other.m[index];
  5387. }
  5388. this._markAsUpdated();
  5389. return this;
  5390. };
  5391. /**
  5392. * Populates the given array from the starting index with the current matrix values
  5393. * @param array defines the target array
  5394. * @param offset defines the offset in the target array where to start storing values
  5395. * @returns the current matrix
  5396. */
  5397. Matrix.prototype.copyToArray = function (array, offset) {
  5398. if (offset === void 0) { offset = 0; }
  5399. for (var index = 0; index < 16; index++) {
  5400. array[offset + index] = this.m[index];
  5401. }
  5402. return this;
  5403. };
  5404. /**
  5405. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5406. * @param other defines the second operand
  5407. * @param result defines the matrix where to store the multiplication
  5408. * @returns the current matrix
  5409. */
  5410. Matrix.prototype.multiplyToRef = function (other, result) {
  5411. this.multiplyToArray(other, result.m, 0);
  5412. result._markAsUpdated();
  5413. return this;
  5414. };
  5415. /**
  5416. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5417. * @param other defines the second operand
  5418. * @param result defines the array where to store the multiplication
  5419. * @param offset defines the offset in the target array where to start storing values
  5420. * @returns the current matrix
  5421. */
  5422. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5423. var tm0 = this.m[0];
  5424. var tm1 = this.m[1];
  5425. var tm2 = this.m[2];
  5426. var tm3 = this.m[3];
  5427. var tm4 = this.m[4];
  5428. var tm5 = this.m[5];
  5429. var tm6 = this.m[6];
  5430. var tm7 = this.m[7];
  5431. var tm8 = this.m[8];
  5432. var tm9 = this.m[9];
  5433. var tm10 = this.m[10];
  5434. var tm11 = this.m[11];
  5435. var tm12 = this.m[12];
  5436. var tm13 = this.m[13];
  5437. var tm14 = this.m[14];
  5438. var tm15 = this.m[15];
  5439. var om0 = other.m[0];
  5440. var om1 = other.m[1];
  5441. var om2 = other.m[2];
  5442. var om3 = other.m[3];
  5443. var om4 = other.m[4];
  5444. var om5 = other.m[5];
  5445. var om6 = other.m[6];
  5446. var om7 = other.m[7];
  5447. var om8 = other.m[8];
  5448. var om9 = other.m[9];
  5449. var om10 = other.m[10];
  5450. var om11 = other.m[11];
  5451. var om12 = other.m[12];
  5452. var om13 = other.m[13];
  5453. var om14 = other.m[14];
  5454. var om15 = other.m[15];
  5455. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5456. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5457. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5458. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5459. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5460. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5461. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5462. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5463. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5464. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5465. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5466. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5467. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5468. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5469. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5470. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5471. return this;
  5472. };
  5473. /**
  5474. * Check equality between this matrix and a second one
  5475. * @param value defines the second matrix to compare
  5476. * @returns true is the current matrix and the given one values are strictly equal
  5477. */
  5478. Matrix.prototype.equals = function (value) {
  5479. return value &&
  5480. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5481. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5482. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5483. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5484. };
  5485. /**
  5486. * Clone the current matrix
  5487. * @returns a new matrix from the current matrix
  5488. */
  5489. Matrix.prototype.clone = function () {
  5490. 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]);
  5491. };
  5492. /**
  5493. * Returns the name of the current matrix class
  5494. * @returns the string "Matrix"
  5495. */
  5496. Matrix.prototype.getClassName = function () {
  5497. return "Matrix";
  5498. };
  5499. /**
  5500. * Gets the hash code of the current matrix
  5501. * @returns the hash code
  5502. */
  5503. Matrix.prototype.getHashCode = function () {
  5504. var hash = this.m[0] || 0;
  5505. for (var i = 1; i < 16; i++) {
  5506. hash = (hash * 397) ^ (this.m[i] || 0);
  5507. }
  5508. return hash;
  5509. };
  5510. /**
  5511. * Decomposes the current Matrix into a translation, rotation and scaling components
  5512. * @param scale defines the scale vector3 given as a reference to update
  5513. * @param rotation defines the rotation quaternion given as a reference to update
  5514. * @param translation defines the translation vector3 given as a reference to update
  5515. * @returns true if operation was successful
  5516. */
  5517. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5518. if (translation) {
  5519. translation.x = this.m[12];
  5520. translation.y = this.m[13];
  5521. translation.z = this.m[14];
  5522. }
  5523. scale = scale || MathTmp.Vector3[0];
  5524. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5525. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5526. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5527. if (this.determinant() <= 0) {
  5528. scale.y *= -1;
  5529. }
  5530. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5531. if (rotation) {
  5532. rotation.x = 0;
  5533. rotation.y = 0;
  5534. rotation.z = 0;
  5535. rotation.w = 1;
  5536. }
  5537. return false;
  5538. }
  5539. if (rotation) {
  5540. 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]);
  5541. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5542. }
  5543. return true;
  5544. };
  5545. /**
  5546. * Gets specific row of the matrix
  5547. * @param index defines the number of the row to get
  5548. * @returns the index-th row of the current matrix as a new Vector4
  5549. */
  5550. Matrix.prototype.getRow = function (index) {
  5551. if (index < 0 || index > 3) {
  5552. return null;
  5553. }
  5554. var i = index * 4;
  5555. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5556. };
  5557. /**
  5558. * Sets the index-th row of the current matrix to the vector4 values
  5559. * @param index defines the number of the row to set
  5560. * @param row defines the target vector4
  5561. * @returns the updated current matrix
  5562. */
  5563. Matrix.prototype.setRow = function (index, row) {
  5564. if (index < 0 || index > 3) {
  5565. return this;
  5566. }
  5567. var i = index * 4;
  5568. this.m[i + 0] = row.x;
  5569. this.m[i + 1] = row.y;
  5570. this.m[i + 2] = row.z;
  5571. this.m[i + 3] = row.w;
  5572. this._markAsUpdated();
  5573. return this;
  5574. };
  5575. /**
  5576. * Compute the transpose of the matrix
  5577. * @returns the new transposed matrix
  5578. */
  5579. Matrix.prototype.transpose = function () {
  5580. return Matrix.Transpose(this);
  5581. };
  5582. /**
  5583. * Compute the transpose of the matrix and store it in a given matrix
  5584. * @param result defines the target matrix
  5585. * @returns the current matrix
  5586. */
  5587. Matrix.prototype.transposeToRef = function (result) {
  5588. Matrix.TransposeToRef(this, result);
  5589. return this;
  5590. };
  5591. /**
  5592. * Sets the index-th row of the current matrix with the given 4 x float values
  5593. * @param index defines the row index
  5594. * @param x defines the x component to set
  5595. * @param y defines the y component to set
  5596. * @param z defines the z component to set
  5597. * @param w defines the w component to set
  5598. * @returns the updated current matrix
  5599. */
  5600. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5601. if (index < 0 || index > 3) {
  5602. return this;
  5603. }
  5604. var i = index * 4;
  5605. this.m[i + 0] = x;
  5606. this.m[i + 1] = y;
  5607. this.m[i + 2] = z;
  5608. this.m[i + 3] = w;
  5609. this._markAsUpdated();
  5610. return this;
  5611. };
  5612. /**
  5613. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5614. * @param scale defines the scale factor
  5615. * @returns a new matrix
  5616. */
  5617. Matrix.prototype.scale = function (scale) {
  5618. var result = new Matrix();
  5619. this.scaleToRef(scale, result);
  5620. return result;
  5621. };
  5622. /**
  5623. * Scale the current matrix values by a factor to a given result matrix
  5624. * @param scale defines the scale factor
  5625. * @param result defines the matrix to store the result
  5626. * @returns the current matrix
  5627. */
  5628. Matrix.prototype.scaleToRef = function (scale, result) {
  5629. for (var index = 0; index < 16; index++) {
  5630. result.m[index] = this.m[index] * scale;
  5631. }
  5632. result._markAsUpdated();
  5633. return this;
  5634. };
  5635. /**
  5636. * Scale the current matrix values by a factor and add the result to a given matrix
  5637. * @param scale defines the scale factor
  5638. * @param result defines the Matrix to store the result
  5639. * @returns the current matrix
  5640. */
  5641. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5642. for (var index = 0; index < 16; index++) {
  5643. result.m[index] += this.m[index] * scale;
  5644. }
  5645. result._markAsUpdated();
  5646. return this;
  5647. };
  5648. /**
  5649. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5650. * @param ref matrix to store the result
  5651. */
  5652. Matrix.prototype.toNormalMatrix = function (ref) {
  5653. this.invertToRef(ref);
  5654. ref.transpose();
  5655. var m = ref.m;
  5656. 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);
  5657. };
  5658. /**
  5659. * Gets only rotation part of the current matrix
  5660. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5661. */
  5662. Matrix.prototype.getRotationMatrix = function () {
  5663. var result = Matrix.Identity();
  5664. this.getRotationMatrixToRef(result);
  5665. return result;
  5666. };
  5667. /**
  5668. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5669. * @param result defines the target matrix to store data to
  5670. * @returns the current matrix
  5671. */
  5672. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5673. var m = this.m;
  5674. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5675. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5676. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5677. if (this.determinant() <= 0) {
  5678. sy *= -1;
  5679. }
  5680. if (sx === 0 || sy === 0 || sz === 0) {
  5681. Matrix.IdentityToRef(result);
  5682. }
  5683. else {
  5684. 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);
  5685. }
  5686. return this;
  5687. };
  5688. // Statics
  5689. /**
  5690. * Creates a matrix from an array
  5691. * @param array defines the source array
  5692. * @param offset defines an offset in the source array
  5693. * @returns a new Matrix set from the starting index of the given array
  5694. */
  5695. Matrix.FromArray = function (array, offset) {
  5696. var result = new Matrix();
  5697. if (!offset) {
  5698. offset = 0;
  5699. }
  5700. Matrix.FromArrayToRef(array, offset, result);
  5701. return result;
  5702. };
  5703. /**
  5704. * Copy the content of an array into a given matrix
  5705. * @param array defines the source array
  5706. * @param offset defines an offset in the source array
  5707. * @param result defines the target matrix
  5708. */
  5709. Matrix.FromArrayToRef = function (array, offset, result) {
  5710. for (var index = 0; index < 16; index++) {
  5711. result.m[index] = array[index + offset];
  5712. }
  5713. result._markAsUpdated();
  5714. };
  5715. /**
  5716. * Stores an array into a matrix after having multiplied each component by a given factor
  5717. * @param array defines the source array
  5718. * @param offset defines the offset in the source array
  5719. * @param scale defines the scaling factor
  5720. * @param result defines the target matrix
  5721. */
  5722. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5723. for (var index = 0; index < 16; index++) {
  5724. result.m[index] = array[index + offset] * scale;
  5725. }
  5726. result._markAsUpdated();
  5727. };
  5728. /**
  5729. * Stores a list of values (16) inside a given matrix
  5730. * @param initialM11 defines 1st value of 1st row
  5731. * @param initialM12 defines 2nd value of 1st row
  5732. * @param initialM13 defines 3rd value of 1st row
  5733. * @param initialM14 defines 4th value of 1st row
  5734. * @param initialM21 defines 1st value of 2nd row
  5735. * @param initialM22 defines 2nd value of 2nd row
  5736. * @param initialM23 defines 3rd value of 2nd row
  5737. * @param initialM24 defines 4th value of 2nd row
  5738. * @param initialM31 defines 1st value of 3rd row
  5739. * @param initialM32 defines 2nd value of 3rd row
  5740. * @param initialM33 defines 3rd value of 3rd row
  5741. * @param initialM34 defines 4th value of 3rd row
  5742. * @param initialM41 defines 1st value of 4th row
  5743. * @param initialM42 defines 2nd value of 4th row
  5744. * @param initialM43 defines 3rd value of 4th row
  5745. * @param initialM44 defines 4th value of 4th row
  5746. * @param result defines the target matrix
  5747. */
  5748. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5749. result.m[0] = initialM11;
  5750. result.m[1] = initialM12;
  5751. result.m[2] = initialM13;
  5752. result.m[3] = initialM14;
  5753. result.m[4] = initialM21;
  5754. result.m[5] = initialM22;
  5755. result.m[6] = initialM23;
  5756. result.m[7] = initialM24;
  5757. result.m[8] = initialM31;
  5758. result.m[9] = initialM32;
  5759. result.m[10] = initialM33;
  5760. result.m[11] = initialM34;
  5761. result.m[12] = initialM41;
  5762. result.m[13] = initialM42;
  5763. result.m[14] = initialM43;
  5764. result.m[15] = initialM44;
  5765. result._markAsUpdated();
  5766. };
  5767. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5768. /**
  5769. * Gets an identity matrix that must not be updated
  5770. */
  5771. get: function () {
  5772. return Matrix._identityReadOnly;
  5773. },
  5774. enumerable: true,
  5775. configurable: true
  5776. });
  5777. /**
  5778. * Creates new matrix from a list of values (16)
  5779. * @param initialM11 defines 1st value of 1st row
  5780. * @param initialM12 defines 2nd value of 1st row
  5781. * @param initialM13 defines 3rd value of 1st row
  5782. * @param initialM14 defines 4th value of 1st row
  5783. * @param initialM21 defines 1st value of 2nd row
  5784. * @param initialM22 defines 2nd value of 2nd row
  5785. * @param initialM23 defines 3rd value of 2nd row
  5786. * @param initialM24 defines 4th value of 2nd row
  5787. * @param initialM31 defines 1st value of 3rd row
  5788. * @param initialM32 defines 2nd value of 3rd row
  5789. * @param initialM33 defines 3rd value of 3rd row
  5790. * @param initialM34 defines 4th value of 3rd row
  5791. * @param initialM41 defines 1st value of 4th row
  5792. * @param initialM42 defines 2nd value of 4th row
  5793. * @param initialM43 defines 3rd value of 4th row
  5794. * @param initialM44 defines 4th value of 4th row
  5795. * @returns the new matrix
  5796. */
  5797. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5798. var result = new Matrix();
  5799. result.m[0] = initialM11;
  5800. result.m[1] = initialM12;
  5801. result.m[2] = initialM13;
  5802. result.m[3] = initialM14;
  5803. result.m[4] = initialM21;
  5804. result.m[5] = initialM22;
  5805. result.m[6] = initialM23;
  5806. result.m[7] = initialM24;
  5807. result.m[8] = initialM31;
  5808. result.m[9] = initialM32;
  5809. result.m[10] = initialM33;
  5810. result.m[11] = initialM34;
  5811. result.m[12] = initialM41;
  5812. result.m[13] = initialM42;
  5813. result.m[14] = initialM43;
  5814. result.m[15] = initialM44;
  5815. return result;
  5816. };
  5817. /**
  5818. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5819. * @param scale defines the scale vector3
  5820. * @param rotation defines the rotation quaternion
  5821. * @param translation defines the translation vector3
  5822. * @returns a new matrix
  5823. */
  5824. Matrix.Compose = function (scale, rotation, translation) {
  5825. var result = Matrix.Identity();
  5826. Matrix.ComposeToRef(scale, rotation, translation, result);
  5827. return result;
  5828. };
  5829. /**
  5830. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5831. * @param scale defines the scale vector3
  5832. * @param rotation defines the rotation quaternion
  5833. * @param translation defines the translation vector3
  5834. * @param result defines the target matrix
  5835. */
  5836. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5837. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5838. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5839. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5840. result.setTranslation(translation);
  5841. };
  5842. /**
  5843. * Creates a new identity matrix
  5844. * @returns a new identity matrix
  5845. */
  5846. Matrix.Identity = function () {
  5847. 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);
  5848. };
  5849. /**
  5850. * Creates a new identity matrix and stores the result in a given matrix
  5851. * @param result defines the target matrix
  5852. */
  5853. Matrix.IdentityToRef = function (result) {
  5854. 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);
  5855. };
  5856. /**
  5857. * Creates a new zero matrix
  5858. * @returns a new zero matrix
  5859. */
  5860. Matrix.Zero = function () {
  5861. 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);
  5862. };
  5863. /**
  5864. * Creates a new rotation matrix for "angle" radians around the X axis
  5865. * @param angle defines the angle (in radians) to use
  5866. * @return the new matrix
  5867. */
  5868. Matrix.RotationX = function (angle) {
  5869. var result = new Matrix();
  5870. Matrix.RotationXToRef(angle, result);
  5871. return result;
  5872. };
  5873. /**
  5874. * Creates a new matrix as the invert of a given matrix
  5875. * @param source defines the source matrix
  5876. * @returns the new matrix
  5877. */
  5878. Matrix.Invert = function (source) {
  5879. var result = new Matrix();
  5880. source.invertToRef(result);
  5881. return result;
  5882. };
  5883. /**
  5884. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5885. * @param angle defines the angle (in radians) to use
  5886. * @param result defines the target matrix
  5887. */
  5888. Matrix.RotationXToRef = function (angle, result) {
  5889. var s = Math.sin(angle);
  5890. var c = Math.cos(angle);
  5891. result.m[0] = 1.0;
  5892. result.m[15] = 1.0;
  5893. result.m[5] = c;
  5894. result.m[10] = c;
  5895. result.m[9] = -s;
  5896. result.m[6] = s;
  5897. result.m[1] = 0.0;
  5898. result.m[2] = 0.0;
  5899. result.m[3] = 0.0;
  5900. result.m[4] = 0.0;
  5901. result.m[7] = 0.0;
  5902. result.m[8] = 0.0;
  5903. result.m[11] = 0.0;
  5904. result.m[12] = 0.0;
  5905. result.m[13] = 0.0;
  5906. result.m[14] = 0.0;
  5907. result._markAsUpdated();
  5908. };
  5909. /**
  5910. * Creates a new rotation matrix for "angle" radians around the Y axis
  5911. * @param angle defines the angle (in radians) to use
  5912. * @return the new matrix
  5913. */
  5914. Matrix.RotationY = function (angle) {
  5915. var result = new Matrix();
  5916. Matrix.RotationYToRef(angle, result);
  5917. return result;
  5918. };
  5919. /**
  5920. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5921. * @param angle defines the angle (in radians) to use
  5922. * @param result defines the target matrix
  5923. */
  5924. Matrix.RotationYToRef = function (angle, result) {
  5925. var s = Math.sin(angle);
  5926. var c = Math.cos(angle);
  5927. result.m[5] = 1.0;
  5928. result.m[15] = 1.0;
  5929. result.m[0] = c;
  5930. result.m[2] = -s;
  5931. result.m[8] = s;
  5932. result.m[10] = c;
  5933. result.m[1] = 0.0;
  5934. result.m[3] = 0.0;
  5935. result.m[4] = 0.0;
  5936. result.m[6] = 0.0;
  5937. result.m[7] = 0.0;
  5938. result.m[9] = 0.0;
  5939. result.m[11] = 0.0;
  5940. result.m[12] = 0.0;
  5941. result.m[13] = 0.0;
  5942. result.m[14] = 0.0;
  5943. result._markAsUpdated();
  5944. };
  5945. /**
  5946. * Creates a new rotation matrix for "angle" radians around the Z axis
  5947. * @param angle defines the angle (in radians) to use
  5948. * @return the new matrix
  5949. */
  5950. Matrix.RotationZ = function (angle) {
  5951. var result = new Matrix();
  5952. Matrix.RotationZToRef(angle, result);
  5953. return result;
  5954. };
  5955. /**
  5956. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5957. * @param angle defines the angle (in radians) to use
  5958. * @param result defines the target matrix
  5959. */
  5960. Matrix.RotationZToRef = function (angle, result) {
  5961. var s = Math.sin(angle);
  5962. var c = Math.cos(angle);
  5963. result.m[10] = 1.0;
  5964. result.m[15] = 1.0;
  5965. result.m[0] = c;
  5966. result.m[1] = s;
  5967. result.m[4] = -s;
  5968. result.m[5] = c;
  5969. result.m[2] = 0.0;
  5970. result.m[3] = 0.0;
  5971. result.m[6] = 0.0;
  5972. result.m[7] = 0.0;
  5973. result.m[8] = 0.0;
  5974. result.m[9] = 0.0;
  5975. result.m[11] = 0.0;
  5976. result.m[12] = 0.0;
  5977. result.m[13] = 0.0;
  5978. result.m[14] = 0.0;
  5979. result._markAsUpdated();
  5980. };
  5981. /**
  5982. * Creates a new rotation matrix for "angle" radians around the given axis
  5983. * @param axis defines the axis to use
  5984. * @param angle defines the angle (in radians) to use
  5985. * @return the new matrix
  5986. */
  5987. Matrix.RotationAxis = function (axis, angle) {
  5988. var result = Matrix.Zero();
  5989. Matrix.RotationAxisToRef(axis, angle, result);
  5990. return result;
  5991. };
  5992. /**
  5993. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5994. * @param axis defines the axis to use
  5995. * @param angle defines the angle (in radians) to use
  5996. * @param result defines the target matrix
  5997. */
  5998. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5999. var s = Math.sin(-angle);
  6000. var c = Math.cos(-angle);
  6001. var c1 = 1 - c;
  6002. axis.normalize();
  6003. result.m[0] = (axis.x * axis.x) * c1 + c;
  6004. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6005. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6006. result.m[3] = 0.0;
  6007. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6008. result.m[5] = (axis.y * axis.y) * c1 + c;
  6009. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6010. result.m[7] = 0.0;
  6011. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6012. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6013. result.m[10] = (axis.z * axis.z) * c1 + c;
  6014. result.m[11] = 0.0;
  6015. result.m[15] = 1.0;
  6016. result._markAsUpdated();
  6017. };
  6018. /**
  6019. * Creates a rotation matrix
  6020. * @param yaw defines the yaw angle in radians (Y axis)
  6021. * @param pitch defines the pitch angle in radians (X axis)
  6022. * @param roll defines the roll angle in radians (X axis)
  6023. * @returns the new rotation matrix
  6024. */
  6025. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6026. var result = new Matrix();
  6027. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6028. return result;
  6029. };
  6030. /**
  6031. * Creates a rotation matrix and stores it in a given matrix
  6032. * @param yaw defines the yaw angle in radians (Y axis)
  6033. * @param pitch defines the pitch angle in radians (X axis)
  6034. * @param roll defines the roll angle in radians (X axis)
  6035. * @param result defines the target matrix
  6036. */
  6037. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6038. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6039. this._tempQuaternion.toRotationMatrix(result);
  6040. };
  6041. /**
  6042. * Creates a scaling matrix
  6043. * @param x defines the scale factor on X axis
  6044. * @param y defines the scale factor on Y axis
  6045. * @param z defines the scale factor on Z axis
  6046. * @returns the new matrix
  6047. */
  6048. Matrix.Scaling = function (x, y, z) {
  6049. var result = Matrix.Zero();
  6050. Matrix.ScalingToRef(x, y, z, result);
  6051. return result;
  6052. };
  6053. /**
  6054. * Creates a scaling matrix and stores it in a given matrix
  6055. * @param x defines the scale factor on X axis
  6056. * @param y defines the scale factor on Y axis
  6057. * @param z defines the scale factor on Z axis
  6058. * @param result defines the target matrix
  6059. */
  6060. Matrix.ScalingToRef = function (x, y, z, result) {
  6061. result.m[0] = x;
  6062. result.m[1] = 0.0;
  6063. result.m[2] = 0.0;
  6064. result.m[3] = 0.0;
  6065. result.m[4] = 0.0;
  6066. result.m[5] = y;
  6067. result.m[6] = 0.0;
  6068. result.m[7] = 0.0;
  6069. result.m[8] = 0.0;
  6070. result.m[9] = 0.0;
  6071. result.m[10] = z;
  6072. result.m[11] = 0.0;
  6073. result.m[12] = 0.0;
  6074. result.m[13] = 0.0;
  6075. result.m[14] = 0.0;
  6076. result.m[15] = 1.0;
  6077. result._markAsUpdated();
  6078. };
  6079. /**
  6080. * Creates a translation matrix
  6081. * @param x defines the translation on X axis
  6082. * @param y defines the translation on Y axis
  6083. * @param z defines the translationon Z axis
  6084. * @returns the new matrix
  6085. */
  6086. Matrix.Translation = function (x, y, z) {
  6087. var result = Matrix.Identity();
  6088. Matrix.TranslationToRef(x, y, z, result);
  6089. return result;
  6090. };
  6091. /**
  6092. * Creates a translation matrix and stores it in a given matrix
  6093. * @param x defines the translation on X axis
  6094. * @param y defines the translation on Y axis
  6095. * @param z defines the translationon Z axis
  6096. * @param result defines the target matrix
  6097. */
  6098. Matrix.TranslationToRef = function (x, y, z, result) {
  6099. 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);
  6100. };
  6101. /**
  6102. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6103. * @param startValue defines the start value
  6104. * @param endValue defines the end value
  6105. * @param gradient defines the gradient factor
  6106. * @returns the new matrix
  6107. */
  6108. Matrix.Lerp = function (startValue, endValue, gradient) {
  6109. var result = Matrix.Zero();
  6110. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6111. return result;
  6112. };
  6113. /**
  6114. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6115. * @param startValue defines the start value
  6116. * @param endValue defines the end value
  6117. * @param gradient defines the gradient factor
  6118. * @param result defines the Matrix object where to store data
  6119. */
  6120. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6121. for (var index = 0; index < 16; index++) {
  6122. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6123. }
  6124. result._markAsUpdated();
  6125. };
  6126. /**
  6127. * Builds a new matrix whose values are computed by:
  6128. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6129. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6130. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6131. * @param startValue defines the first matrix
  6132. * @param endValue defines the second matrix
  6133. * @param gradient defines the gradient between the two matrices
  6134. * @returns the new matrix
  6135. */
  6136. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6137. var result = Matrix.Zero();
  6138. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6139. return result;
  6140. };
  6141. /**
  6142. * Update a matrix to values which are computed by:
  6143. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6144. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6145. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6146. * @param startValue defines the first matrix
  6147. * @param endValue defines the second matrix
  6148. * @param gradient defines the gradient between the two matrices
  6149. * @param result defines the target matrix
  6150. */
  6151. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6152. var startScale = MathTmp.Vector3[0];
  6153. var startRotation = MathTmp.Quaternion[0];
  6154. var startTranslation = MathTmp.Vector3[1];
  6155. startValue.decompose(startScale, startRotation, startTranslation);
  6156. var endScale = MathTmp.Vector3[2];
  6157. var endRotation = MathTmp.Quaternion[1];
  6158. var endTranslation = MathTmp.Vector3[3];
  6159. endValue.decompose(endScale, endRotation, endTranslation);
  6160. var resultScale = MathTmp.Vector3[4];
  6161. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6162. var resultRotation = MathTmp.Quaternion[2];
  6163. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6164. var resultTranslation = MathTmp.Vector3[5];
  6165. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6166. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6167. };
  6168. /**
  6169. * 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"
  6170. * This function works in left handed mode
  6171. * @param eye defines the final position of the entity
  6172. * @param target defines where the entity should look at
  6173. * @param up defines the up vector for the entity
  6174. * @returns the new matrix
  6175. */
  6176. Matrix.LookAtLH = function (eye, target, up) {
  6177. var result = Matrix.Zero();
  6178. Matrix.LookAtLHToRef(eye, target, up, result);
  6179. return result;
  6180. };
  6181. /**
  6182. * 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".
  6183. * This function works in left handed mode
  6184. * @param eye defines the final position of the entity
  6185. * @param target defines where the entity should look at
  6186. * @param up defines the up vector for the entity
  6187. * @param result defines the target matrix
  6188. */
  6189. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6190. // Z axis
  6191. target.subtractToRef(eye, this._zAxis);
  6192. this._zAxis.normalize();
  6193. // X axis
  6194. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6195. if (this._xAxis.lengthSquared() === 0) {
  6196. this._xAxis.x = 1.0;
  6197. }
  6198. else {
  6199. this._xAxis.normalize();
  6200. }
  6201. // Y axis
  6202. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6203. this._yAxis.normalize();
  6204. // Eye angles
  6205. var ex = -Vector3.Dot(this._xAxis, eye);
  6206. var ey = -Vector3.Dot(this._yAxis, eye);
  6207. var ez = -Vector3.Dot(this._zAxis, eye);
  6208. 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);
  6209. };
  6210. /**
  6211. * 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"
  6212. * This function works in right handed mode
  6213. * @param eye defines the final position of the entity
  6214. * @param target defines where the entity should look at
  6215. * @param up defines the up vector for the entity
  6216. * @returns the new matrix
  6217. */
  6218. Matrix.LookAtRH = function (eye, target, up) {
  6219. var result = Matrix.Zero();
  6220. Matrix.LookAtRHToRef(eye, target, up, result);
  6221. return result;
  6222. };
  6223. /**
  6224. * 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".
  6225. * This function works in right 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. * @param result defines the target matrix
  6230. */
  6231. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6232. // Z axis
  6233. eye.subtractToRef(target, this._zAxis);
  6234. this._zAxis.normalize();
  6235. // X axis
  6236. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6237. if (this._xAxis.lengthSquared() === 0) {
  6238. this._xAxis.x = 1.0;
  6239. }
  6240. else {
  6241. this._xAxis.normalize();
  6242. }
  6243. // Y axis
  6244. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6245. this._yAxis.normalize();
  6246. // Eye angles
  6247. var ex = -Vector3.Dot(this._xAxis, eye);
  6248. var ey = -Vector3.Dot(this._yAxis, eye);
  6249. var ez = -Vector3.Dot(this._zAxis, eye);
  6250. 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);
  6251. };
  6252. /**
  6253. * Create a left-handed orthographic projection matrix
  6254. * @param width defines the viewport width
  6255. * @param height defines the viewport height
  6256. * @param znear defines the near clip plane
  6257. * @param zfar defines the far clip plane
  6258. * @returns a new matrix as a left-handed orthographic projection matrix
  6259. */
  6260. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6261. var matrix = Matrix.Zero();
  6262. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6263. return matrix;
  6264. };
  6265. /**
  6266. * Store a left-handed orthographic projection to a given matrix
  6267. * @param width defines the viewport width
  6268. * @param height defines the viewport height
  6269. * @param znear defines the near clip plane
  6270. * @param zfar defines the far clip plane
  6271. * @param result defines the target matrix
  6272. */
  6273. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6274. var n = znear;
  6275. var f = zfar;
  6276. var a = 2.0 / width;
  6277. var b = 2.0 / height;
  6278. var c = 2.0 / (f - n);
  6279. var d = -(f + n) / (f - n);
  6280. 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);
  6281. };
  6282. /**
  6283. * Create a left-handed orthographic projection matrix
  6284. * @param left defines the viewport left coordinate
  6285. * @param right defines the viewport right coordinate
  6286. * @param bottom defines the viewport bottom coordinate
  6287. * @param top defines the viewport top coordinate
  6288. * @param znear defines the near clip plane
  6289. * @param zfar defines the far clip plane
  6290. * @returns a new matrix as a left-handed orthographic projection matrix
  6291. */
  6292. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6293. var matrix = Matrix.Zero();
  6294. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6295. return matrix;
  6296. };
  6297. /**
  6298. * Stores a left-handed orthographic projection into a given matrix
  6299. * @param left defines the viewport left coordinate
  6300. * @param right defines the viewport right coordinate
  6301. * @param bottom defines the viewport bottom coordinate
  6302. * @param top defines the viewport top coordinate
  6303. * @param znear defines the near clip plane
  6304. * @param zfar defines the far clip plane
  6305. * @param result defines the target matrix
  6306. */
  6307. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6308. var n = znear;
  6309. var f = zfar;
  6310. var a = 2.0 / (right - left);
  6311. var b = 2.0 / (top - bottom);
  6312. var c = 2.0 / (f - n);
  6313. var d = -(f + n) / (f - n);
  6314. var i0 = (left + right) / (left - right);
  6315. var i1 = (top + bottom) / (bottom - top);
  6316. 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);
  6317. };
  6318. /**
  6319. * Creates a right-handed orthographic projection matrix
  6320. * @param left defines the viewport left coordinate
  6321. * @param right defines the viewport right coordinate
  6322. * @param bottom defines the viewport bottom coordinate
  6323. * @param top defines the viewport top coordinate
  6324. * @param znear defines the near clip plane
  6325. * @param zfar defines the far clip plane
  6326. * @returns a new matrix as a right-handed orthographic projection matrix
  6327. */
  6328. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6329. var matrix = Matrix.Zero();
  6330. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6331. return matrix;
  6332. };
  6333. /**
  6334. * Stores a right-handed orthographic projection into a given matrix
  6335. * @param left defines the viewport left coordinate
  6336. * @param right defines the viewport right coordinate
  6337. * @param bottom defines the viewport bottom coordinate
  6338. * @param top defines the viewport top coordinate
  6339. * @param znear defines the near clip plane
  6340. * @param zfar defines the far clip plane
  6341. * @param result defines the target matrix
  6342. */
  6343. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6344. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6345. result.m[10] *= -1.0;
  6346. };
  6347. /**
  6348. * Creates a left-handed perspective projection matrix
  6349. * @param width defines the viewport width
  6350. * @param height defines the viewport height
  6351. * @param znear defines the near clip plane
  6352. * @param zfar defines the far clip plane
  6353. * @returns a new matrix as a left-handed perspective projection matrix
  6354. */
  6355. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6356. var matrix = Matrix.Zero();
  6357. var n = znear;
  6358. var f = zfar;
  6359. var a = 2.0 * n / width;
  6360. var b = 2.0 * n / height;
  6361. var c = (f + n) / (f - n);
  6362. var d = -2.0 * f * n / (f - n);
  6363. 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);
  6364. return matrix;
  6365. };
  6366. /**
  6367. * Creates a left-handed perspective projection matrix
  6368. * @param fov defines the horizontal field of view
  6369. * @param aspect defines the aspect ratio
  6370. * @param znear defines the near clip plane
  6371. * @param zfar defines the far clip plane
  6372. * @returns a new matrix as a left-handed perspective projection matrix
  6373. */
  6374. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6375. var matrix = Matrix.Zero();
  6376. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6377. return matrix;
  6378. };
  6379. /**
  6380. * Stores a left-handed perspective projection into a given matrix
  6381. * @param fov defines the horizontal field of view
  6382. * @param aspect defines the aspect ratio
  6383. * @param znear defines the near clip plane
  6384. * @param zfar defines the far clip plane
  6385. * @param result defines the target matrix
  6386. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6387. */
  6388. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6389. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6390. var n = znear;
  6391. var f = zfar;
  6392. var t = 1.0 / (Math.tan(fov * 0.5));
  6393. var a = isVerticalFovFixed ? (t / aspect) : t;
  6394. var b = isVerticalFovFixed ? t : (t * aspect);
  6395. var c = (f + n) / (f - n);
  6396. var d = -2.0 * f * n / (f - n);
  6397. 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);
  6398. };
  6399. /**
  6400. * Creates a right-handed perspective projection matrix
  6401. * @param fov defines the horizontal field of view
  6402. * @param aspect defines the aspect ratio
  6403. * @param znear defines the near clip plane
  6404. * @param zfar defines the far clip plane
  6405. * @returns a new matrix as a right-handed perspective projection matrix
  6406. */
  6407. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6408. var matrix = Matrix.Zero();
  6409. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6410. return matrix;
  6411. };
  6412. /**
  6413. * Stores a right-handed perspective projection into a given matrix
  6414. * @param fov defines the horizontal field of view
  6415. * @param aspect defines the aspect ratio
  6416. * @param znear defines the near clip plane
  6417. * @param zfar defines the far clip plane
  6418. * @param result defines the target matrix
  6419. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6420. */
  6421. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6422. //alternatively this could be expressed as:
  6423. // m = PerspectiveFovLHToRef
  6424. // m[10] *= -1.0;
  6425. // m[11] *= -1.0;
  6426. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6427. var n = znear;
  6428. var f = zfar;
  6429. var t = 1.0 / (Math.tan(fov * 0.5));
  6430. var a = isVerticalFovFixed ? (t / aspect) : t;
  6431. var b = isVerticalFovFixed ? t : (t * aspect);
  6432. var c = -(f + n) / (f - n);
  6433. var d = -2 * f * n / (f - n);
  6434. 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);
  6435. };
  6436. /**
  6437. * Stores a perspective projection for WebVR info a given matrix
  6438. * @param fov defines the field of view
  6439. * @param znear defines the near clip plane
  6440. * @param zfar defines the far clip plane
  6441. * @param result defines the target matrix
  6442. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6443. */
  6444. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6445. if (rightHanded === void 0) { rightHanded = false; }
  6446. var rightHandedFactor = rightHanded ? -1 : 1;
  6447. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6448. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6449. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6450. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6451. var xScale = 2.0 / (leftTan + rightTan);
  6452. var yScale = 2.0 / (upTan + downTan);
  6453. result.m[0] = xScale;
  6454. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6455. result.m[5] = yScale;
  6456. result.m[6] = result.m[7] = 0.0;
  6457. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6458. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6459. result.m[10] = -zfar / (znear - zfar);
  6460. result.m[11] = 1.0 * rightHandedFactor;
  6461. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6462. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6463. result._markAsUpdated();
  6464. };
  6465. /**
  6466. * Computes a complete transformation matrix
  6467. * @param viewport defines the viewport to use
  6468. * @param world defines the world matrix
  6469. * @param view defines the view matrix
  6470. * @param projection defines the projection matrix
  6471. * @param zmin defines the near clip plane
  6472. * @param zmax defines the far clip plane
  6473. * @returns the transformation matrix
  6474. */
  6475. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6476. var cw = viewport.width;
  6477. var ch = viewport.height;
  6478. var cx = viewport.x;
  6479. var cy = viewport.y;
  6480. 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);
  6481. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6482. };
  6483. /**
  6484. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6485. * @param matrix defines the matrix to use
  6486. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6487. */
  6488. Matrix.GetAsMatrix2x2 = function (matrix) {
  6489. return new Float32Array([
  6490. matrix.m[0], matrix.m[1],
  6491. matrix.m[4], matrix.m[5]
  6492. ]);
  6493. };
  6494. /**
  6495. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6496. * @param matrix defines the matrix to use
  6497. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6498. */
  6499. Matrix.GetAsMatrix3x3 = function (matrix) {
  6500. return new Float32Array([
  6501. matrix.m[0], matrix.m[1], matrix.m[2],
  6502. matrix.m[4], matrix.m[5], matrix.m[6],
  6503. matrix.m[8], matrix.m[9], matrix.m[10]
  6504. ]);
  6505. };
  6506. /**
  6507. * Compute the transpose of a given matrix
  6508. * @param matrix defines the matrix to transpose
  6509. * @returns the new matrix
  6510. */
  6511. Matrix.Transpose = function (matrix) {
  6512. var result = new Matrix();
  6513. Matrix.TransposeToRef(matrix, result);
  6514. return result;
  6515. };
  6516. /**
  6517. * Compute the transpose of a matrix and store it in a target matrix
  6518. * @param matrix defines the matrix to transpose
  6519. * @param result defines the target matrix
  6520. */
  6521. Matrix.TransposeToRef = function (matrix, result) {
  6522. result.m[0] = matrix.m[0];
  6523. result.m[1] = matrix.m[4];
  6524. result.m[2] = matrix.m[8];
  6525. result.m[3] = matrix.m[12];
  6526. result.m[4] = matrix.m[1];
  6527. result.m[5] = matrix.m[5];
  6528. result.m[6] = matrix.m[9];
  6529. result.m[7] = matrix.m[13];
  6530. result.m[8] = matrix.m[2];
  6531. result.m[9] = matrix.m[6];
  6532. result.m[10] = matrix.m[10];
  6533. result.m[11] = matrix.m[14];
  6534. result.m[12] = matrix.m[3];
  6535. result.m[13] = matrix.m[7];
  6536. result.m[14] = matrix.m[11];
  6537. result.m[15] = matrix.m[15];
  6538. };
  6539. /**
  6540. * Computes a reflection matrix from a plane
  6541. * @param plane defines the reflection plane
  6542. * @returns a new matrix
  6543. */
  6544. Matrix.Reflection = function (plane) {
  6545. var matrix = new Matrix();
  6546. Matrix.ReflectionToRef(plane, matrix);
  6547. return matrix;
  6548. };
  6549. /**
  6550. * Computes a reflection matrix from a plane
  6551. * @param plane defines the reflection plane
  6552. * @param result defines the target matrix
  6553. */
  6554. Matrix.ReflectionToRef = function (plane, result) {
  6555. plane.normalize();
  6556. var x = plane.normal.x;
  6557. var y = plane.normal.y;
  6558. var z = plane.normal.z;
  6559. var temp = -2 * x;
  6560. var temp2 = -2 * y;
  6561. var temp3 = -2 * z;
  6562. result.m[0] = (temp * x) + 1;
  6563. result.m[1] = temp2 * x;
  6564. result.m[2] = temp3 * x;
  6565. result.m[3] = 0.0;
  6566. result.m[4] = temp * y;
  6567. result.m[5] = (temp2 * y) + 1;
  6568. result.m[6] = temp3 * y;
  6569. result.m[7] = 0.0;
  6570. result.m[8] = temp * z;
  6571. result.m[9] = temp2 * z;
  6572. result.m[10] = (temp3 * z) + 1;
  6573. result.m[11] = 0.0;
  6574. result.m[12] = temp * plane.d;
  6575. result.m[13] = temp2 * plane.d;
  6576. result.m[14] = temp3 * plane.d;
  6577. result.m[15] = 1.0;
  6578. result._markAsUpdated();
  6579. };
  6580. /**
  6581. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6582. * @param xaxis defines the value of the 1st axis
  6583. * @param yaxis defines the value of the 2nd axis
  6584. * @param zaxis defines the value of the 3rd axis
  6585. * @param result defines the target matrix
  6586. */
  6587. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6588. result.m[0] = xaxis.x;
  6589. result.m[1] = xaxis.y;
  6590. result.m[2] = xaxis.z;
  6591. result.m[3] = 0.0;
  6592. result.m[4] = yaxis.x;
  6593. result.m[5] = yaxis.y;
  6594. result.m[6] = yaxis.z;
  6595. result.m[7] = 0.0;
  6596. result.m[8] = zaxis.x;
  6597. result.m[9] = zaxis.y;
  6598. result.m[10] = zaxis.z;
  6599. result.m[11] = 0.0;
  6600. result.m[12] = 0.0;
  6601. result.m[13] = 0.0;
  6602. result.m[14] = 0.0;
  6603. result.m[15] = 1.0;
  6604. result._markAsUpdated();
  6605. };
  6606. /**
  6607. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6608. * @param quat defines the quaternion to use
  6609. * @param result defines the target matrix
  6610. */
  6611. Matrix.FromQuaternionToRef = function (quat, result) {
  6612. var xx = quat.x * quat.x;
  6613. var yy = quat.y * quat.y;
  6614. var zz = quat.z * quat.z;
  6615. var xy = quat.x * quat.y;
  6616. var zw = quat.z * quat.w;
  6617. var zx = quat.z * quat.x;
  6618. var yw = quat.y * quat.w;
  6619. var yz = quat.y * quat.z;
  6620. var xw = quat.x * quat.w;
  6621. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6622. result.m[1] = 2.0 * (xy + zw);
  6623. result.m[2] = 2.0 * (zx - yw);
  6624. result.m[3] = 0.0;
  6625. result.m[4] = 2.0 * (xy - zw);
  6626. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6627. result.m[6] = 2.0 * (yz + xw);
  6628. result.m[7] = 0.0;
  6629. result.m[8] = 2.0 * (zx + yw);
  6630. result.m[9] = 2.0 * (yz - xw);
  6631. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6632. result.m[11] = 0.0;
  6633. result.m[12] = 0.0;
  6634. result.m[13] = 0.0;
  6635. result.m[14] = 0.0;
  6636. result.m[15] = 1.0;
  6637. result._markAsUpdated();
  6638. };
  6639. Matrix._tempQuaternion = new Quaternion();
  6640. Matrix._xAxis = Vector3.Zero();
  6641. Matrix._yAxis = Vector3.Zero();
  6642. Matrix._zAxis = Vector3.Zero();
  6643. Matrix._updateFlagSeed = 0;
  6644. Matrix._identityReadOnly = Matrix.Identity();
  6645. return Matrix;
  6646. }());
  6647. BABYLON.Matrix = Matrix;
  6648. var Plane = /** @class */ (function () {
  6649. /**
  6650. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6651. */
  6652. function Plane(a, b, c, d) {
  6653. this.normal = new Vector3(a, b, c);
  6654. this.d = d;
  6655. }
  6656. /**
  6657. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6658. */
  6659. Plane.prototype.asArray = function () {
  6660. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6661. };
  6662. // Methods
  6663. /**
  6664. * Returns a new plane copied from the current Plane.
  6665. */
  6666. Plane.prototype.clone = function () {
  6667. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6668. };
  6669. /**
  6670. * Returns the string "Plane".
  6671. */
  6672. Plane.prototype.getClassName = function () {
  6673. return "Plane";
  6674. };
  6675. /**
  6676. * Returns the Plane hash code.
  6677. */
  6678. Plane.prototype.getHashCode = function () {
  6679. var hash = this.normal.getHashCode();
  6680. hash = (hash * 397) ^ (this.d || 0);
  6681. return hash;
  6682. };
  6683. /**
  6684. * Normalize the current Plane in place.
  6685. * Returns the updated Plane.
  6686. */
  6687. Plane.prototype.normalize = function () {
  6688. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6689. var magnitude = 0.0;
  6690. if (norm !== 0) {
  6691. magnitude = 1.0 / norm;
  6692. }
  6693. this.normal.x *= magnitude;
  6694. this.normal.y *= magnitude;
  6695. this.normal.z *= magnitude;
  6696. this.d *= magnitude;
  6697. return this;
  6698. };
  6699. /**
  6700. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6701. */
  6702. Plane.prototype.transform = function (transformation) {
  6703. var transposedMatrix = Matrix.Transpose(transformation);
  6704. var x = this.normal.x;
  6705. var y = this.normal.y;
  6706. var z = this.normal.z;
  6707. var d = this.d;
  6708. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6709. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6710. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6711. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6712. return new Plane(normalX, normalY, normalZ, finalD);
  6713. };
  6714. /**
  6715. * Returns the dot product (float) of the point coordinates and the plane normal.
  6716. */
  6717. Plane.prototype.dotCoordinate = function (point) {
  6718. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6719. };
  6720. /**
  6721. * Updates the current Plane from the plane defined by the three given points.
  6722. * Returns the updated Plane.
  6723. */
  6724. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6725. var x1 = point2.x - point1.x;
  6726. var y1 = point2.y - point1.y;
  6727. var z1 = point2.z - point1.z;
  6728. var x2 = point3.x - point1.x;
  6729. var y2 = point3.y - point1.y;
  6730. var z2 = point3.z - point1.z;
  6731. var yz = (y1 * z2) - (z1 * y2);
  6732. var xz = (z1 * x2) - (x1 * z2);
  6733. var xy = (x1 * y2) - (y1 * x2);
  6734. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6735. var invPyth;
  6736. if (pyth !== 0) {
  6737. invPyth = 1.0 / pyth;
  6738. }
  6739. else {
  6740. invPyth = 0.0;
  6741. }
  6742. this.normal.x = yz * invPyth;
  6743. this.normal.y = xz * invPyth;
  6744. this.normal.z = xy * invPyth;
  6745. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6746. return this;
  6747. };
  6748. /**
  6749. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6750. */
  6751. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6752. var dot = Vector3.Dot(this.normal, direction);
  6753. return (dot <= epsilon);
  6754. };
  6755. /**
  6756. * Returns the signed distance (float) from the given point to the Plane.
  6757. */
  6758. Plane.prototype.signedDistanceTo = function (point) {
  6759. return Vector3.Dot(point, this.normal) + this.d;
  6760. };
  6761. // Statics
  6762. /**
  6763. * Returns a new Plane from the given array.
  6764. */
  6765. Plane.FromArray = function (array) {
  6766. return new Plane(array[0], array[1], array[2], array[3]);
  6767. };
  6768. /**
  6769. * Returns a new Plane defined by the three given points.
  6770. */
  6771. Plane.FromPoints = function (point1, point2, point3) {
  6772. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6773. result.copyFromPoints(point1, point2, point3);
  6774. return result;
  6775. };
  6776. /**
  6777. * Returns a new Plane the normal vector to this plane at the given origin point.
  6778. * Note : the vector "normal" is updated because normalized.
  6779. */
  6780. Plane.FromPositionAndNormal = function (origin, normal) {
  6781. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6782. normal.normalize();
  6783. result.normal = normal;
  6784. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6785. return result;
  6786. };
  6787. /**
  6788. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6789. */
  6790. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6791. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6792. return Vector3.Dot(point, normal) + d;
  6793. };
  6794. return Plane;
  6795. }());
  6796. BABYLON.Plane = Plane;
  6797. var Viewport = /** @class */ (function () {
  6798. /**
  6799. * Creates a Viewport object located at (x, y) and sized (width, height).
  6800. */
  6801. function Viewport(x, y, width, height) {
  6802. this.x = x;
  6803. this.y = y;
  6804. this.width = width;
  6805. this.height = height;
  6806. }
  6807. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6808. if (renderWidthOrEngine.getRenderWidth) {
  6809. var engine = renderWidthOrEngine;
  6810. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6811. }
  6812. var renderWidth = renderWidthOrEngine;
  6813. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6814. };
  6815. /**
  6816. * Returns a new Viewport copied from the current one.
  6817. */
  6818. Viewport.prototype.clone = function () {
  6819. return new Viewport(this.x, this.y, this.width, this.height);
  6820. };
  6821. return Viewport;
  6822. }());
  6823. BABYLON.Viewport = Viewport;
  6824. var Frustum = /** @class */ (function () {
  6825. function Frustum() {
  6826. }
  6827. /**
  6828. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6829. */
  6830. Frustum.GetPlanes = function (transform) {
  6831. var frustumPlanes = [];
  6832. for (var index = 0; index < 6; index++) {
  6833. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6834. }
  6835. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6836. return frustumPlanes;
  6837. };
  6838. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6839. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6840. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6841. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6842. frustumPlane.d = transform.m[15] + transform.m[14];
  6843. frustumPlane.normalize();
  6844. };
  6845. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6846. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6847. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6848. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6849. frustumPlane.d = transform.m[15] - transform.m[14];
  6850. frustumPlane.normalize();
  6851. };
  6852. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6853. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6854. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6855. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6856. frustumPlane.d = transform.m[15] + transform.m[12];
  6857. frustumPlane.normalize();
  6858. };
  6859. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6860. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6861. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6862. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6863. frustumPlane.d = transform.m[15] - transform.m[12];
  6864. frustumPlane.normalize();
  6865. };
  6866. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6867. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6868. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6869. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6870. frustumPlane.d = transform.m[15] - transform.m[13];
  6871. frustumPlane.normalize();
  6872. };
  6873. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6874. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6875. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6876. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6877. frustumPlane.d = transform.m[15] + transform.m[13];
  6878. frustumPlane.normalize();
  6879. };
  6880. /**
  6881. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6882. */
  6883. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6884. // Near
  6885. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6886. // Far
  6887. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6888. // Left
  6889. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6890. // Right
  6891. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6892. // Top
  6893. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6894. // Bottom
  6895. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6896. };
  6897. return Frustum;
  6898. }());
  6899. BABYLON.Frustum = Frustum;
  6900. /** Defines supported spaces */
  6901. var Space;
  6902. (function (Space) {
  6903. /** Local (object) space */
  6904. Space[Space["LOCAL"] = 0] = "LOCAL";
  6905. /** World space */
  6906. Space[Space["WORLD"] = 1] = "WORLD";
  6907. /** Bone space */
  6908. Space[Space["BONE"] = 2] = "BONE";
  6909. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6910. /** Defines the 3 main axes */
  6911. var Axis = /** @class */ (function () {
  6912. function Axis() {
  6913. }
  6914. /** X axis */
  6915. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6916. /** Y axis */
  6917. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6918. /** Z axis */
  6919. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6920. return Axis;
  6921. }());
  6922. BABYLON.Axis = Axis;
  6923. ;
  6924. var BezierCurve = /** @class */ (function () {
  6925. function BezierCurve() {
  6926. }
  6927. /**
  6928. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6929. */
  6930. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6931. // Extract X (which is equal to time here)
  6932. var f0 = 1 - 3 * x2 + 3 * x1;
  6933. var f1 = 3 * x2 - 6 * x1;
  6934. var f2 = 3 * x1;
  6935. var refinedT = t;
  6936. for (var i = 0; i < 5; i++) {
  6937. var refinedT2 = refinedT * refinedT;
  6938. var refinedT3 = refinedT2 * refinedT;
  6939. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6940. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6941. refinedT -= (x - t) * slope;
  6942. refinedT = Math.min(1, Math.max(0, refinedT));
  6943. }
  6944. // Resolve cubic bezier for the given x
  6945. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6946. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6947. Math.pow(refinedT, 3);
  6948. };
  6949. return BezierCurve;
  6950. }());
  6951. BABYLON.BezierCurve = BezierCurve;
  6952. /**
  6953. * Defines potential orientation for back face culling
  6954. */
  6955. var Orientation;
  6956. (function (Orientation) {
  6957. /**
  6958. * Clockwise
  6959. */
  6960. Orientation[Orientation["CW"] = 0] = "CW";
  6961. /** Counter clockwise */
  6962. Orientation[Orientation["CCW"] = 1] = "CCW";
  6963. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6964. /**
  6965. * Defines angle representation
  6966. */
  6967. var Angle = /** @class */ (function () {
  6968. /**
  6969. * Creates an Angle object of "radians" radians (float).
  6970. */
  6971. function Angle(radians) {
  6972. this._radians = radians;
  6973. if (this._radians < 0.0)
  6974. this._radians += (2.0 * Math.PI);
  6975. }
  6976. /**
  6977. * Get value in degrees
  6978. * @returns the Angle value in degrees (float)
  6979. */
  6980. Angle.prototype.degrees = function () {
  6981. return this._radians * 180.0 / Math.PI;
  6982. };
  6983. /**
  6984. * Get value in radians
  6985. * @returns the Angle value in radians (float)
  6986. */
  6987. Angle.prototype.radians = function () {
  6988. return this._radians;
  6989. };
  6990. /**
  6991. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6992. * @param a defines first vector
  6993. * @param b defines second vector
  6994. * @returns a new Angle
  6995. */
  6996. Angle.BetweenTwoPoints = function (a, b) {
  6997. var delta = b.subtract(a);
  6998. var theta = Math.atan2(delta.y, delta.x);
  6999. return new Angle(theta);
  7000. };
  7001. /**
  7002. * Gets a new Angle object from the given float in radians
  7003. * @param radians defines the angle value in radians
  7004. * @returns a new Angle
  7005. */
  7006. Angle.FromRadians = function (radians) {
  7007. return new Angle(radians);
  7008. };
  7009. /**
  7010. * Gets a new Angle object from the given float in degrees
  7011. * @param degrees defines the angle value in degrees
  7012. * @returns a new Angle
  7013. */
  7014. Angle.FromDegrees = function (degrees) {
  7015. return new Angle(degrees * Math.PI / 180.0);
  7016. };
  7017. return Angle;
  7018. }());
  7019. BABYLON.Angle = Angle;
  7020. var Arc2 = /** @class */ (function () {
  7021. /**
  7022. * Creates an Arc object from the three given points : start, middle and end.
  7023. */
  7024. function Arc2(startPoint, midPoint, endPoint) {
  7025. this.startPoint = startPoint;
  7026. this.midPoint = midPoint;
  7027. this.endPoint = endPoint;
  7028. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7029. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7030. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7031. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7032. 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);
  7033. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7034. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7035. var a1 = this.startAngle.degrees();
  7036. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7037. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7038. // angles correction
  7039. if (a2 - a1 > +180.0)
  7040. a2 -= 360.0;
  7041. if (a2 - a1 < -180.0)
  7042. a2 += 360.0;
  7043. if (a3 - a2 > +180.0)
  7044. a3 -= 360.0;
  7045. if (a3 - a2 < -180.0)
  7046. a3 += 360.0;
  7047. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7048. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7049. }
  7050. return Arc2;
  7051. }());
  7052. BABYLON.Arc2 = Arc2;
  7053. var Path2 = /** @class */ (function () {
  7054. /**
  7055. * Creates a Path2 object from the starting 2D coordinates x and y.
  7056. */
  7057. function Path2(x, y) {
  7058. this._points = new Array();
  7059. this._length = 0.0;
  7060. this.closed = false;
  7061. this._points.push(new Vector2(x, y));
  7062. }
  7063. /**
  7064. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7065. * Returns the updated Path2.
  7066. */
  7067. Path2.prototype.addLineTo = function (x, y) {
  7068. if (this.closed) {
  7069. return this;
  7070. }
  7071. var newPoint = new Vector2(x, y);
  7072. var previousPoint = this._points[this._points.length - 1];
  7073. this._points.push(newPoint);
  7074. this._length += newPoint.subtract(previousPoint).length();
  7075. return this;
  7076. };
  7077. /**
  7078. * 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.
  7079. * Returns the updated Path2.
  7080. */
  7081. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7082. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7083. if (this.closed) {
  7084. return this;
  7085. }
  7086. var startPoint = this._points[this._points.length - 1];
  7087. var midPoint = new Vector2(midX, midY);
  7088. var endPoint = new Vector2(endX, endY);
  7089. var arc = new Arc2(startPoint, midPoint, endPoint);
  7090. var increment = arc.angle.radians() / numberOfSegments;
  7091. if (arc.orientation === Orientation.CW)
  7092. increment *= -1;
  7093. var currentAngle = arc.startAngle.radians() + increment;
  7094. for (var i = 0; i < numberOfSegments; i++) {
  7095. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7096. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7097. this.addLineTo(x, y);
  7098. currentAngle += increment;
  7099. }
  7100. return this;
  7101. };
  7102. /**
  7103. * Closes the Path2.
  7104. * Returns the Path2.
  7105. */
  7106. Path2.prototype.close = function () {
  7107. this.closed = true;
  7108. return this;
  7109. };
  7110. /**
  7111. * Returns the Path2 total length (float).
  7112. */
  7113. Path2.prototype.length = function () {
  7114. var result = this._length;
  7115. if (!this.closed) {
  7116. var lastPoint = this._points[this._points.length - 1];
  7117. var firstPoint = this._points[0];
  7118. result += (firstPoint.subtract(lastPoint).length());
  7119. }
  7120. return result;
  7121. };
  7122. /**
  7123. * Returns the Path2 internal array of points.
  7124. */
  7125. Path2.prototype.getPoints = function () {
  7126. return this._points;
  7127. };
  7128. /**
  7129. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7130. */
  7131. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7132. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7133. return Vector2.Zero();
  7134. }
  7135. var lengthPosition = normalizedLengthPosition * this.length();
  7136. var previousOffset = 0;
  7137. for (var i = 0; i < this._points.length; i++) {
  7138. var j = (i + 1) % this._points.length;
  7139. var a = this._points[i];
  7140. var b = this._points[j];
  7141. var bToA = b.subtract(a);
  7142. var nextOffset = (bToA.length() + previousOffset);
  7143. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7144. var dir = bToA.normalize();
  7145. var localOffset = lengthPosition - previousOffset;
  7146. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7147. }
  7148. previousOffset = nextOffset;
  7149. }
  7150. return Vector2.Zero();
  7151. };
  7152. /**
  7153. * Returns a new Path2 starting at the coordinates (x, y).
  7154. */
  7155. Path2.StartingAt = function (x, y) {
  7156. return new Path2(x, y);
  7157. };
  7158. return Path2;
  7159. }());
  7160. BABYLON.Path2 = Path2;
  7161. var Path3D = /** @class */ (function () {
  7162. /**
  7163. * new Path3D(path, normal, raw)
  7164. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7165. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7166. * path : an array of Vector3, the curve axis of the Path3D
  7167. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7168. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7169. */
  7170. function Path3D(path, firstNormal, raw) {
  7171. if (firstNormal === void 0) { firstNormal = null; }
  7172. this.path = path;
  7173. this._curve = new Array();
  7174. this._distances = new Array();
  7175. this._tangents = new Array();
  7176. this._normals = new Array();
  7177. this._binormals = new Array();
  7178. for (var p = 0; p < path.length; p++) {
  7179. this._curve[p] = path[p].clone(); // hard copy
  7180. }
  7181. this._raw = raw || false;
  7182. this._compute(firstNormal);
  7183. }
  7184. /**
  7185. * Returns the Path3D array of successive Vector3 designing its curve.
  7186. */
  7187. Path3D.prototype.getCurve = function () {
  7188. return this._curve;
  7189. };
  7190. /**
  7191. * Returns an array populated with tangent vectors on each Path3D curve point.
  7192. */
  7193. Path3D.prototype.getTangents = function () {
  7194. return this._tangents;
  7195. };
  7196. /**
  7197. * Returns an array populated with normal vectors on each Path3D curve point.
  7198. */
  7199. Path3D.prototype.getNormals = function () {
  7200. return this._normals;
  7201. };
  7202. /**
  7203. * Returns an array populated with binormal vectors on each Path3D curve point.
  7204. */
  7205. Path3D.prototype.getBinormals = function () {
  7206. return this._binormals;
  7207. };
  7208. /**
  7209. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7210. */
  7211. Path3D.prototype.getDistances = function () {
  7212. return this._distances;
  7213. };
  7214. /**
  7215. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7216. * Returns the same object updated.
  7217. */
  7218. Path3D.prototype.update = function (path, firstNormal) {
  7219. if (firstNormal === void 0) { firstNormal = null; }
  7220. for (var p = 0; p < path.length; p++) {
  7221. this._curve[p].x = path[p].x;
  7222. this._curve[p].y = path[p].y;
  7223. this._curve[p].z = path[p].z;
  7224. }
  7225. this._compute(firstNormal);
  7226. return this;
  7227. };
  7228. // private function compute() : computes tangents, normals and binormals
  7229. Path3D.prototype._compute = function (firstNormal) {
  7230. var l = this._curve.length;
  7231. // first and last tangents
  7232. this._tangents[0] = this._getFirstNonNullVector(0);
  7233. if (!this._raw) {
  7234. this._tangents[0].normalize();
  7235. }
  7236. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7237. if (!this._raw) {
  7238. this._tangents[l - 1].normalize();
  7239. }
  7240. // normals and binormals at first point : arbitrary vector with _normalVector()
  7241. var tg0 = this._tangents[0];
  7242. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7243. this._normals[0] = pp0;
  7244. if (!this._raw) {
  7245. this._normals[0].normalize();
  7246. }
  7247. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7248. if (!this._raw) {
  7249. this._binormals[0].normalize();
  7250. }
  7251. this._distances[0] = 0.0;
  7252. // normals and binormals : next points
  7253. var prev; // previous vector (segment)
  7254. var cur; // current vector (segment)
  7255. var curTang; // current tangent
  7256. // previous normal
  7257. var prevBinor; // previous binormal
  7258. for (var i = 1; i < l; i++) {
  7259. // tangents
  7260. prev = this._getLastNonNullVector(i);
  7261. if (i < l - 1) {
  7262. cur = this._getFirstNonNullVector(i);
  7263. this._tangents[i] = prev.add(cur);
  7264. this._tangents[i].normalize();
  7265. }
  7266. this._distances[i] = this._distances[i - 1] + prev.length();
  7267. // normals and binormals
  7268. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7269. curTang = this._tangents[i];
  7270. prevBinor = this._binormals[i - 1];
  7271. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7272. if (!this._raw) {
  7273. this._normals[i].normalize();
  7274. }
  7275. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7276. if (!this._raw) {
  7277. this._binormals[i].normalize();
  7278. }
  7279. }
  7280. };
  7281. // private function getFirstNonNullVector(index)
  7282. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7283. Path3D.prototype._getFirstNonNullVector = function (index) {
  7284. var i = 1;
  7285. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7286. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7287. i++;
  7288. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7289. }
  7290. return nNVector;
  7291. };
  7292. // private function getLastNonNullVector(index)
  7293. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7294. Path3D.prototype._getLastNonNullVector = function (index) {
  7295. var i = 1;
  7296. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7297. while (nLVector.length() === 0 && index > i + 1) {
  7298. i++;
  7299. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7300. }
  7301. return nLVector;
  7302. };
  7303. // private function normalVector(v0, vt, va) :
  7304. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7305. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7306. Path3D.prototype._normalVector = function (v0, vt, va) {
  7307. var normal0;
  7308. var tgl = vt.length();
  7309. if (tgl === 0.0) {
  7310. tgl = 1.0;
  7311. }
  7312. if (va === undefined || va === null) {
  7313. var point;
  7314. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7315. point = new Vector3(0.0, -1.0, 0.0);
  7316. }
  7317. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7318. point = new Vector3(1.0, 0.0, 0.0);
  7319. }
  7320. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7321. point = new Vector3(0.0, 0.0, 1.0);
  7322. }
  7323. else {
  7324. point = Vector3.Zero();
  7325. }
  7326. normal0 = Vector3.Cross(vt, point);
  7327. }
  7328. else {
  7329. normal0 = Vector3.Cross(vt, va);
  7330. Vector3.CrossToRef(normal0, vt, normal0);
  7331. }
  7332. normal0.normalize();
  7333. return normal0;
  7334. };
  7335. return Path3D;
  7336. }());
  7337. BABYLON.Path3D = Path3D;
  7338. var Curve3 = /** @class */ (function () {
  7339. /**
  7340. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7341. * A Curve3 is designed from a series of successive Vector3.
  7342. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7343. */
  7344. function Curve3(points) {
  7345. this._length = 0.0;
  7346. this._points = points;
  7347. this._length = this._computeLength(points);
  7348. }
  7349. /**
  7350. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7351. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7352. * @param v1 (Vector3) the control point
  7353. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7354. * @param nbPoints (integer) the wanted number of points in the curve
  7355. */
  7356. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7357. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7358. var bez = new Array();
  7359. var equation = function (t, val0, val1, val2) {
  7360. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7361. return res;
  7362. };
  7363. for (var i = 0; i <= nbPoints; i++) {
  7364. 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)));
  7365. }
  7366. return new Curve3(bez);
  7367. };
  7368. /**
  7369. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7370. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7371. * @param v1 (Vector3) the first control point
  7372. * @param v2 (Vector3) the second control point
  7373. * @param v3 (Vector3) the end point of the Cubic Bezier
  7374. * @param nbPoints (integer) the wanted number of points in the curve
  7375. */
  7376. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7377. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7378. var bez = new Array();
  7379. var equation = function (t, val0, val1, val2, val3) {
  7380. 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;
  7381. return res;
  7382. };
  7383. for (var i = 0; i <= nbPoints; i++) {
  7384. 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)));
  7385. }
  7386. return new Curve3(bez);
  7387. };
  7388. /**
  7389. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7390. * @param p1 (Vector3) the origin point of the Hermite Spline
  7391. * @param t1 (Vector3) the tangent vector at the origin point
  7392. * @param p2 (Vector3) the end point of the Hermite Spline
  7393. * @param t2 (Vector3) the tangent vector at the end point
  7394. * @param nbPoints (integer) the wanted number of points in the curve
  7395. */
  7396. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7397. var hermite = new Array();
  7398. var step = 1.0 / nbPoints;
  7399. for (var i = 0; i <= nbPoints; i++) {
  7400. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7401. }
  7402. return new Curve3(hermite);
  7403. };
  7404. /**
  7405. * Returns a Curve3 object along a CatmullRom Spline curve :
  7406. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7407. * @param nbPoints (integer) the wanted number of points between each curve control points
  7408. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7409. */
  7410. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7411. var catmullRom = new Array();
  7412. var step = 1.0 / nbPoints;
  7413. var amount = 0.0;
  7414. if (closed) {
  7415. var pointsCount = points.length;
  7416. for (var i = 0; i < pointsCount; i++) {
  7417. amount = 0;
  7418. for (var c = 0; c < nbPoints; c++) {
  7419. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7420. amount += step;
  7421. }
  7422. }
  7423. catmullRom.push(catmullRom[0]);
  7424. }
  7425. else {
  7426. var totalPoints = new Array();
  7427. totalPoints.push(points[0].clone());
  7428. Array.prototype.push.apply(totalPoints, points);
  7429. totalPoints.push(points[points.length - 1].clone());
  7430. for (var i = 0; i < totalPoints.length - 3; i++) {
  7431. amount = 0;
  7432. for (var c = 0; c < nbPoints; c++) {
  7433. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7434. amount += step;
  7435. }
  7436. }
  7437. i--;
  7438. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7439. }
  7440. return new Curve3(catmullRom);
  7441. };
  7442. /**
  7443. * Returns the Curve3 stored array of successive Vector3
  7444. */
  7445. Curve3.prototype.getPoints = function () {
  7446. return this._points;
  7447. };
  7448. /**
  7449. * Returns the computed length (float) of the curve.
  7450. */
  7451. Curve3.prototype.length = function () {
  7452. return this._length;
  7453. };
  7454. /**
  7455. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7456. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7457. * curveA and curveB keep unchanged.
  7458. */
  7459. Curve3.prototype.continue = function (curve) {
  7460. var lastPoint = this._points[this._points.length - 1];
  7461. var continuedPoints = this._points.slice();
  7462. var curvePoints = curve.getPoints();
  7463. for (var i = 1; i < curvePoints.length; i++) {
  7464. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7465. }
  7466. var continuedCurve = new Curve3(continuedPoints);
  7467. return continuedCurve;
  7468. };
  7469. Curve3.prototype._computeLength = function (path) {
  7470. var l = 0;
  7471. for (var i = 1; i < path.length; i++) {
  7472. l += (path[i].subtract(path[i - 1])).length();
  7473. }
  7474. return l;
  7475. };
  7476. return Curve3;
  7477. }());
  7478. BABYLON.Curve3 = Curve3;
  7479. // Vertex formats
  7480. var PositionNormalVertex = /** @class */ (function () {
  7481. function PositionNormalVertex(position, normal) {
  7482. if (position === void 0) { position = Vector3.Zero(); }
  7483. if (normal === void 0) { normal = Vector3.Up(); }
  7484. this.position = position;
  7485. this.normal = normal;
  7486. }
  7487. PositionNormalVertex.prototype.clone = function () {
  7488. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7489. };
  7490. return PositionNormalVertex;
  7491. }());
  7492. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7493. var PositionNormalTextureVertex = /** @class */ (function () {
  7494. function PositionNormalTextureVertex(position, normal, uv) {
  7495. if (position === void 0) { position = Vector3.Zero(); }
  7496. if (normal === void 0) { normal = Vector3.Up(); }
  7497. if (uv === void 0) { uv = Vector2.Zero(); }
  7498. this.position = position;
  7499. this.normal = normal;
  7500. this.uv = uv;
  7501. }
  7502. PositionNormalTextureVertex.prototype.clone = function () {
  7503. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7504. };
  7505. return PositionNormalTextureVertex;
  7506. }());
  7507. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7508. // Temporary pre-allocated objects for engine internal use
  7509. // usage in any internal function :
  7510. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7511. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7512. var Tmp = /** @class */ (function () {
  7513. function Tmp() {
  7514. }
  7515. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7516. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7517. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7518. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7519. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7520. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7521. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7522. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7523. Matrix.Zero(), Matrix.Zero(),
  7524. Matrix.Zero(), Matrix.Zero(),
  7525. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7526. return Tmp;
  7527. }());
  7528. BABYLON.Tmp = Tmp;
  7529. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7530. var MathTmp = /** @class */ (function () {
  7531. function MathTmp() {
  7532. }
  7533. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7534. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7535. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7536. return MathTmp;
  7537. }());
  7538. })(BABYLON || (BABYLON = {}));
  7539. //# sourceMappingURL=babylon.math.js.map
  7540. var BABYLON;
  7541. (function (BABYLON) {
  7542. var Scalar = /** @class */ (function () {
  7543. function Scalar() {
  7544. }
  7545. /**
  7546. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7547. */
  7548. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7549. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7550. var num = a - b;
  7551. return -epsilon <= num && num <= epsilon;
  7552. };
  7553. /**
  7554. * Returns a string : the upper case translation of the number i to hexadecimal.
  7555. */
  7556. Scalar.ToHex = function (i) {
  7557. var str = i.toString(16);
  7558. if (i <= 15) {
  7559. return ("0" + str).toUpperCase();
  7560. }
  7561. return str.toUpperCase();
  7562. };
  7563. /**
  7564. * Returns -1 if value is negative and +1 is value is positive.
  7565. * Returns the value itself if it's equal to zero.
  7566. */
  7567. Scalar.Sign = function (value) {
  7568. value = +value; // convert to a number
  7569. if (value === 0 || isNaN(value))
  7570. return value;
  7571. return value > 0 ? 1 : -1;
  7572. };
  7573. /**
  7574. * Returns the value itself if it's between min and max.
  7575. * Returns min if the value is lower than min.
  7576. * Returns max if the value is greater than max.
  7577. */
  7578. Scalar.Clamp = function (value, min, max) {
  7579. if (min === void 0) { min = 0; }
  7580. if (max === void 0) { max = 1; }
  7581. return Math.min(max, Math.max(min, value));
  7582. };
  7583. /**
  7584. * Returns the log2 of value.
  7585. */
  7586. Scalar.Log2 = function (value) {
  7587. return Math.log(value) * Math.LOG2E;
  7588. };
  7589. /**
  7590. * Loops the value, so that it is never larger than length and never smaller than 0.
  7591. *
  7592. * This is similar to the modulo operator but it works with floating point numbers.
  7593. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7594. * With t = 5 and length = 2.5, the result would be 0.0.
  7595. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7596. */
  7597. Scalar.Repeat = function (value, length) {
  7598. return value - Math.floor(value / length) * length;
  7599. };
  7600. /**
  7601. * Normalize the value between 0.0 and 1.0 using min and max values
  7602. */
  7603. Scalar.Normalize = function (value, min, max) {
  7604. return (value - min) / (max - min);
  7605. };
  7606. /**
  7607. * Denormalize the value from 0.0 and 1.0 using min and max values
  7608. */
  7609. Scalar.Denormalize = function (normalized, min, max) {
  7610. return (normalized * (max - min) + min);
  7611. };
  7612. /**
  7613. * Calculates the shortest difference between two given angles given in degrees.
  7614. */
  7615. Scalar.DeltaAngle = function (current, target) {
  7616. var num = Scalar.Repeat(target - current, 360.0);
  7617. if (num > 180.0) {
  7618. num -= 360.0;
  7619. }
  7620. return num;
  7621. };
  7622. /**
  7623. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7624. *
  7625. * The returned value will move back and forth between 0 and length
  7626. */
  7627. Scalar.PingPong = function (tx, length) {
  7628. var t = Scalar.Repeat(tx, length * 2.0);
  7629. return length - Math.abs(t - length);
  7630. };
  7631. /**
  7632. * Interpolates between min and max with smoothing at the limits.
  7633. *
  7634. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7635. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7636. */
  7637. Scalar.SmoothStep = function (from, to, tx) {
  7638. var t = Scalar.Clamp(tx);
  7639. t = -2.0 * t * t * t + 3.0 * t * t;
  7640. return to * t + from * (1.0 - t);
  7641. };
  7642. /**
  7643. * Moves a value current towards target.
  7644. *
  7645. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7646. * Negative values of maxDelta pushes the value away from target.
  7647. */
  7648. Scalar.MoveTowards = function (current, target, maxDelta) {
  7649. var result = 0;
  7650. if (Math.abs(target - current) <= maxDelta) {
  7651. result = target;
  7652. }
  7653. else {
  7654. result = current + Scalar.Sign(target - current) * maxDelta;
  7655. }
  7656. return result;
  7657. };
  7658. /**
  7659. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7660. *
  7661. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7662. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7663. */
  7664. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7665. var num = Scalar.DeltaAngle(current, target);
  7666. var result = 0;
  7667. if (-maxDelta < num && num < maxDelta) {
  7668. result = target;
  7669. }
  7670. else {
  7671. target = current + num;
  7672. result = Scalar.MoveTowards(current, target, maxDelta);
  7673. }
  7674. return result;
  7675. };
  7676. /**
  7677. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7678. */
  7679. Scalar.Lerp = function (start, end, amount) {
  7680. return start + ((end - start) * amount);
  7681. };
  7682. /**
  7683. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7684. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7685. */
  7686. Scalar.LerpAngle = function (start, end, amount) {
  7687. var num = Scalar.Repeat(end - start, 360.0);
  7688. if (num > 180.0) {
  7689. num -= 360.0;
  7690. }
  7691. return start + num * Scalar.Clamp(amount);
  7692. };
  7693. /**
  7694. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7695. */
  7696. Scalar.InverseLerp = function (a, b, value) {
  7697. var result = 0;
  7698. if (a != b) {
  7699. result = Scalar.Clamp((value - a) / (b - a));
  7700. }
  7701. else {
  7702. result = 0.0;
  7703. }
  7704. return result;
  7705. };
  7706. /**
  7707. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7708. */
  7709. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7710. var squared = amount * amount;
  7711. var cubed = amount * squared;
  7712. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7713. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7714. var part3 = (cubed - (2.0 * squared)) + amount;
  7715. var part4 = cubed - squared;
  7716. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7717. };
  7718. /**
  7719. * Returns a random float number between and min and max values
  7720. */
  7721. Scalar.RandomRange = function (min, max) {
  7722. if (min === max)
  7723. return min;
  7724. return ((Math.random() * (max - min)) + min);
  7725. };
  7726. /**
  7727. * This function returns percentage of a number in a given range.
  7728. *
  7729. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7730. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7731. */
  7732. Scalar.RangeToPercent = function (number, min, max) {
  7733. return ((number - min) / (max - min));
  7734. };
  7735. /**
  7736. * This function returns number that corresponds to the percentage in a given range.
  7737. *
  7738. * PercentToRange(0.34,0,100) will return 34.
  7739. */
  7740. Scalar.PercentToRange = function (percent, min, max) {
  7741. return ((max - min) * percent + min);
  7742. };
  7743. /**
  7744. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7745. * @param angle The angle to normalize in radian.
  7746. * @return The converted angle.
  7747. */
  7748. Scalar.NormalizeRadians = function (angle) {
  7749. // More precise but slower version kept for reference.
  7750. // angle = angle % Tools.TwoPi;
  7751. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7752. //if (angle > Math.PI) {
  7753. // angle -= Tools.TwoPi;
  7754. //}
  7755. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7756. return angle;
  7757. };
  7758. /**
  7759. * Two pi constants convenient for computation.
  7760. */
  7761. Scalar.TwoPi = Math.PI * 2;
  7762. return Scalar;
  7763. }());
  7764. BABYLON.Scalar = Scalar;
  7765. })(BABYLON || (BABYLON = {}));
  7766. //# sourceMappingURL=babylon.math.scalar.js.map
  7767. //# sourceMappingURL=babylon.mixins.js.map
  7768. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7769. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7770. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7771. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7772. //# sourceMappingURL=babylon.webgl2.js.map
  7773. var BABYLON;
  7774. (function (BABYLON) {
  7775. var __decoratorInitialStore = {};
  7776. var __mergedStore = {};
  7777. var _copySource = function (creationFunction, source, instanciate) {
  7778. var destination = creationFunction();
  7779. // Tags
  7780. if (BABYLON.Tags) {
  7781. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7782. }
  7783. var classStore = getMergedStore(destination);
  7784. // Properties
  7785. for (var property in classStore) {
  7786. var propertyDescriptor = classStore[property];
  7787. var sourceProperty = source[property];
  7788. var propertyType = propertyDescriptor.type;
  7789. if (sourceProperty !== undefined && sourceProperty !== null) {
  7790. switch (propertyType) {
  7791. case 0: // Value
  7792. case 6: // Mesh reference
  7793. case 11: // Camera reference
  7794. destination[property] = sourceProperty;
  7795. break;
  7796. case 1: // Texture
  7797. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7798. break;
  7799. case 2: // Color3
  7800. case 3: // FresnelParameters
  7801. case 4: // Vector2
  7802. case 5: // Vector3
  7803. case 7: // Color Curves
  7804. case 10: // Quaternion
  7805. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7806. break;
  7807. }
  7808. }
  7809. }
  7810. return destination;
  7811. };
  7812. function getDirectStore(target) {
  7813. var classKey = target.getClassName();
  7814. if (!__decoratorInitialStore[classKey]) {
  7815. __decoratorInitialStore[classKey] = {};
  7816. }
  7817. return __decoratorInitialStore[classKey];
  7818. }
  7819. /**
  7820. * Return the list of properties flagged as serializable
  7821. * @param target: host object
  7822. */
  7823. function getMergedStore(target) {
  7824. var classKey = target.getClassName();
  7825. if (__mergedStore[classKey]) {
  7826. return __mergedStore[classKey];
  7827. }
  7828. __mergedStore[classKey] = {};
  7829. var store = __mergedStore[classKey];
  7830. var currentTarget = target;
  7831. var currentKey = classKey;
  7832. while (currentKey) {
  7833. var initialStore = __decoratorInitialStore[currentKey];
  7834. for (var property in initialStore) {
  7835. store[property] = initialStore[property];
  7836. }
  7837. var parent_1 = void 0;
  7838. var done = false;
  7839. do {
  7840. parent_1 = Object.getPrototypeOf(currentTarget);
  7841. if (!parent_1.getClassName) {
  7842. done = true;
  7843. break;
  7844. }
  7845. if (parent_1.getClassName() !== currentKey) {
  7846. break;
  7847. }
  7848. currentTarget = parent_1;
  7849. } while (parent_1);
  7850. if (done) {
  7851. break;
  7852. }
  7853. currentKey = parent_1.getClassName();
  7854. currentTarget = parent_1;
  7855. }
  7856. return store;
  7857. }
  7858. function generateSerializableMember(type, sourceName) {
  7859. return function (target, propertyKey) {
  7860. var classStore = getDirectStore(target);
  7861. if (!classStore[propertyKey]) {
  7862. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7863. }
  7864. };
  7865. }
  7866. function generateExpandMember(setCallback, targetKey) {
  7867. if (targetKey === void 0) { targetKey = null; }
  7868. return function (target, propertyKey) {
  7869. var key = targetKey || ("_" + propertyKey);
  7870. Object.defineProperty(target, propertyKey, {
  7871. get: function () {
  7872. return this[key];
  7873. },
  7874. set: function (value) {
  7875. if (this[key] === value) {
  7876. return;
  7877. }
  7878. this[key] = value;
  7879. target[setCallback].apply(this);
  7880. },
  7881. enumerable: true,
  7882. configurable: true
  7883. });
  7884. };
  7885. }
  7886. function expandToProperty(callback, targetKey) {
  7887. if (targetKey === void 0) { targetKey = null; }
  7888. return generateExpandMember(callback, targetKey);
  7889. }
  7890. BABYLON.expandToProperty = expandToProperty;
  7891. function serialize(sourceName) {
  7892. return generateSerializableMember(0, sourceName); // value member
  7893. }
  7894. BABYLON.serialize = serialize;
  7895. function serializeAsTexture(sourceName) {
  7896. return generateSerializableMember(1, sourceName); // texture member
  7897. }
  7898. BABYLON.serializeAsTexture = serializeAsTexture;
  7899. function serializeAsColor3(sourceName) {
  7900. return generateSerializableMember(2, sourceName); // color3 member
  7901. }
  7902. BABYLON.serializeAsColor3 = serializeAsColor3;
  7903. function serializeAsFresnelParameters(sourceName) {
  7904. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7905. }
  7906. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7907. function serializeAsVector2(sourceName) {
  7908. return generateSerializableMember(4, sourceName); // vector2 member
  7909. }
  7910. BABYLON.serializeAsVector2 = serializeAsVector2;
  7911. function serializeAsVector3(sourceName) {
  7912. return generateSerializableMember(5, sourceName); // vector3 member
  7913. }
  7914. BABYLON.serializeAsVector3 = serializeAsVector3;
  7915. function serializeAsMeshReference(sourceName) {
  7916. return generateSerializableMember(6, sourceName); // mesh reference member
  7917. }
  7918. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7919. function serializeAsColorCurves(sourceName) {
  7920. return generateSerializableMember(7, sourceName); // color curves
  7921. }
  7922. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7923. function serializeAsColor4(sourceName) {
  7924. return generateSerializableMember(8, sourceName); // color 4
  7925. }
  7926. BABYLON.serializeAsColor4 = serializeAsColor4;
  7927. function serializeAsImageProcessingConfiguration(sourceName) {
  7928. return generateSerializableMember(9, sourceName); // image processing
  7929. }
  7930. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7931. function serializeAsQuaternion(sourceName) {
  7932. return generateSerializableMember(10, sourceName); // quaternion member
  7933. }
  7934. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7935. /**
  7936. * Decorator used to define property that can be serialized as reference to a camera
  7937. * @param sourceName defines the name of the property to decorate
  7938. */
  7939. function serializeAsCameraReference(sourceName) {
  7940. return generateSerializableMember(11, sourceName); // camera reference member
  7941. }
  7942. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7943. var SerializationHelper = /** @class */ (function () {
  7944. function SerializationHelper() {
  7945. }
  7946. SerializationHelper.Serialize = function (entity, serializationObject) {
  7947. if (!serializationObject) {
  7948. serializationObject = {};
  7949. }
  7950. // Tags
  7951. if (BABYLON.Tags) {
  7952. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7953. }
  7954. var serializedProperties = getMergedStore(entity);
  7955. // Properties
  7956. for (var property in serializedProperties) {
  7957. var propertyDescriptor = serializedProperties[property];
  7958. var targetPropertyName = propertyDescriptor.sourceName || property;
  7959. var propertyType = propertyDescriptor.type;
  7960. var sourceProperty = entity[property];
  7961. if (sourceProperty !== undefined && sourceProperty !== null) {
  7962. switch (propertyType) {
  7963. case 0: // Value
  7964. serializationObject[targetPropertyName] = sourceProperty;
  7965. break;
  7966. case 1: // Texture
  7967. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7968. break;
  7969. case 2: // Color3
  7970. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7971. break;
  7972. case 3: // FresnelParameters
  7973. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7974. break;
  7975. case 4: // Vector2
  7976. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7977. break;
  7978. case 5: // Vector3
  7979. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7980. break;
  7981. case 6: // Mesh reference
  7982. serializationObject[targetPropertyName] = sourceProperty.id;
  7983. break;
  7984. case 7: // Color Curves
  7985. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7986. break;
  7987. case 8: // Color 4
  7988. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7989. break;
  7990. case 9: // Image Processing
  7991. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7992. break;
  7993. case 10: // Quaternion
  7994. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7995. break;
  7996. case 11: // Camera reference
  7997. serializationObject[targetPropertyName] = sourceProperty.id;
  7998. break;
  7999. }
  8000. }
  8001. }
  8002. return serializationObject;
  8003. };
  8004. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8005. if (rootUrl === void 0) { rootUrl = null; }
  8006. var destination = creationFunction();
  8007. if (!rootUrl) {
  8008. rootUrl = "";
  8009. }
  8010. // Tags
  8011. if (BABYLON.Tags) {
  8012. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8013. }
  8014. var classStore = getMergedStore(destination);
  8015. // Properties
  8016. for (var property in classStore) {
  8017. var propertyDescriptor = classStore[property];
  8018. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8019. var propertyType = propertyDescriptor.type;
  8020. if (sourceProperty !== undefined && sourceProperty !== null) {
  8021. var dest = destination;
  8022. switch (propertyType) {
  8023. case 0: // Value
  8024. dest[property] = sourceProperty;
  8025. break;
  8026. case 1: // Texture
  8027. if (scene) {
  8028. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8029. }
  8030. break;
  8031. case 2: // Color3
  8032. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8033. break;
  8034. case 3: // FresnelParameters
  8035. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8036. break;
  8037. case 4: // Vector2
  8038. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8039. break;
  8040. case 5: // Vector3
  8041. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8042. break;
  8043. case 6: // Mesh reference
  8044. if (scene) {
  8045. dest[property] = scene.getLastMeshByID(sourceProperty);
  8046. }
  8047. break;
  8048. case 7: // Color Curves
  8049. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8050. break;
  8051. case 8: // Color 4
  8052. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8053. break;
  8054. case 9: // Image Processing
  8055. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8056. break;
  8057. case 10: // Quaternion
  8058. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8059. break;
  8060. case 11: // Camera reference
  8061. if (scene) {
  8062. dest[property] = scene.getCameraByID(sourceProperty);
  8063. }
  8064. break;
  8065. }
  8066. }
  8067. }
  8068. return destination;
  8069. };
  8070. SerializationHelper.Clone = function (creationFunction, source) {
  8071. return _copySource(creationFunction, source, false);
  8072. };
  8073. SerializationHelper.Instanciate = function (creationFunction, source) {
  8074. return _copySource(creationFunction, source, true);
  8075. };
  8076. return SerializationHelper;
  8077. }());
  8078. BABYLON.SerializationHelper = SerializationHelper;
  8079. })(BABYLON || (BABYLON = {}));
  8080. //# sourceMappingURL=babylon.decorators.js.map
  8081. var BABYLON;
  8082. (function (BABYLON) {
  8083. /**
  8084. * Wrapper class for promise with external resolve and reject.
  8085. */
  8086. var Deferred = /** @class */ (function () {
  8087. /**
  8088. * Constructor for this deferred object.
  8089. */
  8090. function Deferred() {
  8091. var _this = this;
  8092. this.promise = new Promise(function (resolve, reject) {
  8093. _this._resolve = resolve;
  8094. _this._reject = reject;
  8095. });
  8096. }
  8097. Object.defineProperty(Deferred.prototype, "resolve", {
  8098. /**
  8099. * The resolve method of the promise associated with this deferred object.
  8100. */
  8101. get: function () {
  8102. return this._resolve;
  8103. },
  8104. enumerable: true,
  8105. configurable: true
  8106. });
  8107. Object.defineProperty(Deferred.prototype, "reject", {
  8108. /**
  8109. * The reject method of the promise associated with this deferred object.
  8110. */
  8111. get: function () {
  8112. return this._reject;
  8113. },
  8114. enumerable: true,
  8115. configurable: true
  8116. });
  8117. return Deferred;
  8118. }());
  8119. BABYLON.Deferred = Deferred;
  8120. })(BABYLON || (BABYLON = {}));
  8121. //# sourceMappingURL=babylon.deferred.js.map
  8122. var BABYLON;
  8123. (function (BABYLON) {
  8124. /**
  8125. * A class serves as a medium between the observable and its observers
  8126. */
  8127. var EventState = /** @class */ (function () {
  8128. /**
  8129. * Create a new EventState
  8130. * @param mask defines the mask associated with this state
  8131. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8132. * @param target defines the original target of the state
  8133. * @param currentTarget defines the current target of the state
  8134. */
  8135. function EventState(mask, skipNextObservers, target, currentTarget) {
  8136. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8137. this.initalize(mask, skipNextObservers, target, currentTarget);
  8138. }
  8139. /**
  8140. * Initialize the current event state
  8141. * @param mask defines the mask associated with this state
  8142. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8143. * @param target defines the original target of the state
  8144. * @param currentTarget defines the current target of the state
  8145. * @returns the current event state
  8146. */
  8147. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8148. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8149. this.mask = mask;
  8150. this.skipNextObservers = skipNextObservers;
  8151. this.target = target;
  8152. this.currentTarget = currentTarget;
  8153. return this;
  8154. };
  8155. return EventState;
  8156. }());
  8157. BABYLON.EventState = EventState;
  8158. /**
  8159. * Represent an Observer registered to a given Observable object.
  8160. */
  8161. var Observer = /** @class */ (function () {
  8162. /**
  8163. * Creates a new observer
  8164. * @param callback defines the callback to call when the observer is notified
  8165. * @param mask defines the mask of the observer (used to filter notifications)
  8166. * @param scope defines the current scope used to restore the JS context
  8167. */
  8168. function Observer(
  8169. /**
  8170. * Defines the callback to call when the observer is notified
  8171. */
  8172. callback,
  8173. /**
  8174. * Defines the mask of the observer (used to filter notifications)
  8175. */
  8176. mask,
  8177. /**
  8178. * Defines the current scope used to restore the JS context
  8179. */
  8180. scope) {
  8181. if (scope === void 0) { scope = null; }
  8182. this.callback = callback;
  8183. this.mask = mask;
  8184. this.scope = scope;
  8185. /** @hidden */
  8186. this._willBeUnregistered = false;
  8187. /**
  8188. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8189. */
  8190. this.unregisterOnNextCall = false;
  8191. }
  8192. return Observer;
  8193. }());
  8194. BABYLON.Observer = Observer;
  8195. /**
  8196. * Represent a list of observers registered to multiple Observables object.
  8197. */
  8198. var MultiObserver = /** @class */ (function () {
  8199. function MultiObserver() {
  8200. }
  8201. /**
  8202. * Release associated resources
  8203. */
  8204. MultiObserver.prototype.dispose = function () {
  8205. if (this._observers && this._observables) {
  8206. for (var index = 0; index < this._observers.length; index++) {
  8207. this._observables[index].remove(this._observers[index]);
  8208. }
  8209. }
  8210. this._observers = null;
  8211. this._observables = null;
  8212. };
  8213. /**
  8214. * Raise a callback when one of the observable will notify
  8215. * @param observables defines a list of observables to watch
  8216. * @param callback defines the callback to call on notification
  8217. * @param mask defines the mask used to filter notifications
  8218. * @param scope defines the current scope used to restore the JS context
  8219. * @returns the new MultiObserver
  8220. */
  8221. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8222. if (mask === void 0) { mask = -1; }
  8223. if (scope === void 0) { scope = null; }
  8224. var result = new MultiObserver();
  8225. result._observers = new Array();
  8226. result._observables = observables;
  8227. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8228. var observable = observables_1[_i];
  8229. var observer = observable.add(callback, mask, false, scope);
  8230. if (observer) {
  8231. result._observers.push(observer);
  8232. }
  8233. }
  8234. return result;
  8235. };
  8236. return MultiObserver;
  8237. }());
  8238. BABYLON.MultiObserver = MultiObserver;
  8239. /**
  8240. * The Observable class is a simple implementation of the Observable pattern.
  8241. *
  8242. * 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.
  8243. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8244. * 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).
  8245. * 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.
  8246. */
  8247. var Observable = /** @class */ (function () {
  8248. /**
  8249. * Creates a new observable
  8250. * @param onObserverAdded defines a callback to call when a new observer is added
  8251. */
  8252. function Observable(onObserverAdded) {
  8253. this._observers = new Array();
  8254. this._eventState = new EventState(0);
  8255. if (onObserverAdded) {
  8256. this._onObserverAdded = onObserverAdded;
  8257. }
  8258. }
  8259. /**
  8260. * Create a new Observer with the specified callback
  8261. * @param callback the callback that will be executed for that Observer
  8262. * @param mask the mask used to filter observers
  8263. * @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.
  8264. * @param scope optional scope for the callback to be called from
  8265. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8266. * @returns the new observer created for the callback
  8267. */
  8268. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8269. if (mask === void 0) { mask = -1; }
  8270. if (insertFirst === void 0) { insertFirst = false; }
  8271. if (scope === void 0) { scope = null; }
  8272. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8273. if (!callback) {
  8274. return null;
  8275. }
  8276. var observer = new Observer(callback, mask, scope);
  8277. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8278. if (insertFirst) {
  8279. this._observers.unshift(observer);
  8280. }
  8281. else {
  8282. this._observers.push(observer);
  8283. }
  8284. if (this._onObserverAdded) {
  8285. this._onObserverAdded(observer);
  8286. }
  8287. return observer;
  8288. };
  8289. /**
  8290. * Create a new Observer with the specified callback and unregisters after the next notification
  8291. * @param callback the callback that will be executed for that Observer
  8292. * @returns the new observer created for the callback
  8293. */
  8294. Observable.prototype.addOnce = function (callback) {
  8295. return this.add(callback, undefined, undefined, undefined, true);
  8296. };
  8297. /**
  8298. * Remove an Observer from the Observable object
  8299. * @param observer the instance of the Observer to remove
  8300. * @returns false if it doesn't belong to this Observable
  8301. */
  8302. Observable.prototype.remove = function (observer) {
  8303. if (!observer) {
  8304. return false;
  8305. }
  8306. var index = this._observers.indexOf(observer);
  8307. if (index !== -1) {
  8308. this._deferUnregister(observer);
  8309. return true;
  8310. }
  8311. return false;
  8312. };
  8313. /**
  8314. * Remove a callback from the Observable object
  8315. * @param callback the callback to remove
  8316. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8317. * @returns false if it doesn't belong to this Observable
  8318. */
  8319. Observable.prototype.removeCallback = function (callback, scope) {
  8320. for (var index = 0; index < this._observers.length; index++) {
  8321. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8322. this._deferUnregister(this._observers[index]);
  8323. return true;
  8324. }
  8325. }
  8326. return false;
  8327. };
  8328. Observable.prototype._deferUnregister = function (observer) {
  8329. var _this = this;
  8330. observer.unregisterOnNextCall = false;
  8331. observer._willBeUnregistered = true;
  8332. BABYLON.Tools.SetImmediate(function () {
  8333. _this._remove(observer);
  8334. });
  8335. };
  8336. // This should only be called when not iterating over _observers to avoid callback skipping.
  8337. // Removes an observer from the _observer Array.
  8338. Observable.prototype._remove = function (observer) {
  8339. if (!observer) {
  8340. return false;
  8341. }
  8342. var index = this._observers.indexOf(observer);
  8343. if (index !== -1) {
  8344. this._observers.splice(index, 1);
  8345. return true;
  8346. }
  8347. return false;
  8348. };
  8349. /**
  8350. * Notify all Observers by calling their respective callback with the given data
  8351. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8352. * @param eventData defines the data to send to all observers
  8353. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8354. * @param target defines the original target of the state
  8355. * @param currentTarget defines the current target of the state
  8356. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8357. */
  8358. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8359. if (mask === void 0) { mask = -1; }
  8360. if (!this._observers.length) {
  8361. return true;
  8362. }
  8363. var state = this._eventState;
  8364. state.mask = mask;
  8365. state.target = target;
  8366. state.currentTarget = currentTarget;
  8367. state.skipNextObservers = false;
  8368. state.lastReturnValue = eventData;
  8369. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8370. var obs = _a[_i];
  8371. if (obs._willBeUnregistered) {
  8372. continue;
  8373. }
  8374. if (obs.mask & mask) {
  8375. if (obs.scope) {
  8376. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8377. }
  8378. else {
  8379. state.lastReturnValue = obs.callback(eventData, state);
  8380. }
  8381. if (obs.unregisterOnNextCall) {
  8382. this._deferUnregister(obs);
  8383. }
  8384. }
  8385. if (state.skipNextObservers) {
  8386. return false;
  8387. }
  8388. }
  8389. return true;
  8390. };
  8391. /**
  8392. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8393. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8394. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8395. * and it is crucial that all callbacks will be executed.
  8396. * The order of the callbacks is kept, callbacks are not executed parallel.
  8397. *
  8398. * @param eventData The data to be sent to each callback
  8399. * @param mask is used to filter observers defaults to -1
  8400. * @param target defines the callback target (see EventState)
  8401. * @param currentTarget defines he current object in the bubbling phase
  8402. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8403. */
  8404. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8405. var _this = this;
  8406. if (mask === void 0) { mask = -1; }
  8407. // create an empty promise
  8408. var p = Promise.resolve(eventData);
  8409. // no observers? return this promise.
  8410. if (!this._observers.length) {
  8411. return p;
  8412. }
  8413. var state = this._eventState;
  8414. state.mask = mask;
  8415. state.target = target;
  8416. state.currentTarget = currentTarget;
  8417. state.skipNextObservers = false;
  8418. // execute one callback after another (not using Promise.all, the order is important)
  8419. this._observers.forEach(function (obs) {
  8420. if (state.skipNextObservers) {
  8421. return;
  8422. }
  8423. if (obs._willBeUnregistered) {
  8424. return;
  8425. }
  8426. if (obs.mask & mask) {
  8427. if (obs.scope) {
  8428. p = p.then(function (lastReturnedValue) {
  8429. state.lastReturnValue = lastReturnedValue;
  8430. return obs.callback.apply(obs.scope, [eventData, state]);
  8431. });
  8432. }
  8433. else {
  8434. p = p.then(function (lastReturnedValue) {
  8435. state.lastReturnValue = lastReturnedValue;
  8436. return obs.callback(eventData, state);
  8437. });
  8438. }
  8439. if (obs.unregisterOnNextCall) {
  8440. _this._deferUnregister(obs);
  8441. }
  8442. }
  8443. });
  8444. // return the eventData
  8445. return p.then(function () { return eventData; });
  8446. };
  8447. /**
  8448. * Notify a specific observer
  8449. * @param observer defines the observer to notify
  8450. * @param eventData defines the data to be sent to each callback
  8451. * @param mask is used to filter observers defaults to -1
  8452. */
  8453. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8454. if (mask === void 0) { mask = -1; }
  8455. var state = this._eventState;
  8456. state.mask = mask;
  8457. state.skipNextObservers = false;
  8458. observer.callback(eventData, state);
  8459. };
  8460. /**
  8461. * Gets a boolean indicating if the observable has at least one observer
  8462. * @returns true is the Observable has at least one Observer registered
  8463. */
  8464. Observable.prototype.hasObservers = function () {
  8465. return this._observers.length > 0;
  8466. };
  8467. /**
  8468. * Clear the list of observers
  8469. */
  8470. Observable.prototype.clear = function () {
  8471. this._observers = new Array();
  8472. this._onObserverAdded = null;
  8473. };
  8474. /**
  8475. * Clone the current observable
  8476. * @returns a new observable
  8477. */
  8478. Observable.prototype.clone = function () {
  8479. var result = new Observable();
  8480. result._observers = this._observers.slice(0);
  8481. return result;
  8482. };
  8483. /**
  8484. * Does this observable handles observer registered with a given mask
  8485. * @param mask defines the mask to be tested
  8486. * @return whether or not one observer registered with the given mask is handeled
  8487. **/
  8488. Observable.prototype.hasSpecificMask = function (mask) {
  8489. if (mask === void 0) { mask = -1; }
  8490. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8491. var obs = _a[_i];
  8492. if (obs.mask & mask || obs.mask === mask) {
  8493. return true;
  8494. }
  8495. }
  8496. return false;
  8497. };
  8498. return Observable;
  8499. }());
  8500. BABYLON.Observable = Observable;
  8501. })(BABYLON || (BABYLON = {}));
  8502. //# sourceMappingURL=babylon.observable.js.map
  8503. var BABYLON;
  8504. (function (BABYLON) {
  8505. /**
  8506. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8507. */
  8508. var SmartArray = /** @class */ (function () {
  8509. /**
  8510. * Instantiates a Smart Array.
  8511. * @param capacity defines the default capacity of the array.
  8512. */
  8513. function SmartArray(capacity) {
  8514. /**
  8515. * The active length of the array.
  8516. */
  8517. this.length = 0;
  8518. this.data = new Array(capacity);
  8519. this._id = SmartArray._GlobalId++;
  8520. }
  8521. /**
  8522. * Pushes a value at the end of the active data.
  8523. * @param value defines the object to push in the array.
  8524. */
  8525. SmartArray.prototype.push = function (value) {
  8526. this.data[this.length++] = value;
  8527. if (this.length > this.data.length) {
  8528. this.data.length *= 2;
  8529. }
  8530. };
  8531. /**
  8532. * Iterates over the active data and apply the lambda to them.
  8533. * @param func defines the action to apply on each value.
  8534. */
  8535. SmartArray.prototype.forEach = function (func) {
  8536. for (var index = 0; index < this.length; index++) {
  8537. func(this.data[index]);
  8538. }
  8539. };
  8540. /**
  8541. * Sorts the full sets of data.
  8542. * @param compareFn defines the comparison function to apply.
  8543. */
  8544. SmartArray.prototype.sort = function (compareFn) {
  8545. this.data.sort(compareFn);
  8546. };
  8547. /**
  8548. * Resets the active data to an empty array.
  8549. */
  8550. SmartArray.prototype.reset = function () {
  8551. this.length = 0;
  8552. };
  8553. /**
  8554. * Releases all the data from the array as well as the array.
  8555. */
  8556. SmartArray.prototype.dispose = function () {
  8557. this.reset();
  8558. if (this.data) {
  8559. this.data.length = 0;
  8560. this.data = [];
  8561. }
  8562. };
  8563. /**
  8564. * Concats the active data with a given array.
  8565. * @param array defines the data to concatenate with.
  8566. */
  8567. SmartArray.prototype.concat = function (array) {
  8568. if (array.length === 0) {
  8569. return;
  8570. }
  8571. if (this.length + array.length > this.data.length) {
  8572. this.data.length = (this.length + array.length) * 2;
  8573. }
  8574. for (var index = 0; index < array.length; index++) {
  8575. this.data[this.length++] = (array.data || array)[index];
  8576. }
  8577. };
  8578. /**
  8579. * Returns the position of a value in the active data.
  8580. * @param value defines the value to find the index for
  8581. * @returns the index if found in the active data otherwise -1
  8582. */
  8583. SmartArray.prototype.indexOf = function (value) {
  8584. var position = this.data.indexOf(value);
  8585. if (position >= this.length) {
  8586. return -1;
  8587. }
  8588. return position;
  8589. };
  8590. /**
  8591. * Returns whether an element is part of the active data.
  8592. * @param value defines the value to look for
  8593. * @returns true if found in the active data otherwise false
  8594. */
  8595. SmartArray.prototype.contains = function (value) {
  8596. return this.indexOf(value) !== -1;
  8597. };
  8598. // Statics
  8599. SmartArray._GlobalId = 0;
  8600. return SmartArray;
  8601. }());
  8602. BABYLON.SmartArray = SmartArray;
  8603. /**
  8604. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8605. * The data in this array can only be present once
  8606. */
  8607. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8608. __extends(SmartArrayNoDuplicate, _super);
  8609. function SmartArrayNoDuplicate() {
  8610. var _this = _super !== null && _super.apply(this, arguments) || this;
  8611. _this._duplicateId = 0;
  8612. return _this;
  8613. }
  8614. /**
  8615. * Pushes a value at the end of the active data.
  8616. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8617. * @param value defines the object to push in the array.
  8618. */
  8619. SmartArrayNoDuplicate.prototype.push = function (value) {
  8620. _super.prototype.push.call(this, value);
  8621. if (!value.__smartArrayFlags) {
  8622. value.__smartArrayFlags = {};
  8623. }
  8624. value.__smartArrayFlags[this._id] = this._duplicateId;
  8625. };
  8626. /**
  8627. * Pushes a value at the end of the active data.
  8628. * If the data is already present, it won t be added again
  8629. * @param value defines the object to push in the array.
  8630. * @returns true if added false if it was already present
  8631. */
  8632. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8633. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8634. return false;
  8635. }
  8636. this.push(value);
  8637. return true;
  8638. };
  8639. /**
  8640. * Resets the active data to an empty array.
  8641. */
  8642. SmartArrayNoDuplicate.prototype.reset = function () {
  8643. _super.prototype.reset.call(this);
  8644. this._duplicateId++;
  8645. };
  8646. /**
  8647. * Concats the active data with a given array.
  8648. * This ensures no dupplicate will be present in the result.
  8649. * @param array defines the data to concatenate with.
  8650. */
  8651. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8652. if (array.length === 0) {
  8653. return;
  8654. }
  8655. if (this.length + array.length > this.data.length) {
  8656. this.data.length = (this.length + array.length) * 2;
  8657. }
  8658. for (var index = 0; index < array.length; index++) {
  8659. var item = (array.data || array)[index];
  8660. this.pushNoDuplicate(item);
  8661. }
  8662. };
  8663. return SmartArrayNoDuplicate;
  8664. }(SmartArray));
  8665. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8666. })(BABYLON || (BABYLON = {}));
  8667. //# sourceMappingURL=babylon.smartArray.js.map
  8668. var BABYLON;
  8669. (function (BABYLON) {
  8670. /** Class used to store color4 gradient */
  8671. var ColorGradient = /** @class */ (function () {
  8672. function ColorGradient() {
  8673. }
  8674. /**
  8675. * Will get a color picked randomly between color1 and color2.
  8676. * If color2 is undefined then color1 will be used
  8677. * @param result defines the target Color4 to store the result in
  8678. */
  8679. ColorGradient.prototype.getColorToRef = function (result) {
  8680. if (!this.color2) {
  8681. result.copyFrom(this.color1);
  8682. return;
  8683. }
  8684. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8685. };
  8686. return ColorGradient;
  8687. }());
  8688. BABYLON.ColorGradient = ColorGradient;
  8689. /** Class used to store color 3 gradient */
  8690. var Color3Gradient = /** @class */ (function () {
  8691. function Color3Gradient() {
  8692. }
  8693. return Color3Gradient;
  8694. }());
  8695. BABYLON.Color3Gradient = Color3Gradient;
  8696. /** Class used to store factor gradient */
  8697. var FactorGradient = /** @class */ (function () {
  8698. function FactorGradient() {
  8699. }
  8700. /**
  8701. * Will get a number picked randomly between factor1 and factor2.
  8702. * If factor2 is undefined then factor1 will be used
  8703. * @returns the picked number
  8704. */
  8705. FactorGradient.prototype.getFactor = function () {
  8706. if (this.factor2 === undefined) {
  8707. return this.factor1;
  8708. }
  8709. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8710. };
  8711. return FactorGradient;
  8712. }());
  8713. BABYLON.FactorGradient = FactorGradient;
  8714. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8715. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8716. var LoadFileError = /** @class */ (function (_super) {
  8717. __extends(LoadFileError, _super);
  8718. function LoadFileError(message, request) {
  8719. var _this = _super.call(this, message) || this;
  8720. _this.request = request;
  8721. _this.name = "LoadFileError";
  8722. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8723. return _this;
  8724. }
  8725. // Polyfill for Object.setPrototypeOf if necessary.
  8726. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8727. return LoadFileError;
  8728. }(Error));
  8729. BABYLON.LoadFileError = LoadFileError;
  8730. var RetryStrategy = /** @class */ (function () {
  8731. function RetryStrategy() {
  8732. }
  8733. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8734. if (maxRetries === void 0) { maxRetries = 3; }
  8735. if (baseInterval === void 0) { baseInterval = 500; }
  8736. return function (url, request, retryIndex) {
  8737. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8738. return -1;
  8739. }
  8740. return Math.pow(2, retryIndex) * baseInterval;
  8741. };
  8742. };
  8743. return RetryStrategy;
  8744. }());
  8745. BABYLON.RetryStrategy = RetryStrategy;
  8746. // Screenshots
  8747. var screenshotCanvas;
  8748. var cloneValue = function (source, destinationObject) {
  8749. if (!source)
  8750. return null;
  8751. if (source instanceof BABYLON.Mesh) {
  8752. return null;
  8753. }
  8754. if (source instanceof BABYLON.SubMesh) {
  8755. return source.clone(destinationObject);
  8756. }
  8757. else if (source.clone) {
  8758. return source.clone();
  8759. }
  8760. return null;
  8761. };
  8762. var Tools = /** @class */ (function () {
  8763. function Tools() {
  8764. }
  8765. /**
  8766. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8767. * @param u defines the coordinate on X axis
  8768. * @param v defines the coordinate on Y axis
  8769. * @param width defines the width of the source data
  8770. * @param height defines the height of the source data
  8771. * @param pixels defines the source byte array
  8772. * @param color defines the output color
  8773. */
  8774. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8775. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8776. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8777. var position = (wrappedU + wrappedV * width) * 4;
  8778. color.r = pixels[position] / 255;
  8779. color.g = pixels[position + 1] / 255;
  8780. color.b = pixels[position + 2] / 255;
  8781. color.a = pixels[position + 3] / 255;
  8782. };
  8783. /**
  8784. * Interpolates between a and b via alpha
  8785. * @param a The lower value (returned when alpha = 0)
  8786. * @param b The upper value (returned when alpha = 1)
  8787. * @param alpha The interpolation-factor
  8788. * @return The mixed value
  8789. */
  8790. Tools.Mix = function (a, b, alpha) {
  8791. return a * (1 - alpha) + b * alpha;
  8792. };
  8793. Tools.Instantiate = function (className) {
  8794. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8795. return Tools.RegisteredExternalClasses[className];
  8796. }
  8797. var arr = className.split(".");
  8798. var fn = (window || this);
  8799. for (var i = 0, len = arr.length; i < len; i++) {
  8800. fn = fn[arr[i]];
  8801. }
  8802. if (typeof fn !== "function") {
  8803. return null;
  8804. }
  8805. return fn;
  8806. };
  8807. /**
  8808. * Provides a slice function that will work even on IE
  8809. * @param data defines the array to slice
  8810. * @param start defines the start of the data (optional)
  8811. * @param end defines the end of the data (optional)
  8812. * @returns the new sliced array
  8813. */
  8814. Tools.Slice = function (data, start, end) {
  8815. if (data.slice) {
  8816. return data.slice(start, end);
  8817. }
  8818. return Array.prototype.slice.call(data, start, end);
  8819. };
  8820. Tools.SetImmediate = function (action) {
  8821. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8822. window.setImmediate(action);
  8823. }
  8824. else {
  8825. setTimeout(action, 1);
  8826. }
  8827. };
  8828. Tools.IsExponentOfTwo = function (value) {
  8829. var count = 1;
  8830. do {
  8831. count *= 2;
  8832. } while (count < value);
  8833. return count === value;
  8834. };
  8835. /**
  8836. * Returns the nearest 32-bit single precision float representation of a Number
  8837. * @param value A Number. If the parameter is of a different type, it will get converted
  8838. * to a number or to NaN if it cannot be converted
  8839. * @returns number
  8840. */
  8841. Tools.FloatRound = function (value) {
  8842. if (Math.fround) {
  8843. return Math.fround(value);
  8844. }
  8845. return (Tools._tmpFloatArray[0] = value);
  8846. };
  8847. /**
  8848. * Find the next highest power of two.
  8849. * @param x Number to start search from.
  8850. * @return Next highest power of two.
  8851. */
  8852. Tools.CeilingPOT = function (x) {
  8853. x--;
  8854. x |= x >> 1;
  8855. x |= x >> 2;
  8856. x |= x >> 4;
  8857. x |= x >> 8;
  8858. x |= x >> 16;
  8859. x++;
  8860. return x;
  8861. };
  8862. /**
  8863. * Find the next lowest power of two.
  8864. * @param x Number to start search from.
  8865. * @return Next lowest power of two.
  8866. */
  8867. Tools.FloorPOT = function (x) {
  8868. x = x | (x >> 1);
  8869. x = x | (x >> 2);
  8870. x = x | (x >> 4);
  8871. x = x | (x >> 8);
  8872. x = x | (x >> 16);
  8873. return x - (x >> 1);
  8874. };
  8875. /**
  8876. * Find the nearest power of two.
  8877. * @param x Number to start search from.
  8878. * @return Next nearest power of two.
  8879. */
  8880. Tools.NearestPOT = function (x) {
  8881. var c = Tools.CeilingPOT(x);
  8882. var f = Tools.FloorPOT(x);
  8883. return (c - x) > (x - f) ? f : c;
  8884. };
  8885. Tools.GetExponentOfTwo = function (value, max, mode) {
  8886. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8887. var pot;
  8888. switch (mode) {
  8889. case BABYLON.Engine.SCALEMODE_FLOOR:
  8890. pot = Tools.FloorPOT(value);
  8891. break;
  8892. case BABYLON.Engine.SCALEMODE_NEAREST:
  8893. pot = Tools.NearestPOT(value);
  8894. break;
  8895. case BABYLON.Engine.SCALEMODE_CEILING:
  8896. default:
  8897. pot = Tools.CeilingPOT(value);
  8898. break;
  8899. }
  8900. return Math.min(pot, max);
  8901. };
  8902. Tools.GetFilename = function (path) {
  8903. var index = path.lastIndexOf("/");
  8904. if (index < 0)
  8905. return path;
  8906. return path.substring(index + 1);
  8907. };
  8908. /**
  8909. * Extracts the "folder" part of a path (everything before the filename).
  8910. * @param uri The URI to extract the info from
  8911. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8912. * @returns The "folder" part of the path
  8913. */
  8914. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8915. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8916. var index = uri.lastIndexOf("/");
  8917. if (index < 0) {
  8918. if (returnUnchangedIfNoSlash) {
  8919. return uri;
  8920. }
  8921. return "";
  8922. }
  8923. return uri.substring(0, index + 1);
  8924. };
  8925. Tools.GetDOMTextContent = function (element) {
  8926. var result = "";
  8927. var child = element.firstChild;
  8928. while (child) {
  8929. if (child.nodeType === 3) {
  8930. result += child.textContent;
  8931. }
  8932. child = child.nextSibling;
  8933. }
  8934. return result;
  8935. };
  8936. Tools.ToDegrees = function (angle) {
  8937. return angle * 180 / Math.PI;
  8938. };
  8939. Tools.ToRadians = function (angle) {
  8940. return angle * Math.PI / 180;
  8941. };
  8942. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8943. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8944. var output = "";
  8945. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8946. var i = 0;
  8947. var bytes = new Uint8Array(buffer);
  8948. while (i < bytes.length) {
  8949. chr1 = bytes[i++];
  8950. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8951. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8952. enc1 = chr1 >> 2;
  8953. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8954. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8955. enc4 = chr3 & 63;
  8956. if (isNaN(chr2)) {
  8957. enc3 = enc4 = 64;
  8958. }
  8959. else if (isNaN(chr3)) {
  8960. enc4 = 64;
  8961. }
  8962. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8963. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8964. }
  8965. return "data:image/png;base64," + output;
  8966. };
  8967. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8968. if (bias === void 0) { bias = null; }
  8969. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8970. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8971. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8972. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8973. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8974. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8975. }
  8976. if (bias) {
  8977. minimum.x -= minimum.x * bias.x + bias.y;
  8978. minimum.y -= minimum.y * bias.x + bias.y;
  8979. minimum.z -= minimum.z * bias.x + bias.y;
  8980. maximum.x += maximum.x * bias.x + bias.y;
  8981. maximum.y += maximum.y * bias.x + bias.y;
  8982. maximum.z += maximum.z * bias.x + bias.y;
  8983. }
  8984. return {
  8985. minimum: minimum,
  8986. maximum: maximum
  8987. };
  8988. };
  8989. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8990. if (bias === void 0) { bias = null; }
  8991. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8992. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8993. if (!stride) {
  8994. stride = 3;
  8995. }
  8996. for (var index = start; index < start + count; index++) {
  8997. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8998. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8999. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9000. }
  9001. if (bias) {
  9002. minimum.x -= minimum.x * bias.x + bias.y;
  9003. minimum.y -= minimum.y * bias.x + bias.y;
  9004. minimum.z -= minimum.z * bias.x + bias.y;
  9005. maximum.x += maximum.x * bias.x + bias.y;
  9006. maximum.y += maximum.y * bias.x + bias.y;
  9007. maximum.z += maximum.z * bias.x + bias.y;
  9008. }
  9009. return {
  9010. minimum: minimum,
  9011. maximum: maximum
  9012. };
  9013. };
  9014. Tools.Vector2ArrayFeeder = function (array) {
  9015. return function (index) {
  9016. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  9017. var length = isFloatArray ? array.length / 2 : array.length;
  9018. if (index >= length) {
  9019. return null;
  9020. }
  9021. if (isFloatArray) {
  9022. var fa = array;
  9023. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  9024. }
  9025. var a = array;
  9026. return a[index];
  9027. };
  9028. };
  9029. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  9030. if (bias === void 0) { bias = null; }
  9031. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  9032. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  9033. var i = 0;
  9034. var cur = feeder(i++);
  9035. while (cur) {
  9036. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  9037. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  9038. cur = feeder(i++);
  9039. }
  9040. if (bias) {
  9041. minimum.x -= minimum.x * bias.x + bias.y;
  9042. minimum.y -= minimum.y * bias.x + bias.y;
  9043. maximum.x += maximum.x * bias.x + bias.y;
  9044. maximum.y += maximum.y * bias.x + bias.y;
  9045. }
  9046. return {
  9047. minimum: minimum,
  9048. maximum: maximum
  9049. };
  9050. };
  9051. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9052. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9053. return null;
  9054. return Array.isArray(obj) ? obj : [obj];
  9055. };
  9056. // Misc.
  9057. Tools.GetPointerPrefix = function () {
  9058. var eventPrefix = "pointer";
  9059. // Check if pointer events are supported
  9060. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9061. eventPrefix = "mouse";
  9062. }
  9063. return eventPrefix;
  9064. };
  9065. /**
  9066. * @param func - the function to be called
  9067. * @param requester - the object that will request the next frame. Falls back to window.
  9068. */
  9069. Tools.QueueNewFrame = function (func, requester) {
  9070. if (!Tools.IsWindowObjectExist()) {
  9071. return setTimeout(func, 16);
  9072. }
  9073. if (!requester) {
  9074. requester = window;
  9075. }
  9076. if (requester.requestAnimationFrame) {
  9077. return requester.requestAnimationFrame(func);
  9078. }
  9079. else if (requester.msRequestAnimationFrame) {
  9080. return requester.msRequestAnimationFrame(func);
  9081. }
  9082. else if (requester.webkitRequestAnimationFrame) {
  9083. return requester.webkitRequestAnimationFrame(func);
  9084. }
  9085. else if (requester.mozRequestAnimationFrame) {
  9086. return requester.mozRequestAnimationFrame(func);
  9087. }
  9088. else if (requester.oRequestAnimationFrame) {
  9089. return requester.oRequestAnimationFrame(func);
  9090. }
  9091. else {
  9092. return window.setTimeout(func, 16);
  9093. }
  9094. };
  9095. Tools.RequestFullscreen = function (element) {
  9096. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9097. if (!requestFunction)
  9098. return;
  9099. requestFunction.call(element);
  9100. };
  9101. Tools.ExitFullscreen = function () {
  9102. if (document.exitFullscreen) {
  9103. document.exitFullscreen();
  9104. }
  9105. else if (document.mozCancelFullScreen) {
  9106. document.mozCancelFullScreen();
  9107. }
  9108. else if (document.webkitCancelFullScreen) {
  9109. document.webkitCancelFullScreen();
  9110. }
  9111. else if (document.msCancelFullScreen) {
  9112. document.msCancelFullScreen();
  9113. }
  9114. };
  9115. Tools.SetCorsBehavior = function (url, element) {
  9116. if (url && url.indexOf("data:") === 0) {
  9117. return;
  9118. }
  9119. if (Tools.CorsBehavior) {
  9120. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9121. element.crossOrigin = Tools.CorsBehavior;
  9122. }
  9123. else {
  9124. var result = Tools.CorsBehavior(url);
  9125. if (result) {
  9126. element.crossOrigin = result;
  9127. }
  9128. }
  9129. }
  9130. };
  9131. // External files
  9132. Tools.CleanUrl = function (url) {
  9133. url = url.replace(/#/mg, "%23");
  9134. return url;
  9135. };
  9136. /**
  9137. * Loads an image as an HTMLImageElement.
  9138. * @param input url string, ArrayBuffer, or Blob to load
  9139. * @param onLoad callback called when the image successfully loads
  9140. * @param onError callback called when the image fails to load
  9141. * @param database database for caching
  9142. * @returns the HTMLImageElement of the loaded image
  9143. */
  9144. Tools.LoadImage = function (input, onLoad, onError, database) {
  9145. var url;
  9146. var usingObjectURL = false;
  9147. if (input instanceof ArrayBuffer) {
  9148. url = URL.createObjectURL(new Blob([input]));
  9149. usingObjectURL = true;
  9150. }
  9151. else if (input instanceof Blob) {
  9152. url = URL.createObjectURL(input);
  9153. usingObjectURL = true;
  9154. }
  9155. else {
  9156. url = Tools.CleanUrl(input);
  9157. url = Tools.PreprocessUrl(input);
  9158. }
  9159. var img = new Image();
  9160. Tools.SetCorsBehavior(url, img);
  9161. var loadHandler = function () {
  9162. if (usingObjectURL && img.src) {
  9163. URL.revokeObjectURL(img.src);
  9164. }
  9165. img.removeEventListener("load", loadHandler);
  9166. img.removeEventListener("error", errorHandler);
  9167. onLoad(img);
  9168. };
  9169. var errorHandler = function (err) {
  9170. if (usingObjectURL && img.src) {
  9171. URL.revokeObjectURL(img.src);
  9172. }
  9173. img.removeEventListener("load", loadHandler);
  9174. img.removeEventListener("error", errorHandler);
  9175. Tools.Error("Error while trying to load image: " + input);
  9176. if (onError) {
  9177. onError("Error while trying to load image: " + input, err);
  9178. }
  9179. };
  9180. img.addEventListener("load", loadHandler);
  9181. img.addEventListener("error", errorHandler);
  9182. var noIndexedDB = function () {
  9183. img.src = url;
  9184. };
  9185. var loadFromIndexedDB = function () {
  9186. if (database) {
  9187. database.loadImageFromDB(url, img);
  9188. }
  9189. };
  9190. //ANY database to do!
  9191. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9192. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9193. }
  9194. else {
  9195. if (url.indexOf("file:") !== -1) {
  9196. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9197. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9198. try {
  9199. var blobURL;
  9200. try {
  9201. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9202. }
  9203. catch (ex) {
  9204. // Chrome doesn't support oneTimeOnly parameter
  9205. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9206. }
  9207. img.src = blobURL;
  9208. usingObjectURL = true;
  9209. }
  9210. catch (e) {
  9211. img.src = "";
  9212. }
  9213. return img;
  9214. }
  9215. }
  9216. noIndexedDB();
  9217. }
  9218. return img;
  9219. };
  9220. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9221. url = Tools.CleanUrl(url);
  9222. url = Tools.PreprocessUrl(url);
  9223. // If file and file input are set
  9224. if (url.indexOf("file:") !== -1) {
  9225. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9226. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9227. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9228. }
  9229. }
  9230. var loadUrl = Tools.BaseUrl + url;
  9231. var aborted = false;
  9232. var fileRequest = {
  9233. onCompleteObservable: new BABYLON.Observable(),
  9234. abort: function () { return aborted = true; },
  9235. };
  9236. var requestFile = function () {
  9237. var request = new XMLHttpRequest();
  9238. var retryHandle = null;
  9239. fileRequest.abort = function () {
  9240. aborted = true;
  9241. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9242. request.abort();
  9243. }
  9244. if (retryHandle !== null) {
  9245. clearTimeout(retryHandle);
  9246. retryHandle = null;
  9247. }
  9248. };
  9249. var retryLoop = function (retryIndex) {
  9250. request.open('GET', loadUrl, true);
  9251. if (useArrayBuffer) {
  9252. request.responseType = "arraybuffer";
  9253. }
  9254. if (onProgress) {
  9255. request.addEventListener("progress", onProgress);
  9256. }
  9257. var onLoadEnd = function () {
  9258. request.removeEventListener("loadend", onLoadEnd);
  9259. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9260. fileRequest.onCompleteObservable.clear();
  9261. };
  9262. request.addEventListener("loadend", onLoadEnd);
  9263. var onReadyStateChange = function () {
  9264. if (aborted) {
  9265. return;
  9266. }
  9267. // In case of undefined state in some browsers.
  9268. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9269. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9270. request.removeEventListener("readystatechange", onReadyStateChange);
  9271. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9272. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9273. return;
  9274. }
  9275. var retryStrategy = Tools.DefaultRetryStrategy;
  9276. if (retryStrategy) {
  9277. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9278. if (waitTime !== -1) {
  9279. // Prevent the request from completing for retry.
  9280. request.removeEventListener("loadend", onLoadEnd);
  9281. request = new XMLHttpRequest();
  9282. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9283. return;
  9284. }
  9285. }
  9286. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9287. if (onError) {
  9288. onError(request, e);
  9289. }
  9290. else {
  9291. throw e;
  9292. }
  9293. }
  9294. };
  9295. request.addEventListener("readystatechange", onReadyStateChange);
  9296. request.send();
  9297. };
  9298. retryLoop(0);
  9299. };
  9300. // Caching all files
  9301. if (database && database.enableSceneOffline) {
  9302. var noIndexedDB_1 = function (request) {
  9303. if (request && request.status > 400) {
  9304. if (onError) {
  9305. onError(request);
  9306. }
  9307. }
  9308. else {
  9309. if (!aborted) {
  9310. requestFile();
  9311. }
  9312. }
  9313. };
  9314. var loadFromIndexedDB = function () {
  9315. // TODO: database needs to support aborting and should return a IFileRequest
  9316. if (aborted) {
  9317. return;
  9318. }
  9319. if (database) {
  9320. database.loadFileFromDB(url, function (data) {
  9321. if (!aborted) {
  9322. onSuccess(data);
  9323. }
  9324. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9325. }, onProgress ? function (event) {
  9326. if (!aborted) {
  9327. onProgress(event);
  9328. }
  9329. } : undefined, noIndexedDB_1, useArrayBuffer);
  9330. }
  9331. };
  9332. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9333. }
  9334. else {
  9335. requestFile();
  9336. }
  9337. return fileRequest;
  9338. };
  9339. /**
  9340. * Load a script (identified by an url). When the url returns, the
  9341. * content of this file is added into a new script element, attached to the DOM (body element)
  9342. */
  9343. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9344. if (!Tools.IsWindowObjectExist()) {
  9345. return;
  9346. }
  9347. var head = document.getElementsByTagName('head')[0];
  9348. var script = document.createElement('script');
  9349. script.type = 'text/javascript';
  9350. script.src = scriptUrl;
  9351. script.onload = function () {
  9352. if (onSuccess) {
  9353. onSuccess();
  9354. }
  9355. };
  9356. script.onerror = function (e) {
  9357. if (onError) {
  9358. onError("Unable to load script '" + scriptUrl + "'", e);
  9359. }
  9360. };
  9361. head.appendChild(script);
  9362. };
  9363. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9364. var reader = new FileReader();
  9365. var request = {
  9366. onCompleteObservable: new BABYLON.Observable(),
  9367. abort: function () { return reader.abort(); },
  9368. };
  9369. reader.onloadend = function (e) {
  9370. request.onCompleteObservable.notifyObservers(request);
  9371. };
  9372. reader.onload = function (e) {
  9373. //target doesn't have result from ts 1.3
  9374. callback(e.target['result']);
  9375. };
  9376. reader.onprogress = progressCallback;
  9377. reader.readAsDataURL(fileToLoad);
  9378. return request;
  9379. };
  9380. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9381. var reader = new FileReader();
  9382. var request = {
  9383. onCompleteObservable: new BABYLON.Observable(),
  9384. abort: function () { return reader.abort(); },
  9385. };
  9386. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9387. reader.onerror = function (e) {
  9388. Tools.Log("Error while reading file: " + fileToLoad.name);
  9389. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9390. };
  9391. reader.onload = function (e) {
  9392. //target doesn't have result from ts 1.3
  9393. callback(e.target['result']);
  9394. };
  9395. if (progressCallBack) {
  9396. reader.onprogress = progressCallBack;
  9397. }
  9398. if (!useArrayBuffer) {
  9399. // Asynchronous read
  9400. reader.readAsText(fileToLoad);
  9401. }
  9402. else {
  9403. reader.readAsArrayBuffer(fileToLoad);
  9404. }
  9405. return request;
  9406. };
  9407. //returns a downloadable url to a file content.
  9408. Tools.FileAsURL = function (content) {
  9409. var fileBlob = new Blob([content]);
  9410. var url = window.URL || window.webkitURL;
  9411. var link = url.createObjectURL(fileBlob);
  9412. return link;
  9413. };
  9414. // Misc.
  9415. Tools.Format = function (value, decimals) {
  9416. if (decimals === void 0) { decimals = 2; }
  9417. return value.toFixed(decimals);
  9418. };
  9419. Tools.CheckExtends = function (v, min, max) {
  9420. if (v.x < min.x)
  9421. min.x = v.x;
  9422. if (v.y < min.y)
  9423. min.y = v.y;
  9424. if (v.z < min.z)
  9425. min.z = v.z;
  9426. if (v.x > max.x)
  9427. max.x = v.x;
  9428. if (v.y > max.y)
  9429. max.y = v.y;
  9430. if (v.z > max.z)
  9431. max.z = v.z;
  9432. };
  9433. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9434. for (var prop in source) {
  9435. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9436. continue;
  9437. }
  9438. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9439. continue;
  9440. }
  9441. var sourceValue = source[prop];
  9442. var typeOfSourceValue = typeof sourceValue;
  9443. if (typeOfSourceValue === "function") {
  9444. continue;
  9445. }
  9446. try {
  9447. if (typeOfSourceValue === "object") {
  9448. if (sourceValue instanceof Array) {
  9449. destination[prop] = [];
  9450. if (sourceValue.length > 0) {
  9451. if (typeof sourceValue[0] == "object") {
  9452. for (var index = 0; index < sourceValue.length; index++) {
  9453. var clonedValue = cloneValue(sourceValue[index], destination);
  9454. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9455. destination[prop].push(clonedValue);
  9456. }
  9457. }
  9458. }
  9459. else {
  9460. destination[prop] = sourceValue.slice(0);
  9461. }
  9462. }
  9463. }
  9464. else {
  9465. destination[prop] = cloneValue(sourceValue, destination);
  9466. }
  9467. }
  9468. else {
  9469. destination[prop] = sourceValue;
  9470. }
  9471. }
  9472. catch (e) {
  9473. // Just ignore error (it could be because of a read-only property)
  9474. }
  9475. }
  9476. };
  9477. Tools.IsEmpty = function (obj) {
  9478. for (var i in obj) {
  9479. if (obj.hasOwnProperty(i)) {
  9480. return false;
  9481. }
  9482. }
  9483. return true;
  9484. };
  9485. Tools.RegisterTopRootEvents = function (events) {
  9486. for (var index = 0; index < events.length; index++) {
  9487. var event = events[index];
  9488. window.addEventListener(event.name, event.handler, false);
  9489. try {
  9490. if (window.parent) {
  9491. window.parent.addEventListener(event.name, event.handler, false);
  9492. }
  9493. }
  9494. catch (e) {
  9495. // Silently fails...
  9496. }
  9497. }
  9498. };
  9499. Tools.UnregisterTopRootEvents = function (events) {
  9500. for (var index = 0; index < events.length; index++) {
  9501. var event = events[index];
  9502. window.removeEventListener(event.name, event.handler);
  9503. try {
  9504. if (window.parent) {
  9505. window.parent.removeEventListener(event.name, event.handler);
  9506. }
  9507. }
  9508. catch (e) {
  9509. // Silently fails...
  9510. }
  9511. }
  9512. };
  9513. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9514. if (mimeType === void 0) { mimeType = "image/png"; }
  9515. // Read the contents of the framebuffer
  9516. var numberOfChannelsByLine = width * 4;
  9517. var halfHeight = height / 2;
  9518. //Reading datas from WebGL
  9519. var data = engine.readPixels(0, 0, width, height);
  9520. //To flip image on Y axis.
  9521. for (var i = 0; i < halfHeight; i++) {
  9522. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9523. var currentCell = j + i * numberOfChannelsByLine;
  9524. var targetLine = height - i - 1;
  9525. var targetCell = j + targetLine * numberOfChannelsByLine;
  9526. var temp = data[currentCell];
  9527. data[currentCell] = data[targetCell];
  9528. data[targetCell] = temp;
  9529. }
  9530. }
  9531. // Create a 2D canvas to store the result
  9532. if (!screenshotCanvas) {
  9533. screenshotCanvas = document.createElement('canvas');
  9534. }
  9535. screenshotCanvas.width = width;
  9536. screenshotCanvas.height = height;
  9537. var context = screenshotCanvas.getContext('2d');
  9538. if (context) {
  9539. // Copy the pixels to a 2D canvas
  9540. var imageData = context.createImageData(width, height);
  9541. var castData = (imageData.data);
  9542. castData.set(data);
  9543. context.putImageData(imageData, 0, 0);
  9544. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9545. }
  9546. };
  9547. /**
  9548. * Converts the canvas data to blob.
  9549. * This acts as a polyfill for browsers not supporting the to blob function.
  9550. * @param canvas Defines the canvas to extract the data from
  9551. * @param successCallback Defines the callback triggered once the data are available
  9552. * @param mimeType Defines the mime type of the result
  9553. */
  9554. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9555. if (mimeType === void 0) { mimeType = "image/png"; }
  9556. // We need HTMLCanvasElement.toBlob for HD screenshots
  9557. if (!canvas.toBlob) {
  9558. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9559. canvas.toBlob = function (callback, type, quality) {
  9560. var _this = this;
  9561. setTimeout(function () {
  9562. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9563. for (var i = 0; i < len; i++) {
  9564. arr[i] = binStr.charCodeAt(i);
  9565. }
  9566. callback(new Blob([arr]));
  9567. });
  9568. };
  9569. }
  9570. canvas.toBlob(function (blob) {
  9571. successCallback(blob);
  9572. }, mimeType);
  9573. };
  9574. /**
  9575. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9576. * @param successCallback Defines the callback triggered once the data are available
  9577. * @param mimeType Defines the mime type of the result
  9578. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9579. */
  9580. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9581. if (mimeType === void 0) { mimeType = "image/png"; }
  9582. if (successCallback) {
  9583. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9584. successCallback(base64Image);
  9585. }
  9586. else {
  9587. this.ToBlob(screenshotCanvas, function (blob) {
  9588. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9589. if (("download" in document.createElement("a"))) {
  9590. if (!fileName) {
  9591. var date = new Date();
  9592. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9593. fileName = "screenshot_" + stringDate + ".png";
  9594. }
  9595. Tools.Download(blob, fileName);
  9596. }
  9597. else {
  9598. var url = URL.createObjectURL(blob);
  9599. var newWindow = window.open("");
  9600. if (!newWindow)
  9601. return;
  9602. var img = newWindow.document.createElement("img");
  9603. img.onload = function () {
  9604. // no longer need to read the blob so it's revoked
  9605. URL.revokeObjectURL(url);
  9606. };
  9607. img.src = url;
  9608. newWindow.document.body.appendChild(img);
  9609. }
  9610. }, mimeType);
  9611. }
  9612. };
  9613. /**
  9614. * Downloads a blob in the browser
  9615. * @param blob defines the blob to download
  9616. * @param fileName defines the name of the downloaded file
  9617. */
  9618. Tools.Download = function (blob, fileName) {
  9619. if (navigator && navigator.msSaveBlob) {
  9620. navigator.msSaveBlob(blob, fileName);
  9621. return;
  9622. }
  9623. var url = window.URL.createObjectURL(blob);
  9624. var a = document.createElement("a");
  9625. document.body.appendChild(a);
  9626. a.style.display = "none";
  9627. a.href = url;
  9628. a.download = fileName;
  9629. a.addEventListener("click", function () {
  9630. if (a.parentElement) {
  9631. a.parentElement.removeChild(a);
  9632. }
  9633. });
  9634. a.click();
  9635. window.URL.revokeObjectURL(url);
  9636. };
  9637. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9638. if (mimeType === void 0) { mimeType = "image/png"; }
  9639. var width;
  9640. var height;
  9641. // If a precision value is specified
  9642. if (size.precision) {
  9643. width = Math.round(engine.getRenderWidth() * size.precision);
  9644. height = Math.round(width / engine.getAspectRatio(camera));
  9645. }
  9646. else if (size.width && size.height) {
  9647. width = size.width;
  9648. height = size.height;
  9649. }
  9650. //If passing only width, computing height to keep display canvas ratio.
  9651. else if (size.width && !size.height) {
  9652. width = size.width;
  9653. height = Math.round(width / engine.getAspectRatio(camera));
  9654. }
  9655. //If passing only height, computing width to keep display canvas ratio.
  9656. else if (size.height && !size.width) {
  9657. height = size.height;
  9658. width = Math.round(height * engine.getAspectRatio(camera));
  9659. }
  9660. //Assuming here that "size" parameter is a number
  9661. else if (!isNaN(size)) {
  9662. height = size;
  9663. width = size;
  9664. }
  9665. else {
  9666. Tools.Error("Invalid 'size' parameter !");
  9667. return;
  9668. }
  9669. if (!screenshotCanvas) {
  9670. screenshotCanvas = document.createElement('canvas');
  9671. }
  9672. screenshotCanvas.width = width;
  9673. screenshotCanvas.height = height;
  9674. var renderContext = screenshotCanvas.getContext("2d");
  9675. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9676. var newWidth = width;
  9677. var newHeight = newWidth / ratio;
  9678. if (newHeight > height) {
  9679. newHeight = height;
  9680. newWidth = newHeight * ratio;
  9681. }
  9682. var offsetX = Math.max(0, width - newWidth) / 2;
  9683. var offsetY = Math.max(0, height - newHeight) / 2;
  9684. var renderingCanvas = engine.getRenderingCanvas();
  9685. if (renderContext && renderingCanvas) {
  9686. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9687. }
  9688. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9689. };
  9690. /**
  9691. * Generates an image screenshot from the specified camera.
  9692. *
  9693. * @param engine The engine to use for rendering
  9694. * @param camera The camera to use for rendering
  9695. * @param size This parameter can be set to a single number or to an object with the
  9696. * following (optional) properties: precision, width, height. If a single number is passed,
  9697. * it will be used for both width and height. If an object is passed, the screenshot size
  9698. * will be derived from the parameters. The precision property is a multiplier allowing
  9699. * rendering at a higher or lower resolution.
  9700. * @param successCallback The callback receives a single parameter which contains the
  9701. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9702. * src parameter of an <img> to display it.
  9703. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9704. * Check your browser for supported MIME types.
  9705. * @param samples Texture samples (default: 1)
  9706. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9707. * @param fileName A name for for the downloaded file.
  9708. * @constructor
  9709. */
  9710. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9711. if (mimeType === void 0) { mimeType = "image/png"; }
  9712. if (samples === void 0) { samples = 1; }
  9713. if (antialiasing === void 0) { antialiasing = false; }
  9714. var width;
  9715. var height;
  9716. //If a precision value is specified
  9717. if (size.precision) {
  9718. width = Math.round(engine.getRenderWidth() * size.precision);
  9719. height = Math.round(width / engine.getAspectRatio(camera));
  9720. size = { width: width, height: height };
  9721. }
  9722. else if (size.width && size.height) {
  9723. width = size.width;
  9724. height = size.height;
  9725. }
  9726. //If passing only width, computing height to keep display canvas ratio.
  9727. else if (size.width && !size.height) {
  9728. width = size.width;
  9729. height = Math.round(width / engine.getAspectRatio(camera));
  9730. size = { width: width, height: height };
  9731. }
  9732. //If passing only height, computing width to keep display canvas ratio.
  9733. else if (size.height && !size.width) {
  9734. height = size.height;
  9735. width = Math.round(height * engine.getAspectRatio(camera));
  9736. size = { width: width, height: height };
  9737. }
  9738. //Assuming here that "size" parameter is a number
  9739. else if (!isNaN(size)) {
  9740. height = size;
  9741. width = size;
  9742. }
  9743. else {
  9744. Tools.Error("Invalid 'size' parameter !");
  9745. return;
  9746. }
  9747. var scene = camera.getScene();
  9748. var previousCamera = null;
  9749. if (scene.activeCamera !== camera) {
  9750. previousCamera = scene.activeCamera;
  9751. scene.activeCamera = camera;
  9752. }
  9753. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9754. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9755. texture.renderList = null;
  9756. texture.samples = samples;
  9757. if (antialiasing) {
  9758. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9759. }
  9760. texture.onAfterRenderObservable.add(function () {
  9761. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9762. });
  9763. scene.incrementRenderId();
  9764. scene.resetCachedMaterial();
  9765. texture.render(true);
  9766. texture.dispose();
  9767. if (previousCamera) {
  9768. scene.activeCamera = previousCamera;
  9769. }
  9770. camera.getProjectionMatrix(true); // Force cache refresh;
  9771. };
  9772. // XHR response validator for local file scenario
  9773. Tools.ValidateXHRData = function (xhr, dataType) {
  9774. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9775. if (dataType === void 0) { dataType = 7; }
  9776. try {
  9777. if (dataType & 1) {
  9778. if (xhr.responseText && xhr.responseText.length > 0) {
  9779. return true;
  9780. }
  9781. else if (dataType === 1) {
  9782. return false;
  9783. }
  9784. }
  9785. if (dataType & 2) {
  9786. // Check header width and height since there is no "TGA" magic number
  9787. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9788. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9789. return true;
  9790. }
  9791. else if (dataType === 2) {
  9792. return false;
  9793. }
  9794. }
  9795. if (dataType & 4) {
  9796. // Check for the "DDS" magic number
  9797. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9798. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9799. return true;
  9800. }
  9801. else {
  9802. return false;
  9803. }
  9804. }
  9805. }
  9806. catch (e) {
  9807. // Global protection
  9808. }
  9809. return false;
  9810. };
  9811. /**
  9812. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9813. * Be aware Math.random() could cause collisions, but:
  9814. * "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"
  9815. */
  9816. Tools.RandomId = function () {
  9817. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9818. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9819. return v.toString(16);
  9820. });
  9821. };
  9822. /**
  9823. * Test if the given uri is a base64 string.
  9824. * @param uri The uri to test
  9825. * @return True if the uri is a base64 string or false otherwise.
  9826. */
  9827. Tools.IsBase64 = function (uri) {
  9828. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9829. };
  9830. /**
  9831. * Decode the given base64 uri.
  9832. * @param uri The uri to decode
  9833. * @return The decoded base64 data.
  9834. */
  9835. Tools.DecodeBase64 = function (uri) {
  9836. var decodedString = atob(uri.split(",")[1]);
  9837. var bufferLength = decodedString.length;
  9838. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9839. for (var i = 0; i < bufferLength; i++) {
  9840. bufferView[i] = decodedString.charCodeAt(i);
  9841. }
  9842. return bufferView.buffer;
  9843. };
  9844. Object.defineProperty(Tools, "NoneLogLevel", {
  9845. get: function () {
  9846. return Tools._NoneLogLevel;
  9847. },
  9848. enumerable: true,
  9849. configurable: true
  9850. });
  9851. Object.defineProperty(Tools, "MessageLogLevel", {
  9852. get: function () {
  9853. return Tools._MessageLogLevel;
  9854. },
  9855. enumerable: true,
  9856. configurable: true
  9857. });
  9858. Object.defineProperty(Tools, "WarningLogLevel", {
  9859. get: function () {
  9860. return Tools._WarningLogLevel;
  9861. },
  9862. enumerable: true,
  9863. configurable: true
  9864. });
  9865. Object.defineProperty(Tools, "ErrorLogLevel", {
  9866. get: function () {
  9867. return Tools._ErrorLogLevel;
  9868. },
  9869. enumerable: true,
  9870. configurable: true
  9871. });
  9872. Object.defineProperty(Tools, "AllLogLevel", {
  9873. get: function () {
  9874. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9875. },
  9876. enumerable: true,
  9877. configurable: true
  9878. });
  9879. Tools._AddLogEntry = function (entry) {
  9880. Tools._LogCache = entry + Tools._LogCache;
  9881. if (Tools.OnNewCacheEntry) {
  9882. Tools.OnNewCacheEntry(entry);
  9883. }
  9884. };
  9885. Tools._FormatMessage = function (message) {
  9886. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9887. var date = new Date();
  9888. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9889. };
  9890. Tools._LogDisabled = function (message) {
  9891. // nothing to do
  9892. };
  9893. Tools._LogEnabled = function (message) {
  9894. var formattedMessage = Tools._FormatMessage(message);
  9895. console.log("BJS - " + formattedMessage);
  9896. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9897. Tools._AddLogEntry(entry);
  9898. };
  9899. Tools._WarnDisabled = function (message) {
  9900. // nothing to do
  9901. };
  9902. Tools._WarnEnabled = function (message) {
  9903. var formattedMessage = Tools._FormatMessage(message);
  9904. console.warn("BJS - " + formattedMessage);
  9905. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9906. Tools._AddLogEntry(entry);
  9907. };
  9908. Tools._ErrorDisabled = function (message) {
  9909. // nothing to do
  9910. };
  9911. Tools._ErrorEnabled = function (message) {
  9912. Tools.errorsCount++;
  9913. var formattedMessage = Tools._FormatMessage(message);
  9914. console.error("BJS - " + formattedMessage);
  9915. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9916. Tools._AddLogEntry(entry);
  9917. };
  9918. Object.defineProperty(Tools, "LogCache", {
  9919. get: function () {
  9920. return Tools._LogCache;
  9921. },
  9922. enumerable: true,
  9923. configurable: true
  9924. });
  9925. Tools.ClearLogCache = function () {
  9926. Tools._LogCache = "";
  9927. Tools.errorsCount = 0;
  9928. };
  9929. Object.defineProperty(Tools, "LogLevels", {
  9930. set: function (level) {
  9931. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9932. Tools.Log = Tools._LogEnabled;
  9933. }
  9934. else {
  9935. Tools.Log = Tools._LogDisabled;
  9936. }
  9937. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9938. Tools.Warn = Tools._WarnEnabled;
  9939. }
  9940. else {
  9941. Tools.Warn = Tools._WarnDisabled;
  9942. }
  9943. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9944. Tools.Error = Tools._ErrorEnabled;
  9945. }
  9946. else {
  9947. Tools.Error = Tools._ErrorDisabled;
  9948. }
  9949. },
  9950. enumerable: true,
  9951. configurable: true
  9952. });
  9953. /**
  9954. * Check if the loaded document was accessed via `file:`-Protocol.
  9955. * @returns boolean
  9956. */
  9957. Tools.IsFileURL = function () {
  9958. return location.protocol === "file:";
  9959. };
  9960. Tools.IsWindowObjectExist = function () {
  9961. return (typeof window) !== "undefined";
  9962. };
  9963. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9964. get: function () {
  9965. return Tools._PerformanceNoneLogLevel;
  9966. },
  9967. enumerable: true,
  9968. configurable: true
  9969. });
  9970. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9971. get: function () {
  9972. return Tools._PerformanceUserMarkLogLevel;
  9973. },
  9974. enumerable: true,
  9975. configurable: true
  9976. });
  9977. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9978. get: function () {
  9979. return Tools._PerformanceConsoleLogLevel;
  9980. },
  9981. enumerable: true,
  9982. configurable: true
  9983. });
  9984. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9985. set: function (level) {
  9986. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9987. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9988. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9989. return;
  9990. }
  9991. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9992. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9993. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9994. return;
  9995. }
  9996. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9997. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9998. },
  9999. enumerable: true,
  10000. configurable: true
  10001. });
  10002. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10003. };
  10004. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10005. };
  10006. Tools._StartUserMark = function (counterName, condition) {
  10007. if (condition === void 0) { condition = true; }
  10008. if (!Tools._performance) {
  10009. if (!Tools.IsWindowObjectExist()) {
  10010. return;
  10011. }
  10012. Tools._performance = window.performance;
  10013. }
  10014. if (!condition || !Tools._performance.mark) {
  10015. return;
  10016. }
  10017. Tools._performance.mark(counterName + "-Begin");
  10018. };
  10019. Tools._EndUserMark = function (counterName, condition) {
  10020. if (condition === void 0) { condition = true; }
  10021. if (!condition || !Tools._performance.mark) {
  10022. return;
  10023. }
  10024. Tools._performance.mark(counterName + "-End");
  10025. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10026. };
  10027. Tools._StartPerformanceConsole = function (counterName, condition) {
  10028. if (condition === void 0) { condition = true; }
  10029. if (!condition) {
  10030. return;
  10031. }
  10032. Tools._StartUserMark(counterName, condition);
  10033. if (console.time) {
  10034. console.time(counterName);
  10035. }
  10036. };
  10037. Tools._EndPerformanceConsole = function (counterName, condition) {
  10038. if (condition === void 0) { condition = true; }
  10039. if (!condition) {
  10040. return;
  10041. }
  10042. Tools._EndUserMark(counterName, condition);
  10043. if (console.time) {
  10044. console.timeEnd(counterName);
  10045. }
  10046. };
  10047. Object.defineProperty(Tools, "Now", {
  10048. get: function () {
  10049. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10050. return window.performance.now();
  10051. }
  10052. return Date.now();
  10053. },
  10054. enumerable: true,
  10055. configurable: true
  10056. });
  10057. /**
  10058. * This method will return the name of the class used to create the instance of the given object.
  10059. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10060. * @param object the object to get the class name from
  10061. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  10062. */
  10063. Tools.GetClassName = function (object, isType) {
  10064. if (isType === void 0) { isType = false; }
  10065. var name = null;
  10066. if (!isType && object.getClassName) {
  10067. name = object.getClassName();
  10068. }
  10069. else {
  10070. if (object instanceof Object) {
  10071. var classObj = isType ? object : Object.getPrototypeOf(object);
  10072. name = classObj.constructor["__bjsclassName__"];
  10073. }
  10074. if (!name) {
  10075. name = typeof object;
  10076. }
  10077. }
  10078. return name;
  10079. };
  10080. Tools.First = function (array, predicate) {
  10081. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10082. var el = array_1[_i];
  10083. if (predicate(el)) {
  10084. return el;
  10085. }
  10086. }
  10087. return null;
  10088. };
  10089. /**
  10090. * This method will return the name of the full name of the class, including its owning module (if any).
  10091. * 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).
  10092. * @param object the object to get the class name from
  10093. * @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.
  10094. */
  10095. Tools.getFullClassName = function (object, isType) {
  10096. if (isType === void 0) { isType = false; }
  10097. var className = null;
  10098. var moduleName = null;
  10099. if (!isType && object.getClassName) {
  10100. className = object.getClassName();
  10101. }
  10102. else {
  10103. if (object instanceof Object) {
  10104. var classObj = isType ? object : Object.getPrototypeOf(object);
  10105. className = classObj.constructor["__bjsclassName__"];
  10106. moduleName = classObj.constructor["__bjsmoduleName__"];
  10107. }
  10108. if (!className) {
  10109. className = typeof object;
  10110. }
  10111. }
  10112. if (!className) {
  10113. return null;
  10114. }
  10115. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10116. };
  10117. /**
  10118. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  10119. * @param array
  10120. */
  10121. Tools.arrayOrStringFeeder = function (array) {
  10122. return function (index) {
  10123. if (index >= array.length) {
  10124. return null;
  10125. }
  10126. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10127. if (val && val.getHashCode) {
  10128. val = val.getHashCode();
  10129. }
  10130. if (typeof val === "string") {
  10131. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10132. }
  10133. return val;
  10134. };
  10135. };
  10136. /**
  10137. * Compute the hashCode of a stream of number
  10138. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10139. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10140. * @return the hash code computed
  10141. */
  10142. Tools.hashCodeFromStream = function (feeder) {
  10143. // Based from here: http://stackoverflow.com/a/7616484/802124
  10144. var hash = 0;
  10145. var index = 0;
  10146. var chr = feeder(index++);
  10147. while (chr != null) {
  10148. hash = ((hash << 5) - hash) + chr;
  10149. hash |= 0; // Convert to 32bit integer
  10150. chr = feeder(index++);
  10151. }
  10152. return hash;
  10153. };
  10154. /**
  10155. * Returns a promise that resolves after the given amount of time.
  10156. * @param delay Number of milliseconds to delay
  10157. * @returns Promise that resolves after the given amount of time
  10158. */
  10159. Tools.DelayAsync = function (delay) {
  10160. return new Promise(function (resolve) {
  10161. setTimeout(function () {
  10162. resolve();
  10163. }, delay);
  10164. });
  10165. };
  10166. /**
  10167. * Gets the current gradient from an array of IValueGradient
  10168. * @param ratio defines the current ratio to get
  10169. * @param gradients defines the array of IValueGradient
  10170. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10171. */
  10172. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10173. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10174. var currentGradient = gradients[gradientIndex];
  10175. var nextGradient = gradients[gradientIndex + 1];
  10176. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10177. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10178. updateFunc(currentGradient, nextGradient, scale);
  10179. return;
  10180. }
  10181. }
  10182. // Use last index if over
  10183. var lastIndex = gradients.length - 1;
  10184. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10185. };
  10186. Tools.BaseUrl = "";
  10187. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10188. /**
  10189. * Default behaviour for cors in the application.
  10190. * It can be a string if the expected behavior is identical in the entire app.
  10191. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10192. */
  10193. Tools.CorsBehavior = "anonymous";
  10194. Tools.UseFallbackTexture = true;
  10195. /**
  10196. * Use this object to register external classes like custom textures or material
  10197. * to allow the laoders to instantiate them
  10198. */
  10199. Tools.RegisteredExternalClasses = {};
  10200. // Used in case of a texture loading problem
  10201. 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";
  10202. Tools._tmpFloatArray = new Float32Array(1);
  10203. Tools.PreprocessUrl = function (url) {
  10204. return url;
  10205. };
  10206. // Logs
  10207. Tools._NoneLogLevel = 0;
  10208. Tools._MessageLogLevel = 1;
  10209. Tools._WarningLogLevel = 2;
  10210. Tools._ErrorLogLevel = 4;
  10211. Tools._LogCache = "";
  10212. Tools.errorsCount = 0;
  10213. Tools.Log = Tools._LogEnabled;
  10214. Tools.Warn = Tools._WarnEnabled;
  10215. Tools.Error = Tools._ErrorEnabled;
  10216. // Performances
  10217. Tools._PerformanceNoneLogLevel = 0;
  10218. Tools._PerformanceUserMarkLogLevel = 1;
  10219. Tools._PerformanceConsoleLogLevel = 2;
  10220. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10221. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10222. return Tools;
  10223. }());
  10224. BABYLON.Tools = Tools;
  10225. /**
  10226. * This class is used to track a performance counter which is number based.
  10227. * The user has access to many properties which give statistics of different nature
  10228. *
  10229. * The implementer can track two kinds of Performance Counter: time and count
  10230. * 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.
  10231. * 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.
  10232. */
  10233. var PerfCounter = /** @class */ (function () {
  10234. function PerfCounter() {
  10235. this._startMonitoringTime = 0;
  10236. this._min = 0;
  10237. this._max = 0;
  10238. this._average = 0;
  10239. this._lastSecAverage = 0;
  10240. this._current = 0;
  10241. this._totalValueCount = 0;
  10242. this._totalAccumulated = 0;
  10243. this._lastSecAccumulated = 0;
  10244. this._lastSecTime = 0;
  10245. this._lastSecValueCount = 0;
  10246. }
  10247. Object.defineProperty(PerfCounter.prototype, "min", {
  10248. /**
  10249. * Returns the smallest value ever
  10250. */
  10251. get: function () {
  10252. return this._min;
  10253. },
  10254. enumerable: true,
  10255. configurable: true
  10256. });
  10257. Object.defineProperty(PerfCounter.prototype, "max", {
  10258. /**
  10259. * Returns the biggest value ever
  10260. */
  10261. get: function () {
  10262. return this._max;
  10263. },
  10264. enumerable: true,
  10265. configurable: true
  10266. });
  10267. Object.defineProperty(PerfCounter.prototype, "average", {
  10268. /**
  10269. * Returns the average value since the performance counter is running
  10270. */
  10271. get: function () {
  10272. return this._average;
  10273. },
  10274. enumerable: true,
  10275. configurable: true
  10276. });
  10277. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10278. /**
  10279. * Returns the average value of the last second the counter was monitored
  10280. */
  10281. get: function () {
  10282. return this._lastSecAverage;
  10283. },
  10284. enumerable: true,
  10285. configurable: true
  10286. });
  10287. Object.defineProperty(PerfCounter.prototype, "current", {
  10288. /**
  10289. * Returns the current value
  10290. */
  10291. get: function () {
  10292. return this._current;
  10293. },
  10294. enumerable: true,
  10295. configurable: true
  10296. });
  10297. Object.defineProperty(PerfCounter.prototype, "total", {
  10298. get: function () {
  10299. return this._totalAccumulated;
  10300. },
  10301. enumerable: true,
  10302. configurable: true
  10303. });
  10304. Object.defineProperty(PerfCounter.prototype, "count", {
  10305. get: function () {
  10306. return this._totalValueCount;
  10307. },
  10308. enumerable: true,
  10309. configurable: true
  10310. });
  10311. /**
  10312. * Call this method to start monitoring a new frame.
  10313. * 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.
  10314. */
  10315. PerfCounter.prototype.fetchNewFrame = function () {
  10316. this._totalValueCount++;
  10317. this._current = 0;
  10318. this._lastSecValueCount++;
  10319. };
  10320. /**
  10321. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10322. * @param newCount the count value to add to the monitored count
  10323. * @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.
  10324. */
  10325. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10326. if (!PerfCounter.Enabled) {
  10327. return;
  10328. }
  10329. this._current += newCount;
  10330. if (fetchResult) {
  10331. this._fetchResult();
  10332. }
  10333. };
  10334. /**
  10335. * Start monitoring this performance counter
  10336. */
  10337. PerfCounter.prototype.beginMonitoring = function () {
  10338. if (!PerfCounter.Enabled) {
  10339. return;
  10340. }
  10341. this._startMonitoringTime = Tools.Now;
  10342. };
  10343. /**
  10344. * Compute the time lapsed since the previous beginMonitoring() call.
  10345. * @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
  10346. */
  10347. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10348. if (newFrame === void 0) { newFrame = true; }
  10349. if (!PerfCounter.Enabled) {
  10350. return;
  10351. }
  10352. if (newFrame) {
  10353. this.fetchNewFrame();
  10354. }
  10355. var currentTime = Tools.Now;
  10356. this._current = currentTime - this._startMonitoringTime;
  10357. if (newFrame) {
  10358. this._fetchResult();
  10359. }
  10360. };
  10361. PerfCounter.prototype._fetchResult = function () {
  10362. this._totalAccumulated += this._current;
  10363. this._lastSecAccumulated += this._current;
  10364. // Min/Max update
  10365. this._min = Math.min(this._min, this._current);
  10366. this._max = Math.max(this._max, this._current);
  10367. this._average = this._totalAccumulated / this._totalValueCount;
  10368. // Reset last sec?
  10369. var now = Tools.Now;
  10370. if ((now - this._lastSecTime) > 1000) {
  10371. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10372. this._lastSecTime = now;
  10373. this._lastSecAccumulated = 0;
  10374. this._lastSecValueCount = 0;
  10375. }
  10376. };
  10377. PerfCounter.Enabled = true;
  10378. return PerfCounter;
  10379. }());
  10380. BABYLON.PerfCounter = PerfCounter;
  10381. /**
  10382. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10383. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10384. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10385. * @param name The name of the class, case should be preserved
  10386. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10387. */
  10388. function className(name, module) {
  10389. return function (target) {
  10390. target["__bjsclassName__"] = name;
  10391. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10392. };
  10393. }
  10394. BABYLON.className = className;
  10395. /**
  10396. * An implementation of a loop for asynchronous functions.
  10397. */
  10398. var AsyncLoop = /** @class */ (function () {
  10399. /**
  10400. * Constroctor.
  10401. * @param iterations the number of iterations.
  10402. * @param _fn the function to run each iteration
  10403. * @param _successCallback the callback that will be called upon succesful execution
  10404. * @param offset starting offset.
  10405. */
  10406. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10407. if (offset === void 0) { offset = 0; }
  10408. this.iterations = iterations;
  10409. this._fn = _fn;
  10410. this._successCallback = _successCallback;
  10411. this.index = offset - 1;
  10412. this._done = false;
  10413. }
  10414. /**
  10415. * Execute the next iteration. Must be called after the last iteration was finished.
  10416. */
  10417. AsyncLoop.prototype.executeNext = function () {
  10418. if (!this._done) {
  10419. if (this.index + 1 < this.iterations) {
  10420. ++this.index;
  10421. this._fn(this);
  10422. }
  10423. else {
  10424. this.breakLoop();
  10425. }
  10426. }
  10427. };
  10428. /**
  10429. * Break the loop and run the success callback.
  10430. */
  10431. AsyncLoop.prototype.breakLoop = function () {
  10432. this._done = true;
  10433. this._successCallback();
  10434. };
  10435. /**
  10436. * Helper function
  10437. */
  10438. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10439. if (offset === void 0) { offset = 0; }
  10440. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10441. loop.executeNext();
  10442. return loop;
  10443. };
  10444. /**
  10445. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10446. * @param iterations total number of iterations
  10447. * @param syncedIterations number of synchronous iterations in each async iteration.
  10448. * @param fn the function to call each iteration.
  10449. * @param callback a success call back that will be called when iterating stops.
  10450. * @param breakFunction a break condition (optional)
  10451. * @param timeout timeout settings for the setTimeout function. default - 0.
  10452. * @constructor
  10453. */
  10454. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10455. if (timeout === void 0) { timeout = 0; }
  10456. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10457. if (breakFunction && breakFunction())
  10458. loop.breakLoop();
  10459. else {
  10460. setTimeout(function () {
  10461. for (var i = 0; i < syncedIterations; ++i) {
  10462. var iteration = (loop.index * syncedIterations) + i;
  10463. if (iteration >= iterations)
  10464. break;
  10465. fn(iteration);
  10466. if (breakFunction && breakFunction()) {
  10467. loop.breakLoop();
  10468. break;
  10469. }
  10470. }
  10471. loop.executeNext();
  10472. }, timeout);
  10473. }
  10474. }, callback);
  10475. };
  10476. return AsyncLoop;
  10477. }());
  10478. BABYLON.AsyncLoop = AsyncLoop;
  10479. })(BABYLON || (BABYLON = {}));
  10480. //# sourceMappingURL=babylon.tools.js.map
  10481. var BABYLON;
  10482. (function (BABYLON) {
  10483. var PromiseStates;
  10484. (function (PromiseStates) {
  10485. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10486. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10487. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10488. })(PromiseStates || (PromiseStates = {}));
  10489. var FulFillmentAgregator = /** @class */ (function () {
  10490. function FulFillmentAgregator() {
  10491. this.count = 0;
  10492. this.target = 0;
  10493. this.results = [];
  10494. }
  10495. return FulFillmentAgregator;
  10496. }());
  10497. var InternalPromise = /** @class */ (function () {
  10498. function InternalPromise(resolver) {
  10499. var _this = this;
  10500. this._state = PromiseStates.Pending;
  10501. this._children = new Array();
  10502. this._rejectWasConsumed = false;
  10503. if (!resolver) {
  10504. return;
  10505. }
  10506. try {
  10507. resolver(function (value) {
  10508. _this._resolve(value);
  10509. }, function (reason) {
  10510. _this._reject(reason);
  10511. });
  10512. }
  10513. catch (e) {
  10514. this._reject(e);
  10515. }
  10516. }
  10517. Object.defineProperty(InternalPromise.prototype, "_result", {
  10518. get: function () {
  10519. return this._resultValue;
  10520. },
  10521. set: function (value) {
  10522. this._resultValue = value;
  10523. if (this._parent && this._parent._result === undefined) {
  10524. this._parent._result = value;
  10525. }
  10526. },
  10527. enumerable: true,
  10528. configurable: true
  10529. });
  10530. InternalPromise.prototype.catch = function (onRejected) {
  10531. return this.then(undefined, onRejected);
  10532. };
  10533. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10534. var _this = this;
  10535. var newPromise = new InternalPromise();
  10536. newPromise._onFulfilled = onFulfilled;
  10537. newPromise._onRejected = onRejected;
  10538. // Composition
  10539. this._children.push(newPromise);
  10540. newPromise._parent = this;
  10541. if (this._state !== PromiseStates.Pending) {
  10542. BABYLON.Tools.SetImmediate(function () {
  10543. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10544. var returnedValue = newPromise._resolve(_this._result);
  10545. if (returnedValue !== undefined && returnedValue !== null) {
  10546. if (returnedValue._state !== undefined) {
  10547. var returnedPromise = returnedValue;
  10548. newPromise._children.push(returnedPromise);
  10549. returnedPromise._parent = newPromise;
  10550. newPromise = returnedPromise;
  10551. }
  10552. else {
  10553. newPromise._result = returnedValue;
  10554. }
  10555. }
  10556. }
  10557. else {
  10558. newPromise._reject(_this._reason);
  10559. }
  10560. });
  10561. }
  10562. return newPromise;
  10563. };
  10564. InternalPromise.prototype._moveChildren = function (children) {
  10565. var _this = this;
  10566. var _a;
  10567. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10568. this._children.forEach(function (child) {
  10569. child._parent = _this;
  10570. });
  10571. if (this._state === PromiseStates.Fulfilled) {
  10572. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10573. var child = _b[_i];
  10574. child._resolve(this._result);
  10575. }
  10576. }
  10577. else if (this._state === PromiseStates.Rejected) {
  10578. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10579. var child = _d[_c];
  10580. child._reject(this._reason);
  10581. }
  10582. }
  10583. };
  10584. InternalPromise.prototype._resolve = function (value) {
  10585. try {
  10586. this._state = PromiseStates.Fulfilled;
  10587. var returnedValue = null;
  10588. if (this._onFulfilled) {
  10589. returnedValue = this._onFulfilled(value);
  10590. }
  10591. if (returnedValue !== undefined && returnedValue !== null) {
  10592. if (returnedValue._state !== undefined) {
  10593. // Transmit children
  10594. var returnedPromise = returnedValue;
  10595. returnedPromise._parent = this;
  10596. returnedPromise._moveChildren(this._children);
  10597. value = returnedPromise._result;
  10598. }
  10599. else {
  10600. value = returnedValue;
  10601. }
  10602. }
  10603. this._result = value;
  10604. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10605. var child = _a[_i];
  10606. child._resolve(value);
  10607. }
  10608. this._children.length = 0;
  10609. delete this._onFulfilled;
  10610. delete this._onRejected;
  10611. }
  10612. catch (e) {
  10613. this._reject(e, true);
  10614. }
  10615. };
  10616. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10617. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10618. this._state = PromiseStates.Rejected;
  10619. this._reason = reason;
  10620. if (this._onRejected && !onLocalThrow) {
  10621. try {
  10622. this._onRejected(reason);
  10623. this._rejectWasConsumed = true;
  10624. }
  10625. catch (e) {
  10626. reason = e;
  10627. }
  10628. }
  10629. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10630. var child = _a[_i];
  10631. if (this._rejectWasConsumed) {
  10632. child._resolve(null);
  10633. }
  10634. else {
  10635. child._reject(reason);
  10636. }
  10637. }
  10638. this._children.length = 0;
  10639. delete this._onFulfilled;
  10640. delete this._onRejected;
  10641. };
  10642. InternalPromise.resolve = function (value) {
  10643. var newPromise = new InternalPromise();
  10644. newPromise._resolve(value);
  10645. return newPromise;
  10646. };
  10647. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10648. promise.then(function (value) {
  10649. agregator.results[index] = value;
  10650. agregator.count++;
  10651. if (agregator.count === agregator.target) {
  10652. agregator.rootPromise._resolve(agregator.results);
  10653. }
  10654. return null;
  10655. }, function (reason) {
  10656. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10657. agregator.rootPromise._reject(reason);
  10658. }
  10659. });
  10660. };
  10661. InternalPromise.all = function (promises) {
  10662. var newPromise = new InternalPromise();
  10663. var agregator = new FulFillmentAgregator();
  10664. agregator.target = promises.length;
  10665. agregator.rootPromise = newPromise;
  10666. if (promises.length) {
  10667. for (var index = 0; index < promises.length; index++) {
  10668. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10669. }
  10670. }
  10671. else {
  10672. newPromise._resolve([]);
  10673. }
  10674. return newPromise;
  10675. };
  10676. InternalPromise.race = function (promises) {
  10677. var newPromise = new InternalPromise();
  10678. if (promises.length) {
  10679. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10680. var promise = promises_1[_i];
  10681. promise.then(function (value) {
  10682. if (newPromise) {
  10683. newPromise._resolve(value);
  10684. newPromise = null;
  10685. }
  10686. return null;
  10687. }, function (reason) {
  10688. if (newPromise) {
  10689. newPromise._reject(reason);
  10690. newPromise = null;
  10691. }
  10692. });
  10693. }
  10694. }
  10695. return newPromise;
  10696. };
  10697. return InternalPromise;
  10698. }());
  10699. /**
  10700. * Helper class that provides a small promise polyfill
  10701. */
  10702. var PromisePolyfill = /** @class */ (function () {
  10703. function PromisePolyfill() {
  10704. }
  10705. /**
  10706. * Static function used to check if the polyfill is required
  10707. * If this is the case then the function will inject the polyfill to window.Promise
  10708. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10709. */
  10710. PromisePolyfill.Apply = function (force) {
  10711. if (force === void 0) { force = false; }
  10712. if (force || typeof Promise === 'undefined') {
  10713. var root = window;
  10714. root.Promise = InternalPromise;
  10715. }
  10716. };
  10717. return PromisePolyfill;
  10718. }());
  10719. BABYLON.PromisePolyfill = PromisePolyfill;
  10720. })(BABYLON || (BABYLON = {}));
  10721. //# sourceMappingURL=babylon.promise.js.map
  10722. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10723. var BABYLON;
  10724. (function (BABYLON) {
  10725. /**
  10726. * Helper class to push actions to a pool of workers.
  10727. */
  10728. var WorkerPool = /** @class */ (function () {
  10729. /**
  10730. * Constructor
  10731. * @param workers Array of workers to use for actions
  10732. */
  10733. function WorkerPool(workers) {
  10734. this._pendingActions = new Array();
  10735. this._workerInfos = workers.map(function (worker) { return ({
  10736. worker: worker,
  10737. active: false
  10738. }); });
  10739. }
  10740. /**
  10741. * Terminates all workers and clears any pending actions.
  10742. */
  10743. WorkerPool.prototype.dispose = function () {
  10744. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10745. var workerInfo = _a[_i];
  10746. workerInfo.worker.terminate();
  10747. }
  10748. delete this._workerInfos;
  10749. delete this._pendingActions;
  10750. };
  10751. /**
  10752. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10753. * pended until a worker has completed its action.
  10754. * @param action The action to perform. Call onComplete when the action is complete.
  10755. */
  10756. WorkerPool.prototype.push = function (action) {
  10757. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10758. var workerInfo = _a[_i];
  10759. if (!workerInfo.active) {
  10760. this._execute(workerInfo, action);
  10761. return;
  10762. }
  10763. }
  10764. this._pendingActions.push(action);
  10765. };
  10766. WorkerPool.prototype._execute = function (workerInfo, action) {
  10767. var _this = this;
  10768. workerInfo.active = true;
  10769. action(workerInfo.worker, function () {
  10770. workerInfo.active = false;
  10771. var nextAction = _this._pendingActions.shift();
  10772. if (nextAction) {
  10773. _this._execute(workerInfo, nextAction);
  10774. }
  10775. });
  10776. };
  10777. return WorkerPool;
  10778. }());
  10779. BABYLON.WorkerPool = WorkerPool;
  10780. })(BABYLON || (BABYLON = {}));
  10781. //# sourceMappingURL=babylon.workerPool.js.map
  10782. var BABYLON;
  10783. (function (BABYLON) {
  10784. /**
  10785. * @hidden
  10786. **/
  10787. var _AlphaState = /** @class */ (function () {
  10788. /**
  10789. * Initializes the state.
  10790. */
  10791. function _AlphaState() {
  10792. this._isAlphaBlendDirty = false;
  10793. this._isBlendFunctionParametersDirty = false;
  10794. this._isBlendEquationParametersDirty = false;
  10795. this._isBlendConstantsDirty = false;
  10796. this._alphaBlend = false;
  10797. this._blendFunctionParameters = new Array(4);
  10798. this._blendEquationParameters = new Array(2);
  10799. this._blendConstants = new Array(4);
  10800. this.reset();
  10801. }
  10802. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10803. get: function () {
  10804. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10810. get: function () {
  10811. return this._alphaBlend;
  10812. },
  10813. set: function (value) {
  10814. if (this._alphaBlend === value) {
  10815. return;
  10816. }
  10817. this._alphaBlend = value;
  10818. this._isAlphaBlendDirty = true;
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10824. if (this._blendConstants[0] === r &&
  10825. this._blendConstants[1] === g &&
  10826. this._blendConstants[2] === b &&
  10827. this._blendConstants[3] === a) {
  10828. return;
  10829. }
  10830. this._blendConstants[0] = r;
  10831. this._blendConstants[1] = g;
  10832. this._blendConstants[2] = b;
  10833. this._blendConstants[3] = a;
  10834. this._isBlendConstantsDirty = true;
  10835. };
  10836. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10837. if (this._blendFunctionParameters[0] === value0 &&
  10838. this._blendFunctionParameters[1] === value1 &&
  10839. this._blendFunctionParameters[2] === value2 &&
  10840. this._blendFunctionParameters[3] === value3) {
  10841. return;
  10842. }
  10843. this._blendFunctionParameters[0] = value0;
  10844. this._blendFunctionParameters[1] = value1;
  10845. this._blendFunctionParameters[2] = value2;
  10846. this._blendFunctionParameters[3] = value3;
  10847. this._isBlendFunctionParametersDirty = true;
  10848. };
  10849. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10850. if (this._blendEquationParameters[0] === rgb &&
  10851. this._blendEquationParameters[1] === alpha) {
  10852. return;
  10853. }
  10854. this._blendEquationParameters[0] = rgb;
  10855. this._blendEquationParameters[1] = alpha;
  10856. this._isBlendEquationParametersDirty = true;
  10857. };
  10858. _AlphaState.prototype.reset = function () {
  10859. this._alphaBlend = false;
  10860. this._blendFunctionParameters[0] = null;
  10861. this._blendFunctionParameters[1] = null;
  10862. this._blendFunctionParameters[2] = null;
  10863. this._blendFunctionParameters[3] = null;
  10864. this._blendEquationParameters[0] = null;
  10865. this._blendEquationParameters[1] = null;
  10866. this._blendConstants[0] = null;
  10867. this._blendConstants[1] = null;
  10868. this._blendConstants[2] = null;
  10869. this._blendConstants[3] = null;
  10870. this._isAlphaBlendDirty = true;
  10871. this._isBlendFunctionParametersDirty = false;
  10872. this._isBlendEquationParametersDirty = false;
  10873. this._isBlendConstantsDirty = false;
  10874. };
  10875. _AlphaState.prototype.apply = function (gl) {
  10876. if (!this.isDirty) {
  10877. return;
  10878. }
  10879. // Alpha blend
  10880. if (this._isAlphaBlendDirty) {
  10881. if (this._alphaBlend) {
  10882. gl.enable(gl.BLEND);
  10883. }
  10884. else {
  10885. gl.disable(gl.BLEND);
  10886. }
  10887. this._isAlphaBlendDirty = false;
  10888. }
  10889. // Alpha function
  10890. if (this._isBlendFunctionParametersDirty) {
  10891. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10892. this._isBlendFunctionParametersDirty = false;
  10893. }
  10894. // Alpha equation
  10895. if (this._isBlendEquationParametersDirty) {
  10896. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10897. this._isBlendEquationParametersDirty = false;
  10898. }
  10899. // Constants
  10900. if (this._isBlendConstantsDirty) {
  10901. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10902. this._isBlendConstantsDirty = false;
  10903. }
  10904. };
  10905. return _AlphaState;
  10906. }());
  10907. BABYLON._AlphaState = _AlphaState;
  10908. })(BABYLON || (BABYLON = {}));
  10909. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10910. var BABYLON;
  10911. (function (BABYLON) {
  10912. /**
  10913. * @hidden
  10914. **/
  10915. var _DepthCullingState = /** @class */ (function () {
  10916. /**
  10917. * Initializes the state.
  10918. */
  10919. function _DepthCullingState() {
  10920. this._isDepthTestDirty = false;
  10921. this._isDepthMaskDirty = false;
  10922. this._isDepthFuncDirty = false;
  10923. this._isCullFaceDirty = false;
  10924. this._isCullDirty = false;
  10925. this._isZOffsetDirty = false;
  10926. this._isFrontFaceDirty = false;
  10927. this.reset();
  10928. }
  10929. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10930. get: function () {
  10931. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10932. },
  10933. enumerable: true,
  10934. configurable: true
  10935. });
  10936. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10937. get: function () {
  10938. return this._zOffset;
  10939. },
  10940. set: function (value) {
  10941. if (this._zOffset === value) {
  10942. return;
  10943. }
  10944. this._zOffset = value;
  10945. this._isZOffsetDirty = true;
  10946. },
  10947. enumerable: true,
  10948. configurable: true
  10949. });
  10950. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10951. get: function () {
  10952. return this._cullFace;
  10953. },
  10954. set: function (value) {
  10955. if (this._cullFace === value) {
  10956. return;
  10957. }
  10958. this._cullFace = value;
  10959. this._isCullFaceDirty = true;
  10960. },
  10961. enumerable: true,
  10962. configurable: true
  10963. });
  10964. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10965. get: function () {
  10966. return this._cull;
  10967. },
  10968. set: function (value) {
  10969. if (this._cull === value) {
  10970. return;
  10971. }
  10972. this._cull = value;
  10973. this._isCullDirty = true;
  10974. },
  10975. enumerable: true,
  10976. configurable: true
  10977. });
  10978. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10979. get: function () {
  10980. return this._depthFunc;
  10981. },
  10982. set: function (value) {
  10983. if (this._depthFunc === value) {
  10984. return;
  10985. }
  10986. this._depthFunc = value;
  10987. this._isDepthFuncDirty = true;
  10988. },
  10989. enumerable: true,
  10990. configurable: true
  10991. });
  10992. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10993. get: function () {
  10994. return this._depthMask;
  10995. },
  10996. set: function (value) {
  10997. if (this._depthMask === value) {
  10998. return;
  10999. }
  11000. this._depthMask = value;
  11001. this._isDepthMaskDirty = true;
  11002. },
  11003. enumerable: true,
  11004. configurable: true
  11005. });
  11006. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11007. get: function () {
  11008. return this._depthTest;
  11009. },
  11010. set: function (value) {
  11011. if (this._depthTest === value) {
  11012. return;
  11013. }
  11014. this._depthTest = value;
  11015. this._isDepthTestDirty = true;
  11016. },
  11017. enumerable: true,
  11018. configurable: true
  11019. });
  11020. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11021. get: function () {
  11022. return this._frontFace;
  11023. },
  11024. set: function (value) {
  11025. if (this._frontFace === value) {
  11026. return;
  11027. }
  11028. this._frontFace = value;
  11029. this._isFrontFaceDirty = true;
  11030. },
  11031. enumerable: true,
  11032. configurable: true
  11033. });
  11034. _DepthCullingState.prototype.reset = function () {
  11035. this._depthMask = true;
  11036. this._depthTest = true;
  11037. this._depthFunc = null;
  11038. this._cullFace = null;
  11039. this._cull = null;
  11040. this._zOffset = 0;
  11041. this._frontFace = null;
  11042. this._isDepthTestDirty = true;
  11043. this._isDepthMaskDirty = true;
  11044. this._isDepthFuncDirty = false;
  11045. this._isCullFaceDirty = false;
  11046. this._isCullDirty = false;
  11047. this._isZOffsetDirty = false;
  11048. this._isFrontFaceDirty = false;
  11049. };
  11050. _DepthCullingState.prototype.apply = function (gl) {
  11051. if (!this.isDirty) {
  11052. return;
  11053. }
  11054. // Cull
  11055. if (this._isCullDirty) {
  11056. if (this.cull) {
  11057. gl.enable(gl.CULL_FACE);
  11058. }
  11059. else {
  11060. gl.disable(gl.CULL_FACE);
  11061. }
  11062. this._isCullDirty = false;
  11063. }
  11064. // Cull face
  11065. if (this._isCullFaceDirty) {
  11066. gl.cullFace(this.cullFace);
  11067. this._isCullFaceDirty = false;
  11068. }
  11069. // Depth mask
  11070. if (this._isDepthMaskDirty) {
  11071. gl.depthMask(this.depthMask);
  11072. this._isDepthMaskDirty = false;
  11073. }
  11074. // Depth test
  11075. if (this._isDepthTestDirty) {
  11076. if (this.depthTest) {
  11077. gl.enable(gl.DEPTH_TEST);
  11078. }
  11079. else {
  11080. gl.disable(gl.DEPTH_TEST);
  11081. }
  11082. this._isDepthTestDirty = false;
  11083. }
  11084. // Depth func
  11085. if (this._isDepthFuncDirty) {
  11086. gl.depthFunc(this.depthFunc);
  11087. this._isDepthFuncDirty = false;
  11088. }
  11089. // zOffset
  11090. if (this._isZOffsetDirty) {
  11091. if (this.zOffset) {
  11092. gl.enable(gl.POLYGON_OFFSET_FILL);
  11093. gl.polygonOffset(this.zOffset, 0);
  11094. }
  11095. else {
  11096. gl.disable(gl.POLYGON_OFFSET_FILL);
  11097. }
  11098. this._isZOffsetDirty = false;
  11099. }
  11100. // Front face
  11101. if (this._isFrontFaceDirty) {
  11102. gl.frontFace(this.frontFace);
  11103. this._isFrontFaceDirty = false;
  11104. }
  11105. };
  11106. return _DepthCullingState;
  11107. }());
  11108. BABYLON._DepthCullingState = _DepthCullingState;
  11109. })(BABYLON || (BABYLON = {}));
  11110. //# sourceMappingURL=babylon.depthCullingState.js.map
  11111. var BABYLON;
  11112. (function (BABYLON) {
  11113. /**
  11114. * @hidden
  11115. **/
  11116. var _StencilState = /** @class */ (function () {
  11117. function _StencilState() {
  11118. this._isStencilTestDirty = false;
  11119. this._isStencilMaskDirty = false;
  11120. this._isStencilFuncDirty = false;
  11121. this._isStencilOpDirty = false;
  11122. this.reset();
  11123. }
  11124. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11125. get: function () {
  11126. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11127. },
  11128. enumerable: true,
  11129. configurable: true
  11130. });
  11131. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11132. get: function () {
  11133. return this._stencilFunc;
  11134. },
  11135. set: function (value) {
  11136. if (this._stencilFunc === value) {
  11137. return;
  11138. }
  11139. this._stencilFunc = value;
  11140. this._isStencilFuncDirty = true;
  11141. },
  11142. enumerable: true,
  11143. configurable: true
  11144. });
  11145. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11146. get: function () {
  11147. return this._stencilFuncRef;
  11148. },
  11149. set: function (value) {
  11150. if (this._stencilFuncRef === value) {
  11151. return;
  11152. }
  11153. this._stencilFuncRef = value;
  11154. this._isStencilFuncDirty = true;
  11155. },
  11156. enumerable: true,
  11157. configurable: true
  11158. });
  11159. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11160. get: function () {
  11161. return this._stencilFuncMask;
  11162. },
  11163. set: function (value) {
  11164. if (this._stencilFuncMask === value) {
  11165. return;
  11166. }
  11167. this._stencilFuncMask = value;
  11168. this._isStencilFuncDirty = true;
  11169. },
  11170. enumerable: true,
  11171. configurable: true
  11172. });
  11173. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11174. get: function () {
  11175. return this._stencilOpStencilFail;
  11176. },
  11177. set: function (value) {
  11178. if (this._stencilOpStencilFail === value) {
  11179. return;
  11180. }
  11181. this._stencilOpStencilFail = value;
  11182. this._isStencilOpDirty = true;
  11183. },
  11184. enumerable: true,
  11185. configurable: true
  11186. });
  11187. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11188. get: function () {
  11189. return this._stencilOpDepthFail;
  11190. },
  11191. set: function (value) {
  11192. if (this._stencilOpDepthFail === value) {
  11193. return;
  11194. }
  11195. this._stencilOpDepthFail = value;
  11196. this._isStencilOpDirty = true;
  11197. },
  11198. enumerable: true,
  11199. configurable: true
  11200. });
  11201. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11202. get: function () {
  11203. return this._stencilOpStencilDepthPass;
  11204. },
  11205. set: function (value) {
  11206. if (this._stencilOpStencilDepthPass === value) {
  11207. return;
  11208. }
  11209. this._stencilOpStencilDepthPass = value;
  11210. this._isStencilOpDirty = true;
  11211. },
  11212. enumerable: true,
  11213. configurable: true
  11214. });
  11215. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11216. get: function () {
  11217. return this._stencilMask;
  11218. },
  11219. set: function (value) {
  11220. if (this._stencilMask === value) {
  11221. return;
  11222. }
  11223. this._stencilMask = value;
  11224. this._isStencilMaskDirty = true;
  11225. },
  11226. enumerable: true,
  11227. configurable: true
  11228. });
  11229. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11230. get: function () {
  11231. return this._stencilTest;
  11232. },
  11233. set: function (value) {
  11234. if (this._stencilTest === value) {
  11235. return;
  11236. }
  11237. this._stencilTest = value;
  11238. this._isStencilTestDirty = true;
  11239. },
  11240. enumerable: true,
  11241. configurable: true
  11242. });
  11243. _StencilState.prototype.reset = function () {
  11244. this._stencilTest = false;
  11245. this._stencilMask = 0xFF;
  11246. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11247. this._stencilFuncRef = 1;
  11248. this._stencilFuncMask = 0xFF;
  11249. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11250. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11251. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11252. this._isStencilTestDirty = true;
  11253. this._isStencilMaskDirty = true;
  11254. this._isStencilFuncDirty = true;
  11255. this._isStencilOpDirty = true;
  11256. };
  11257. _StencilState.prototype.apply = function (gl) {
  11258. if (!this.isDirty) {
  11259. return;
  11260. }
  11261. // Stencil test
  11262. if (this._isStencilTestDirty) {
  11263. if (this.stencilTest) {
  11264. gl.enable(gl.STENCIL_TEST);
  11265. }
  11266. else {
  11267. gl.disable(gl.STENCIL_TEST);
  11268. }
  11269. this._isStencilTestDirty = false;
  11270. }
  11271. // Stencil mask
  11272. if (this._isStencilMaskDirty) {
  11273. gl.stencilMask(this.stencilMask);
  11274. this._isStencilMaskDirty = false;
  11275. }
  11276. // Stencil func
  11277. if (this._isStencilFuncDirty) {
  11278. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11279. this._isStencilFuncDirty = false;
  11280. }
  11281. // Stencil op
  11282. if (this._isStencilOpDirty) {
  11283. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11284. this._isStencilOpDirty = false;
  11285. }
  11286. };
  11287. return _StencilState;
  11288. }());
  11289. BABYLON._StencilState = _StencilState;
  11290. })(BABYLON || (BABYLON = {}));
  11291. //# sourceMappingURL=babylon.stencilState.js.map
  11292. var __assign = (this && this.__assign) || function () {
  11293. __assign = Object.assign || function(t) {
  11294. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11295. s = arguments[i];
  11296. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11297. t[p] = s[p];
  11298. }
  11299. return t;
  11300. };
  11301. return __assign.apply(this, arguments);
  11302. };
  11303. var BABYLON;
  11304. (function (BABYLON) {
  11305. /**
  11306. * Keeps track of all the buffer info used in engine.
  11307. */
  11308. var BufferPointer = /** @class */ (function () {
  11309. function BufferPointer() {
  11310. }
  11311. return BufferPointer;
  11312. }());
  11313. /**
  11314. * Interface for attribute information associated with buffer instanciation
  11315. */
  11316. var InstancingAttributeInfo = /** @class */ (function () {
  11317. function InstancingAttributeInfo() {
  11318. }
  11319. return InstancingAttributeInfo;
  11320. }());
  11321. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11322. /**
  11323. * Define options used to create a render target texture
  11324. */
  11325. var RenderTargetCreationOptions = /** @class */ (function () {
  11326. function RenderTargetCreationOptions() {
  11327. }
  11328. return RenderTargetCreationOptions;
  11329. }());
  11330. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11331. /**
  11332. * Define options used to create a depth texture
  11333. */
  11334. var DepthTextureCreationOptions = /** @class */ (function () {
  11335. function DepthTextureCreationOptions() {
  11336. }
  11337. return DepthTextureCreationOptions;
  11338. }());
  11339. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11340. /**
  11341. * Class used to describe the capabilities of the engine relatively to the current browser
  11342. */
  11343. var EngineCapabilities = /** @class */ (function () {
  11344. function EngineCapabilities() {
  11345. }
  11346. return EngineCapabilities;
  11347. }());
  11348. BABYLON.EngineCapabilities = EngineCapabilities;
  11349. /**
  11350. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11351. */
  11352. var Engine = /** @class */ (function () {
  11353. /**
  11354. * Creates a new engine
  11355. * @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
  11356. * @param antialias defines enable antialiasing (default: false)
  11357. * @param options defines further options to be sent to the getContext() function
  11358. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11359. */
  11360. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11361. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11362. var _this = this;
  11363. // Public members
  11364. /**
  11365. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11366. */
  11367. this.forcePOTTextures = false;
  11368. /**
  11369. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11370. */
  11371. this.isFullscreen = false;
  11372. /**
  11373. * Gets a boolean indicating if the pointer is currently locked
  11374. */
  11375. this.isPointerLock = false;
  11376. /**
  11377. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11378. */
  11379. this.cullBackFaces = true;
  11380. /**
  11381. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11382. */
  11383. this.renderEvenInBackground = true;
  11384. /**
  11385. * Gets or sets a boolean indicating that cache can be kept between frames
  11386. */
  11387. this.preventCacheWipeBetweenFrames = false;
  11388. /**
  11389. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11390. **/
  11391. this.enableOfflineSupport = false;
  11392. /**
  11393. * 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)
  11394. **/
  11395. this.disableManifestCheck = false;
  11396. /**
  11397. * Gets the list of created scenes
  11398. */
  11399. this.scenes = new Array();
  11400. /**
  11401. * Gets the list of created postprocesses
  11402. */
  11403. this.postProcesses = new Array();
  11404. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11405. this.validateShaderPrograms = false;
  11406. // Observables
  11407. /**
  11408. * Observable event triggered each time the rendering canvas is resized
  11409. */
  11410. this.onResizeObservable = new BABYLON.Observable();
  11411. /**
  11412. * Observable event triggered each time the canvas loses focus
  11413. */
  11414. this.onCanvasBlurObservable = new BABYLON.Observable();
  11415. /**
  11416. * Observable event triggered each time the canvas gains focus
  11417. */
  11418. this.onCanvasFocusObservable = new BABYLON.Observable();
  11419. /**
  11420. * Observable event triggered each time the canvas receives pointerout event
  11421. */
  11422. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11423. /**
  11424. * Observable event triggered before each texture is initialized
  11425. */
  11426. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11427. //WebVR
  11428. this._vrDisplay = undefined;
  11429. this._vrSupported = false;
  11430. this._vrExclusivePointerMode = false;
  11431. // Uniform buffers list
  11432. /**
  11433. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11434. */
  11435. this.disableUniformBuffers = false;
  11436. /** @hidden */
  11437. this._uniformBuffers = new Array();
  11438. // Observables
  11439. /**
  11440. * Observable raised when the engine begins a new frame
  11441. */
  11442. this.onBeginFrameObservable = new BABYLON.Observable();
  11443. /**
  11444. * Observable raised when the engine ends the current frame
  11445. */
  11446. this.onEndFrameObservable = new BABYLON.Observable();
  11447. /**
  11448. * Observable raised when the engine is about to compile a shader
  11449. */
  11450. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11451. /**
  11452. * Observable raised when the engine has jsut compiled a shader
  11453. */
  11454. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11455. this._windowIsBackground = false;
  11456. this._webGLVersion = 1.0;
  11457. /** @hidden */
  11458. this._badOS = false;
  11459. /** @hidden */
  11460. this._badDesktopOS = false;
  11461. /**
  11462. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11463. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11464. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11465. */
  11466. this.disableTextureBindingOptimization = false;
  11467. /**
  11468. * Observable signaled when VR display mode changes
  11469. */
  11470. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11471. /**
  11472. * Observable signaled when VR request present is complete
  11473. */
  11474. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11475. /**
  11476. * Observable signaled when VR request present starts
  11477. */
  11478. this.onVRRequestPresentStart = new BABYLON.Observable();
  11479. this._colorWrite = true;
  11480. /** @hidden */
  11481. this._drawCalls = new BABYLON.PerfCounter();
  11482. /** @hidden */
  11483. this._textureCollisions = new BABYLON.PerfCounter();
  11484. this._renderingQueueLaunched = false;
  11485. this._activeRenderLoops = new Array();
  11486. // Deterministic lockstepMaxSteps
  11487. this._deterministicLockstep = false;
  11488. this._lockstepMaxSteps = 4;
  11489. // Lost context
  11490. /**
  11491. * Observable signaled when a context lost event is raised
  11492. */
  11493. this.onContextLostObservable = new BABYLON.Observable();
  11494. /**
  11495. * Observable signaled when a context restored event is raised
  11496. */
  11497. this.onContextRestoredObservable = new BABYLON.Observable();
  11498. this._contextWasLost = false;
  11499. this._doNotHandleContextLost = false;
  11500. // FPS
  11501. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11502. this._fps = 60;
  11503. this._deltaTime = 0;
  11504. /**
  11505. * Turn this value on if you want to pause FPS computation when in background
  11506. */
  11507. this.disablePerformanceMonitorInBackground = false;
  11508. // States
  11509. /** @hidden */
  11510. this._depthCullingState = new BABYLON._DepthCullingState();
  11511. /** @hidden */
  11512. this._stencilState = new BABYLON._StencilState();
  11513. /** @hidden */
  11514. this._alphaState = new BABYLON._AlphaState();
  11515. /** @hidden */
  11516. this._alphaMode = Engine.ALPHA_DISABLE;
  11517. // Cache
  11518. this._internalTexturesCache = new Array();
  11519. /** @hidden */
  11520. this._activeChannel = 0;
  11521. this._currentTextureChannel = -1;
  11522. /** @hidden */
  11523. this._boundTexturesCache = {};
  11524. this._compiledEffects = {};
  11525. this._vertexAttribArraysEnabled = [];
  11526. this._uintIndicesCurrentlySet = false;
  11527. this._currentBoundBuffer = new Array();
  11528. /** @hidden */
  11529. this._currentFramebuffer = null;
  11530. this._currentBufferPointers = new Array();
  11531. this._currentInstanceLocations = new Array();
  11532. this._currentInstanceBuffers = new Array();
  11533. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11534. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11535. this._vaoRecordInProgress = false;
  11536. this._mustWipeVertexAttributes = false;
  11537. this._nextFreeTextureSlots = new Array();
  11538. this._maxSimultaneousTextures = 0;
  11539. this._activeRequests = new Array();
  11540. // Hardware supported Compressed Textures
  11541. this._texturesSupported = new Array();
  11542. /**
  11543. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11544. */
  11545. this.premultipliedAlpha = true;
  11546. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11547. this._onVRFullScreenTriggered = function () {
  11548. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11549. //get the old size before we change
  11550. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11551. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11552. //get the width and height, change the render size
  11553. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11554. _this.setHardwareScalingLevel(1);
  11555. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11556. }
  11557. else {
  11558. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11559. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11560. }
  11561. };
  11562. this._unpackFlipYCached = null;
  11563. /**
  11564. * In case you are sharing the context with other applications, it might
  11565. * be interested to not cache the unpack flip y state to ensure a consistent
  11566. * value would be set.
  11567. */
  11568. this.enableUnpackFlipYCached = true;
  11569. this._boundUniforms = {};
  11570. // Register promises
  11571. BABYLON.PromisePolyfill.Apply();
  11572. var canvas = null;
  11573. Engine.Instances.push(this);
  11574. if (!canvasOrContext) {
  11575. return;
  11576. }
  11577. options = options || {};
  11578. if (canvasOrContext.getContext) {
  11579. canvas = canvasOrContext;
  11580. this._renderingCanvas = canvas;
  11581. if (antialias != null) {
  11582. options.antialias = antialias;
  11583. }
  11584. if (options.deterministicLockstep === undefined) {
  11585. options.deterministicLockstep = false;
  11586. }
  11587. if (options.lockstepMaxSteps === undefined) {
  11588. options.lockstepMaxSteps = 4;
  11589. }
  11590. if (options.preserveDrawingBuffer === undefined) {
  11591. options.preserveDrawingBuffer = false;
  11592. }
  11593. if (options.audioEngine === undefined) {
  11594. options.audioEngine = true;
  11595. }
  11596. if (options.stencil === undefined) {
  11597. options.stencil = true;
  11598. }
  11599. if (options.premultipliedAlpha === false) {
  11600. this.premultipliedAlpha = false;
  11601. }
  11602. this._deterministicLockstep = options.deterministicLockstep;
  11603. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11604. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11605. // Exceptions
  11606. if (navigator && navigator.userAgent) {
  11607. var ua = navigator.userAgent;
  11608. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11609. var exception = _a[_i];
  11610. var key = exception.key;
  11611. var targets = exception.targets;
  11612. if (ua.indexOf(key) > -1) {
  11613. if (exception.capture && exception.captureConstraint) {
  11614. var capture = exception.capture;
  11615. var constraint = exception.captureConstraint;
  11616. var regex = new RegExp(capture);
  11617. var matches = regex.exec(ua);
  11618. if (matches && matches.length > 0) {
  11619. var capturedValue = parseInt(matches[matches.length - 1]);
  11620. if (capturedValue >= constraint) {
  11621. continue;
  11622. }
  11623. }
  11624. }
  11625. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11626. var target = targets_1[_b];
  11627. switch (target) {
  11628. case "uniformBuffer":
  11629. this.disableUniformBuffers = true;
  11630. break;
  11631. case "textureBindingOptimization":
  11632. this.disableTextureBindingOptimization = true;
  11633. break;
  11634. }
  11635. }
  11636. }
  11637. }
  11638. }
  11639. // GL
  11640. if (!options.disableWebGL2Support) {
  11641. try {
  11642. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11643. if (this._gl) {
  11644. this._webGLVersion = 2.0;
  11645. }
  11646. }
  11647. catch (e) {
  11648. // Do nothing
  11649. }
  11650. }
  11651. if (!this._gl) {
  11652. if (!canvas) {
  11653. throw new Error("The provided canvas is null or undefined.");
  11654. }
  11655. try {
  11656. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11657. }
  11658. catch (e) {
  11659. throw new Error("WebGL not supported");
  11660. }
  11661. }
  11662. if (!this._gl) {
  11663. throw new Error("WebGL not supported");
  11664. }
  11665. this._onCanvasFocus = function () {
  11666. _this.onCanvasFocusObservable.notifyObservers(_this);
  11667. };
  11668. this._onCanvasBlur = function () {
  11669. _this.onCanvasBlurObservable.notifyObservers(_this);
  11670. };
  11671. canvas.addEventListener("focus", this._onCanvasFocus);
  11672. canvas.addEventListener("blur", this._onCanvasBlur);
  11673. this._onBlur = function () {
  11674. if (_this.disablePerformanceMonitorInBackground) {
  11675. _this._performanceMonitor.disable();
  11676. }
  11677. _this._windowIsBackground = true;
  11678. };
  11679. this._onFocus = function () {
  11680. if (_this.disablePerformanceMonitorInBackground) {
  11681. _this._performanceMonitor.enable();
  11682. }
  11683. _this._windowIsBackground = false;
  11684. };
  11685. this._onCanvasPointerOut = function (ev) {
  11686. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11687. };
  11688. window.addEventListener("blur", this._onBlur);
  11689. window.addEventListener("focus", this._onFocus);
  11690. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11691. // Context lost
  11692. if (!this._doNotHandleContextLost) {
  11693. this._onContextLost = function (evt) {
  11694. evt.preventDefault();
  11695. _this._contextWasLost = true;
  11696. BABYLON.Tools.Warn("WebGL context lost.");
  11697. _this.onContextLostObservable.notifyObservers(_this);
  11698. };
  11699. this._onContextRestored = function (evt) {
  11700. // Adding a timeout to avoid race condition at browser level
  11701. setTimeout(function () {
  11702. // Rebuild gl context
  11703. _this._initGLContext();
  11704. // Rebuild effects
  11705. _this._rebuildEffects();
  11706. // Rebuild textures
  11707. _this._rebuildInternalTextures();
  11708. // Rebuild buffers
  11709. _this._rebuildBuffers();
  11710. // Cache
  11711. _this.wipeCaches(true);
  11712. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11713. _this.onContextRestoredObservable.notifyObservers(_this);
  11714. _this._contextWasLost = false;
  11715. }, 0);
  11716. };
  11717. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11718. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11719. }
  11720. }
  11721. else {
  11722. this._gl = canvasOrContext;
  11723. this._renderingCanvas = this._gl.canvas;
  11724. if (this._gl.renderbufferStorageMultisample) {
  11725. this._webGLVersion = 2.0;
  11726. }
  11727. options.stencil = this._gl.getContextAttributes().stencil;
  11728. }
  11729. // Viewport
  11730. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11731. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11732. this.resize();
  11733. this._isStencilEnable = options.stencil ? true : false;
  11734. this._initGLContext();
  11735. if (canvas) {
  11736. // Fullscreen
  11737. this._onFullscreenChange = function () {
  11738. if (document.fullscreen !== undefined) {
  11739. _this.isFullscreen = document.fullscreen;
  11740. }
  11741. else if (document.mozFullScreen !== undefined) {
  11742. _this.isFullscreen = document.mozFullScreen;
  11743. }
  11744. else if (document.webkitIsFullScreen !== undefined) {
  11745. _this.isFullscreen = document.webkitIsFullScreen;
  11746. }
  11747. else if (document.msIsFullScreen !== undefined) {
  11748. _this.isFullscreen = document.msIsFullScreen;
  11749. }
  11750. // Pointer lock
  11751. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11752. canvas.requestPointerLock = canvas.requestPointerLock ||
  11753. canvas.msRequestPointerLock ||
  11754. canvas.mozRequestPointerLock ||
  11755. canvas.webkitRequestPointerLock;
  11756. if (canvas.requestPointerLock) {
  11757. canvas.requestPointerLock();
  11758. }
  11759. }
  11760. };
  11761. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11762. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11763. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11764. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11765. // Pointer lock
  11766. this._onPointerLockChange = function () {
  11767. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11768. document.webkitPointerLockElement === canvas ||
  11769. document.msPointerLockElement === canvas ||
  11770. document.pointerLockElement === canvas);
  11771. };
  11772. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11773. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11774. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11775. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11776. this._onVRDisplayPointerRestricted = function () {
  11777. if (canvas) {
  11778. canvas.requestPointerLock();
  11779. }
  11780. };
  11781. this._onVRDisplayPointerUnrestricted = function () {
  11782. document.exitPointerLock();
  11783. };
  11784. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11785. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11786. }
  11787. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11788. Engine.audioEngine = new BABYLON.AudioEngine();
  11789. }
  11790. // Prepare buffer pointers
  11791. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11792. this._currentBufferPointers[i] = new BufferPointer();
  11793. }
  11794. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11795. // Load WebVR Devices
  11796. if (options.autoEnableWebVR) {
  11797. this.initWebVR();
  11798. }
  11799. // Detect if we are running on a faulty buggy OS.
  11800. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11801. // Detect if we are running on a faulty buggy desktop OS.
  11802. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11803. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11804. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11805. }
  11806. Object.defineProperty(Engine, "LastCreatedEngine", {
  11807. /**
  11808. * Gets the latest created engine
  11809. */
  11810. get: function () {
  11811. if (Engine.Instances.length === 0) {
  11812. return null;
  11813. }
  11814. return Engine.Instances[Engine.Instances.length - 1];
  11815. },
  11816. enumerable: true,
  11817. configurable: true
  11818. });
  11819. Object.defineProperty(Engine, "LastCreatedScene", {
  11820. /**
  11821. * Gets the latest created scene
  11822. */
  11823. get: function () {
  11824. var lastCreatedEngine = Engine.LastCreatedEngine;
  11825. if (!lastCreatedEngine) {
  11826. return null;
  11827. }
  11828. if (lastCreatedEngine.scenes.length === 0) {
  11829. return null;
  11830. }
  11831. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11832. },
  11833. enumerable: true,
  11834. configurable: true
  11835. });
  11836. /**
  11837. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11838. * @param flag defines which part of the materials must be marked as dirty
  11839. * @param predicate defines a predicate used to filter which materials should be affected
  11840. */
  11841. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11842. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11843. var engine = Engine.Instances[engineIndex];
  11844. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11845. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11846. }
  11847. }
  11848. };
  11849. Object.defineProperty(Engine, "Version", {
  11850. /**
  11851. * Returns the current version of the framework
  11852. */
  11853. get: function () {
  11854. return "3.3.0-beta.5";
  11855. },
  11856. enumerable: true,
  11857. configurable: true
  11858. });
  11859. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11860. /**
  11861. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11862. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11863. */
  11864. get: function () {
  11865. return this._vrExclusivePointerMode;
  11866. },
  11867. enumerable: true,
  11868. configurable: true
  11869. });
  11870. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11871. /**
  11872. * Gets a boolean indicating that the engine supports uniform buffers
  11873. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11874. */
  11875. get: function () {
  11876. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11877. },
  11878. enumerable: true,
  11879. configurable: true
  11880. });
  11881. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11882. /**
  11883. * Gets a boolean indicating that only power of 2 textures are supported
  11884. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11885. */
  11886. get: function () {
  11887. return this._webGLVersion < 2 || this.forcePOTTextures;
  11888. },
  11889. enumerable: true,
  11890. configurable: true
  11891. });
  11892. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11893. /**
  11894. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11895. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11896. */
  11897. get: function () {
  11898. return this._doNotHandleContextLost;
  11899. },
  11900. set: function (value) {
  11901. this._doNotHandleContextLost = value;
  11902. },
  11903. enumerable: true,
  11904. configurable: true
  11905. });
  11906. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11907. /**
  11908. * Gets the performance monitor attached to this engine
  11909. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11910. */
  11911. get: function () {
  11912. return this._performanceMonitor;
  11913. },
  11914. enumerable: true,
  11915. configurable: true
  11916. });
  11917. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11918. /**
  11919. * Gets the list of texture formats supported
  11920. */
  11921. get: function () {
  11922. return this._texturesSupported;
  11923. },
  11924. enumerable: true,
  11925. configurable: true
  11926. });
  11927. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11928. /**
  11929. * Gets the list of texture formats in use
  11930. */
  11931. get: function () {
  11932. return this._textureFormatInUse;
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. Object.defineProperty(Engine.prototype, "currentViewport", {
  11938. /**
  11939. * Gets the current viewport
  11940. */
  11941. get: function () {
  11942. return this._cachedViewport;
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11948. /**
  11949. * Gets the default empty texture
  11950. */
  11951. get: function () {
  11952. if (!this._emptyTexture) {
  11953. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11954. }
  11955. return this._emptyTexture;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11961. /**
  11962. * Gets the default empty 3D texture
  11963. */
  11964. get: function () {
  11965. if (!this._emptyTexture3D) {
  11966. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11967. }
  11968. return this._emptyTexture3D;
  11969. },
  11970. enumerable: true,
  11971. configurable: true
  11972. });
  11973. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11974. /**
  11975. * Gets the default empty cube texture
  11976. */
  11977. get: function () {
  11978. if (!this._emptyCubeTexture) {
  11979. var faceData = new Uint8Array(4);
  11980. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11981. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11982. }
  11983. return this._emptyCubeTexture;
  11984. },
  11985. enumerable: true,
  11986. configurable: true
  11987. });
  11988. Engine.prototype._rebuildInternalTextures = function () {
  11989. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11990. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11991. var internalTexture = currentState_1[_i];
  11992. internalTexture._rebuild();
  11993. }
  11994. };
  11995. Engine.prototype._rebuildEffects = function () {
  11996. for (var key in this._compiledEffects) {
  11997. var effect = this._compiledEffects[key];
  11998. effect._prepareEffect();
  11999. }
  12000. BABYLON.Effect.ResetCache();
  12001. };
  12002. Engine.prototype._rebuildBuffers = function () {
  12003. // Index / Vertex
  12004. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12005. var scene = _a[_i];
  12006. scene.resetCachedMaterial();
  12007. scene._rebuildGeometries();
  12008. scene._rebuildTextures();
  12009. }
  12010. // Uniforms
  12011. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12012. var uniformBuffer = _c[_b];
  12013. uniformBuffer._rebuild();
  12014. }
  12015. };
  12016. Engine.prototype._initGLContext = function () {
  12017. // Caps
  12018. this._caps = new EngineCapabilities();
  12019. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12020. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12021. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12022. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12023. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12024. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12025. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12026. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12027. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12028. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12029. // Infos
  12030. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12031. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12032. if (rendererInfo != null) {
  12033. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12034. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12035. }
  12036. if (!this._glVendor) {
  12037. this._glVendor = "Unknown vendor";
  12038. }
  12039. if (!this._glRenderer) {
  12040. this._glRenderer = "Unknown renderer";
  12041. }
  12042. // Constants
  12043. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12044. if (this._gl.RGBA16F !== 0x881A) {
  12045. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12046. }
  12047. if (this._gl.RGBA32F !== 0x8814) {
  12048. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12049. }
  12050. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12051. this._gl.DEPTH24_STENCIL8 = 35056;
  12052. }
  12053. // Extensions
  12054. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12055. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12056. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12057. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12058. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12059. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12060. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12061. 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');
  12062. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12063. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12064. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12065. this._caps.highPrecisionShaderSupported = true;
  12066. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12067. if (this._caps.timerQuery) {
  12068. if (this._webGLVersion === 1) {
  12069. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12070. }
  12071. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12072. }
  12073. // Checks if some of the format renders first to allow the use of webgl inspector.
  12074. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12075. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12076. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12077. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12078. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12079. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12080. if (this._webGLVersion > 1) {
  12081. this._gl.HALF_FLOAT_OES = 0x140B;
  12082. }
  12083. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12084. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12085. // Draw buffers
  12086. if (this._webGLVersion > 1) {
  12087. this._caps.drawBuffersExtension = true;
  12088. }
  12089. else {
  12090. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12091. if (drawBuffersExtension !== null) {
  12092. this._caps.drawBuffersExtension = true;
  12093. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12094. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12095. for (var i = 0; i < 16; i++) {
  12096. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12097. }
  12098. }
  12099. else {
  12100. this._caps.drawBuffersExtension = false;
  12101. }
  12102. }
  12103. // Depth Texture
  12104. if (this._webGLVersion > 1) {
  12105. this._caps.depthTextureExtension = true;
  12106. }
  12107. else {
  12108. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12109. if (depthTextureExtension != null) {
  12110. this._caps.depthTextureExtension = true;
  12111. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12112. }
  12113. }
  12114. // Vertex array object
  12115. if (this._webGLVersion > 1) {
  12116. this._caps.vertexArrayObject = true;
  12117. }
  12118. else {
  12119. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12120. if (vertexArrayObjectExtension != null) {
  12121. this._caps.vertexArrayObject = true;
  12122. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12123. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12124. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12125. }
  12126. else {
  12127. this._caps.vertexArrayObject = false;
  12128. }
  12129. }
  12130. // Instances count
  12131. if (this._webGLVersion > 1) {
  12132. this._caps.instancedArrays = true;
  12133. }
  12134. else {
  12135. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12136. if (instanceExtension != null) {
  12137. this._caps.instancedArrays = true;
  12138. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12139. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12140. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12141. }
  12142. else {
  12143. this._caps.instancedArrays = false;
  12144. }
  12145. }
  12146. // Intelligently add supported compressed formats in order to check for.
  12147. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12148. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12149. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12150. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12151. if (this._caps.astc)
  12152. this.texturesSupported.push('-astc.ktx');
  12153. if (this._caps.s3tc)
  12154. this.texturesSupported.push('-dxt.ktx');
  12155. if (this._caps.pvrtc)
  12156. this.texturesSupported.push('-pvrtc.ktx');
  12157. if (this._caps.etc2)
  12158. this.texturesSupported.push('-etc2.ktx');
  12159. if (this._caps.etc1)
  12160. this.texturesSupported.push('-etc1.ktx');
  12161. if (this._gl.getShaderPrecisionFormat) {
  12162. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12163. if (highp) {
  12164. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12165. }
  12166. }
  12167. // Depth buffer
  12168. this.setDepthBuffer(true);
  12169. this.setDepthFunctionToLessOrEqual();
  12170. this.setDepthWrite(true);
  12171. // Texture maps
  12172. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12173. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12174. this._nextFreeTextureSlots.push(slot);
  12175. }
  12176. };
  12177. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12178. /**
  12179. * Gets version of the current webGL context
  12180. */
  12181. get: function () {
  12182. return this._webGLVersion;
  12183. },
  12184. enumerable: true,
  12185. configurable: true
  12186. });
  12187. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12188. /**
  12189. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12190. */
  12191. get: function () {
  12192. return this._isStencilEnable;
  12193. },
  12194. enumerable: true,
  12195. configurable: true
  12196. });
  12197. Engine.prototype._prepareWorkingCanvas = function () {
  12198. if (this._workingCanvas) {
  12199. return;
  12200. }
  12201. this._workingCanvas = document.createElement("canvas");
  12202. var context = this._workingCanvas.getContext("2d");
  12203. if (context) {
  12204. this._workingContext = context;
  12205. }
  12206. };
  12207. /**
  12208. * Reset the texture cache to empty state
  12209. */
  12210. Engine.prototype.resetTextureCache = function () {
  12211. for (var key in this._boundTexturesCache) {
  12212. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12213. continue;
  12214. }
  12215. var boundTexture = this._boundTexturesCache[key];
  12216. if (boundTexture) {
  12217. this._removeDesignatedSlot(boundTexture);
  12218. }
  12219. this._boundTexturesCache[key] = null;
  12220. }
  12221. if (!this.disableTextureBindingOptimization) {
  12222. this._nextFreeTextureSlots = [];
  12223. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12224. this._nextFreeTextureSlots.push(slot);
  12225. }
  12226. }
  12227. this._currentTextureChannel = -1;
  12228. };
  12229. /**
  12230. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12231. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12232. * @returns true if engine is in deterministic lock step mode
  12233. */
  12234. Engine.prototype.isDeterministicLockStep = function () {
  12235. return this._deterministicLockstep;
  12236. };
  12237. /**
  12238. * Gets the max steps when engine is running in deterministic lock step
  12239. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12240. * @returns the max steps
  12241. */
  12242. Engine.prototype.getLockstepMaxSteps = function () {
  12243. return this._lockstepMaxSteps;
  12244. };
  12245. /**
  12246. * Gets an object containing information about the current webGL context
  12247. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12248. */
  12249. Engine.prototype.getGlInfo = function () {
  12250. return {
  12251. vendor: this._glVendor,
  12252. renderer: this._glRenderer,
  12253. version: this._glVersion
  12254. };
  12255. };
  12256. /**
  12257. * Gets current aspect ratio
  12258. * @param camera defines the camera to use to get the aspect ratio
  12259. * @param useScreen defines if screen size must be used (or the current render target if any)
  12260. * @returns a number defining the aspect ratio
  12261. */
  12262. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12263. if (useScreen === void 0) { useScreen = false; }
  12264. var viewport = camera.viewport;
  12265. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12266. };
  12267. /**
  12268. * Gets current screen aspect ratio
  12269. * @returns a number defining the aspect ratio
  12270. */
  12271. Engine.prototype.getScreenAspectRatio = function () {
  12272. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12273. };
  12274. /**
  12275. * Gets the current render width
  12276. * @param useScreen defines if screen size must be used (or the current render target if any)
  12277. * @returns a number defining the current render width
  12278. */
  12279. Engine.prototype.getRenderWidth = function (useScreen) {
  12280. if (useScreen === void 0) { useScreen = false; }
  12281. if (!useScreen && this._currentRenderTarget) {
  12282. return this._currentRenderTarget.width;
  12283. }
  12284. return this._gl.drawingBufferWidth;
  12285. };
  12286. /**
  12287. * Gets the current render height
  12288. * @param useScreen defines if screen size must be used (or the current render target if any)
  12289. * @returns a number defining the current render height
  12290. */
  12291. Engine.prototype.getRenderHeight = function (useScreen) {
  12292. if (useScreen === void 0) { useScreen = false; }
  12293. if (!useScreen && this._currentRenderTarget) {
  12294. return this._currentRenderTarget.height;
  12295. }
  12296. return this._gl.drawingBufferHeight;
  12297. };
  12298. /**
  12299. * Gets the HTML canvas attached with the current webGL context
  12300. * @returns a HTML canvas
  12301. */
  12302. Engine.prototype.getRenderingCanvas = function () {
  12303. return this._renderingCanvas;
  12304. };
  12305. /**
  12306. * Gets the client rect of the HTML canvas attached with the current webGL context
  12307. * @returns a client rectanglee
  12308. */
  12309. Engine.prototype.getRenderingCanvasClientRect = function () {
  12310. if (!this._renderingCanvas) {
  12311. return null;
  12312. }
  12313. return this._renderingCanvas.getBoundingClientRect();
  12314. };
  12315. /**
  12316. * Defines the hardware scaling level.
  12317. * By default the hardware scaling level is computed from the window device ratio.
  12318. * 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.
  12319. * @param level defines the level to use
  12320. */
  12321. Engine.prototype.setHardwareScalingLevel = function (level) {
  12322. this._hardwareScalingLevel = level;
  12323. this.resize();
  12324. };
  12325. /**
  12326. * Gets the current hardware scaling level.
  12327. * By default the hardware scaling level is computed from the window device ratio.
  12328. * 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.
  12329. * @returns a number indicating the current hardware scaling level
  12330. */
  12331. Engine.prototype.getHardwareScalingLevel = function () {
  12332. return this._hardwareScalingLevel;
  12333. };
  12334. /**
  12335. * Gets the list of loaded textures
  12336. * @returns an array containing all loaded textures
  12337. */
  12338. Engine.prototype.getLoadedTexturesCache = function () {
  12339. return this._internalTexturesCache;
  12340. };
  12341. /**
  12342. * Gets the object containing all engine capabilities
  12343. * @returns the EngineCapabilities object
  12344. */
  12345. Engine.prototype.getCaps = function () {
  12346. return this._caps;
  12347. };
  12348. Object.defineProperty(Engine.prototype, "drawCalls", {
  12349. /** @hidden */
  12350. get: function () {
  12351. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12352. return 0;
  12353. },
  12354. enumerable: true,
  12355. configurable: true
  12356. });
  12357. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12358. /** @hidden */
  12359. get: function () {
  12360. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12361. return null;
  12362. },
  12363. enumerable: true,
  12364. configurable: true
  12365. });
  12366. /**
  12367. * Gets the current depth function
  12368. * @returns a number defining the depth function
  12369. */
  12370. Engine.prototype.getDepthFunction = function () {
  12371. return this._depthCullingState.depthFunc;
  12372. };
  12373. /**
  12374. * Sets the current depth function
  12375. * @param depthFunc defines the function to use
  12376. */
  12377. Engine.prototype.setDepthFunction = function (depthFunc) {
  12378. this._depthCullingState.depthFunc = depthFunc;
  12379. };
  12380. /**
  12381. * Sets the current depth function to GREATER
  12382. */
  12383. Engine.prototype.setDepthFunctionToGreater = function () {
  12384. this._depthCullingState.depthFunc = this._gl.GREATER;
  12385. };
  12386. /**
  12387. * Sets the current depth function to GEQUAL
  12388. */
  12389. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12390. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12391. };
  12392. /**
  12393. * Sets the current depth function to LESS
  12394. */
  12395. Engine.prototype.setDepthFunctionToLess = function () {
  12396. this._depthCullingState.depthFunc = this._gl.LESS;
  12397. };
  12398. /**
  12399. * Sets the current depth function to LEQUAL
  12400. */
  12401. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12402. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12403. };
  12404. /**
  12405. * Gets a boolean indicating if stencil buffer is enabled
  12406. * @returns the current stencil buffer state
  12407. */
  12408. Engine.prototype.getStencilBuffer = function () {
  12409. return this._stencilState.stencilTest;
  12410. };
  12411. /**
  12412. * Enable or disable the stencil buffer
  12413. * @param enable defines if the stencil buffer must be enabled or disabled
  12414. */
  12415. Engine.prototype.setStencilBuffer = function (enable) {
  12416. this._stencilState.stencilTest = enable;
  12417. };
  12418. /**
  12419. * Gets the current stencil mask
  12420. * @returns a number defining the new stencil mask to use
  12421. */
  12422. Engine.prototype.getStencilMask = function () {
  12423. return this._stencilState.stencilMask;
  12424. };
  12425. /**
  12426. * Sets the current stencil mask
  12427. * @param mask defines the new stencil mask to use
  12428. */
  12429. Engine.prototype.setStencilMask = function (mask) {
  12430. this._stencilState.stencilMask = mask;
  12431. };
  12432. /**
  12433. * Gets the current stencil function
  12434. * @returns a number defining the stencil function to use
  12435. */
  12436. Engine.prototype.getStencilFunction = function () {
  12437. return this._stencilState.stencilFunc;
  12438. };
  12439. /**
  12440. * Gets the current stencil reference value
  12441. * @returns a number defining the stencil reference value to use
  12442. */
  12443. Engine.prototype.getStencilFunctionReference = function () {
  12444. return this._stencilState.stencilFuncRef;
  12445. };
  12446. /**
  12447. * Gets the current stencil mask
  12448. * @returns a number defining the stencil mask to use
  12449. */
  12450. Engine.prototype.getStencilFunctionMask = function () {
  12451. return this._stencilState.stencilFuncMask;
  12452. };
  12453. /**
  12454. * Sets the current stencil function
  12455. * @param stencilFunc defines the new stencil function to use
  12456. */
  12457. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12458. this._stencilState.stencilFunc = stencilFunc;
  12459. };
  12460. /**
  12461. * Sets the current stencil reference
  12462. * @param reference defines the new stencil reference to use
  12463. */
  12464. Engine.prototype.setStencilFunctionReference = function (reference) {
  12465. this._stencilState.stencilFuncRef = reference;
  12466. };
  12467. /**
  12468. * Sets the current stencil mask
  12469. * @param mask defines the new stencil mask to use
  12470. */
  12471. Engine.prototype.setStencilFunctionMask = function (mask) {
  12472. this._stencilState.stencilFuncMask = mask;
  12473. };
  12474. /**
  12475. * Gets the current stencil operation when stencil fails
  12476. * @returns a number defining stencil operation to use when stencil fails
  12477. */
  12478. Engine.prototype.getStencilOperationFail = function () {
  12479. return this._stencilState.stencilOpStencilFail;
  12480. };
  12481. /**
  12482. * Gets the current stencil operation when depth fails
  12483. * @returns a number defining stencil operation to use when depth fails
  12484. */
  12485. Engine.prototype.getStencilOperationDepthFail = function () {
  12486. return this._stencilState.stencilOpDepthFail;
  12487. };
  12488. /**
  12489. * Gets the current stencil operation when stencil passes
  12490. * @returns a number defining stencil operation to use when stencil passes
  12491. */
  12492. Engine.prototype.getStencilOperationPass = function () {
  12493. return this._stencilState.stencilOpStencilDepthPass;
  12494. };
  12495. /**
  12496. * Sets the stencil operation to use when stencil fails
  12497. * @param operation defines the stencil operation to use when stencil fails
  12498. */
  12499. Engine.prototype.setStencilOperationFail = function (operation) {
  12500. this._stencilState.stencilOpStencilFail = operation;
  12501. };
  12502. /**
  12503. * Sets the stencil operation to use when depth fails
  12504. * @param operation defines the stencil operation to use when depth fails
  12505. */
  12506. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12507. this._stencilState.stencilOpDepthFail = operation;
  12508. };
  12509. /**
  12510. * Sets the stencil operation to use when stencil passes
  12511. * @param operation defines the stencil operation to use when stencil passes
  12512. */
  12513. Engine.prototype.setStencilOperationPass = function (operation) {
  12514. this._stencilState.stencilOpStencilDepthPass = operation;
  12515. };
  12516. /**
  12517. * Sets a boolean indicating if the dithering state is enabled or disabled
  12518. * @param value defines the dithering state
  12519. */
  12520. Engine.prototype.setDitheringState = function (value) {
  12521. if (value) {
  12522. this._gl.enable(this._gl.DITHER);
  12523. }
  12524. else {
  12525. this._gl.disable(this._gl.DITHER);
  12526. }
  12527. };
  12528. /**
  12529. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12530. * @param value defines the rasterizer state
  12531. */
  12532. Engine.prototype.setRasterizerState = function (value) {
  12533. if (value) {
  12534. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12535. }
  12536. else {
  12537. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12538. }
  12539. };
  12540. /**
  12541. * stop executing a render loop function and remove it from the execution array
  12542. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12543. */
  12544. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12545. if (!renderFunction) {
  12546. this._activeRenderLoops = [];
  12547. return;
  12548. }
  12549. var index = this._activeRenderLoops.indexOf(renderFunction);
  12550. if (index >= 0) {
  12551. this._activeRenderLoops.splice(index, 1);
  12552. }
  12553. };
  12554. /** @hidden */
  12555. Engine.prototype._renderLoop = function () {
  12556. if (!this._contextWasLost) {
  12557. var shouldRender = true;
  12558. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12559. shouldRender = false;
  12560. }
  12561. if (shouldRender) {
  12562. // Start new frame
  12563. this.beginFrame();
  12564. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12565. var renderFunction = this._activeRenderLoops[index];
  12566. renderFunction();
  12567. }
  12568. // Present
  12569. this.endFrame();
  12570. }
  12571. }
  12572. if (this._activeRenderLoops.length > 0) {
  12573. // Register new frame
  12574. var requester = null;
  12575. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12576. requester = this._vrDisplay;
  12577. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12578. }
  12579. else {
  12580. this._renderingQueueLaunched = false;
  12581. }
  12582. };
  12583. /**
  12584. * Register and execute a render loop. The engine can have more than one render function
  12585. * @param renderFunction defines the function to continuously execute
  12586. */
  12587. Engine.prototype.runRenderLoop = function (renderFunction) {
  12588. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12589. return;
  12590. }
  12591. this._activeRenderLoops.push(renderFunction);
  12592. if (!this._renderingQueueLaunched) {
  12593. this._renderingQueueLaunched = true;
  12594. this._bindedRenderFunction = this._renderLoop.bind(this);
  12595. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12596. }
  12597. };
  12598. /**
  12599. * Toggle full screen mode
  12600. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12601. * @param options defines an option object to be sent to the requestFullscreen function
  12602. */
  12603. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12604. if (this.isFullscreen) {
  12605. BABYLON.Tools.ExitFullscreen();
  12606. }
  12607. else {
  12608. this._pointerLockRequested = requestPointerLock;
  12609. if (this._renderingCanvas) {
  12610. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12611. }
  12612. }
  12613. };
  12614. /**
  12615. * Clear the current render buffer or the current render target (if any is set up)
  12616. * @param color defines the color to use
  12617. * @param backBuffer defines if the back buffer must be cleared
  12618. * @param depth defines if the depth buffer must be cleared
  12619. * @param stencil defines if the stencil buffer must be cleared
  12620. */
  12621. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12622. if (stencil === void 0) { stencil = false; }
  12623. this.applyStates();
  12624. var mode = 0;
  12625. if (backBuffer && color) {
  12626. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12627. mode |= this._gl.COLOR_BUFFER_BIT;
  12628. }
  12629. if (depth) {
  12630. this._gl.clearDepth(1.0);
  12631. mode |= this._gl.DEPTH_BUFFER_BIT;
  12632. }
  12633. if (stencil) {
  12634. this._gl.clearStencil(0);
  12635. mode |= this._gl.STENCIL_BUFFER_BIT;
  12636. }
  12637. this._gl.clear(mode);
  12638. };
  12639. /**
  12640. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12641. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12642. * @param y defines the y-coordinate of the corner of the clear rectangle
  12643. * @param width defines the width of the clear rectangle
  12644. * @param height defines the height of the clear rectangle
  12645. * @param clearColor defines the clear color
  12646. */
  12647. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12648. var gl = this._gl;
  12649. // Save state
  12650. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12651. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12652. // Change state
  12653. gl.enable(gl.SCISSOR_TEST);
  12654. gl.scissor(x, y, width, height);
  12655. // Clear
  12656. this.clear(clearColor, true, true, true);
  12657. // Restore state
  12658. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12659. if (curScissor === true) {
  12660. gl.enable(gl.SCISSOR_TEST);
  12661. }
  12662. else {
  12663. gl.disable(gl.SCISSOR_TEST);
  12664. }
  12665. };
  12666. /** @hidden */
  12667. Engine.prototype._viewport = function (x, y, width, height) {
  12668. if (x !== this._viewportCached.x ||
  12669. y !== this._viewportCached.y ||
  12670. width !== this._viewportCached.z ||
  12671. height !== this._viewportCached.w) {
  12672. this._viewportCached.x = x;
  12673. this._viewportCached.y = y;
  12674. this._viewportCached.z = width;
  12675. this._viewportCached.w = height;
  12676. this._gl.viewport(x, y, width, height);
  12677. }
  12678. };
  12679. /**
  12680. * Set the WebGL's viewport
  12681. * @param viewport defines the viewport element to be used
  12682. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12683. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12684. */
  12685. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12686. var width = requiredWidth || this.getRenderWidth();
  12687. var height = requiredHeight || this.getRenderHeight();
  12688. var x = viewport.x || 0;
  12689. var y = viewport.y || 0;
  12690. this._cachedViewport = viewport;
  12691. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12692. };
  12693. /**
  12694. * Directly set the WebGL Viewport
  12695. * @param x defines the x coordinate of the viewport (in screen space)
  12696. * @param y defines the y coordinate of the viewport (in screen space)
  12697. * @param width defines the width of the viewport (in screen space)
  12698. * @param height defines the height of the viewport (in screen space)
  12699. * @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
  12700. */
  12701. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12702. var currentViewport = this._cachedViewport;
  12703. this._cachedViewport = null;
  12704. this._viewport(x, y, width, height);
  12705. return currentViewport;
  12706. };
  12707. /**
  12708. * Begin a new frame
  12709. */
  12710. Engine.prototype.beginFrame = function () {
  12711. this.onBeginFrameObservable.notifyObservers(this);
  12712. this._measureFps();
  12713. };
  12714. /**
  12715. * Enf the current frame
  12716. */
  12717. Engine.prototype.endFrame = function () {
  12718. // Force a flush in case we are using a bad OS.
  12719. if (this._badOS) {
  12720. this.flushFramebuffer();
  12721. }
  12722. // Submit frame to the vr device, if enabled
  12723. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12724. // TODO: We should only submit the frame if we read frameData successfully.
  12725. this._vrDisplay.submitFrame();
  12726. }
  12727. this.onEndFrameObservable.notifyObservers(this);
  12728. };
  12729. /**
  12730. * Resize the view according to the canvas' size
  12731. */
  12732. Engine.prototype.resize = function () {
  12733. // We're not resizing the size of the canvas while in VR mode & presenting
  12734. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12735. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12736. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12737. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12738. }
  12739. };
  12740. /**
  12741. * Force a specific size of the canvas
  12742. * @param width defines the new canvas' width
  12743. * @param height defines the new canvas' height
  12744. */
  12745. Engine.prototype.setSize = function (width, height) {
  12746. if (!this._renderingCanvas) {
  12747. return;
  12748. }
  12749. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12750. return;
  12751. }
  12752. this._renderingCanvas.width = width;
  12753. this._renderingCanvas.height = height;
  12754. for (var index = 0; index < this.scenes.length; index++) {
  12755. var scene = this.scenes[index];
  12756. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12757. var cam = scene.cameras[camIndex];
  12758. cam._currentRenderId = 0;
  12759. }
  12760. }
  12761. if (this.onResizeObservable.hasObservers) {
  12762. this.onResizeObservable.notifyObservers(this);
  12763. }
  12764. };
  12765. // WebVR functions
  12766. /**
  12767. * Gets a boolean indicating if a webVR device was detected
  12768. * @returns true if a webVR device was detected
  12769. */
  12770. Engine.prototype.isVRDevicePresent = function () {
  12771. return !!this._vrDisplay;
  12772. };
  12773. /**
  12774. * Gets the current webVR device
  12775. * @returns the current webVR device (or null)
  12776. */
  12777. Engine.prototype.getVRDevice = function () {
  12778. return this._vrDisplay;
  12779. };
  12780. /**
  12781. * Initializes a webVR display and starts listening to display change events
  12782. * The onVRDisplayChangedObservable will be notified upon these changes
  12783. * @returns The onVRDisplayChangedObservable
  12784. */
  12785. Engine.prototype.initWebVR = function () {
  12786. this.initWebVRAsync();
  12787. return this.onVRDisplayChangedObservable;
  12788. };
  12789. /**
  12790. * Initializes a webVR display and starts listening to display change events
  12791. * The onVRDisplayChangedObservable will be notified upon these changes
  12792. * @returns A promise containing a VRDisplay and if vr is supported
  12793. */
  12794. Engine.prototype.initWebVRAsync = function () {
  12795. var _this = this;
  12796. var notifyObservers = function () {
  12797. var eventArgs = {
  12798. vrDisplay: _this._vrDisplay,
  12799. vrSupported: _this._vrSupported
  12800. };
  12801. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12802. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12803. };
  12804. if (!this._onVrDisplayConnect) {
  12805. this._onVrDisplayConnect = function (event) {
  12806. _this._vrDisplay = event.display;
  12807. notifyObservers();
  12808. };
  12809. this._onVrDisplayDisconnect = function () {
  12810. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12811. _this._vrDisplay = undefined;
  12812. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12813. notifyObservers();
  12814. };
  12815. this._onVrDisplayPresentChange = function () {
  12816. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12817. };
  12818. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12819. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12820. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12821. }
  12822. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12823. this._webVRInitPromise.then(notifyObservers);
  12824. return this._webVRInitPromise;
  12825. };
  12826. /**
  12827. * Call this function to switch to webVR mode
  12828. * Will do nothing if webVR is not supported or if there is no webVR device
  12829. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12830. */
  12831. Engine.prototype.enableVR = function () {
  12832. var _this = this;
  12833. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12834. var onResolved = function () {
  12835. _this.onVRRequestPresentComplete.notifyObservers(true);
  12836. _this._onVRFullScreenTriggered();
  12837. };
  12838. var onRejected = function () {
  12839. _this.onVRRequestPresentComplete.notifyObservers(false);
  12840. };
  12841. this.onVRRequestPresentStart.notifyObservers(this);
  12842. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12843. }
  12844. };
  12845. /**
  12846. * Call this function to leave webVR mode
  12847. * Will do nothing if webVR is not supported or if there is no webVR device
  12848. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12849. */
  12850. Engine.prototype.disableVR = function () {
  12851. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12852. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12853. }
  12854. };
  12855. Engine.prototype._getVRDisplaysAsync = function () {
  12856. var _this = this;
  12857. return new Promise(function (res, rej) {
  12858. if (navigator.getVRDisplays) {
  12859. navigator.getVRDisplays().then(function (devices) {
  12860. _this._vrSupported = true;
  12861. // note that devices may actually be an empty array. This is fine;
  12862. // we expect this._vrDisplay to be undefined in this case.
  12863. _this._vrDisplay = devices[0];
  12864. res({
  12865. vrDisplay: _this._vrDisplay,
  12866. vrSupported: _this._vrSupported
  12867. });
  12868. });
  12869. }
  12870. else {
  12871. _this._vrDisplay = undefined;
  12872. _this._vrSupported = false;
  12873. res({
  12874. vrDisplay: _this._vrDisplay,
  12875. vrSupported: _this._vrSupported
  12876. });
  12877. }
  12878. });
  12879. };
  12880. /**
  12881. * Binds the frame buffer to the specified texture.
  12882. * @param texture The texture to render to or null for the default canvas
  12883. * @param faceIndex The face of the texture to render to in case of cube texture
  12884. * @param requiredWidth The width of the target to render to
  12885. * @param requiredHeight The height of the target to render to
  12886. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12887. * @param depthStencilTexture The depth stencil texture to use to render
  12888. * @param lodLevel defines le lod level to bind to the frame buffer
  12889. */
  12890. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12891. if (lodLevel === void 0) { lodLevel = 0; }
  12892. if (this._currentRenderTarget) {
  12893. this.unBindFramebuffer(this._currentRenderTarget);
  12894. }
  12895. this._currentRenderTarget = texture;
  12896. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12897. var gl = this._gl;
  12898. if (texture.isCube) {
  12899. if (faceIndex === undefined) {
  12900. faceIndex = 0;
  12901. }
  12902. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12903. if (depthStencilTexture) {
  12904. if (depthStencilTexture._generateStencilBuffer) {
  12905. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12906. }
  12907. else {
  12908. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12909. }
  12910. }
  12911. }
  12912. if (this._cachedViewport && !forceFullscreenViewport) {
  12913. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12914. }
  12915. else {
  12916. if (!requiredWidth) {
  12917. requiredWidth = texture.width;
  12918. if (lodLevel) {
  12919. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12920. }
  12921. }
  12922. if (!requiredHeight) {
  12923. requiredHeight = texture.height;
  12924. if (lodLevel) {
  12925. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12926. }
  12927. }
  12928. this._viewport(0, 0, requiredWidth, requiredHeight);
  12929. }
  12930. this.wipeCaches();
  12931. };
  12932. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12933. if (this._currentFramebuffer !== framebuffer) {
  12934. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12935. this._currentFramebuffer = framebuffer;
  12936. }
  12937. };
  12938. /**
  12939. * Unbind the current render target texture from the webGL context
  12940. * @param texture defines the render target texture to unbind
  12941. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12942. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12943. */
  12944. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12945. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12946. this._currentRenderTarget = null;
  12947. // If MSAA, we need to bitblt back to main texture
  12948. var gl = this._gl;
  12949. if (texture._MSAAFramebuffer) {
  12950. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12951. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12952. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12953. }
  12954. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12955. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12956. gl.generateMipmap(gl.TEXTURE_2D);
  12957. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12958. }
  12959. if (onBeforeUnbind) {
  12960. if (texture._MSAAFramebuffer) {
  12961. // Bind the correct framebuffer
  12962. this.bindUnboundFramebuffer(texture._framebuffer);
  12963. }
  12964. onBeforeUnbind();
  12965. }
  12966. this.bindUnboundFramebuffer(null);
  12967. };
  12968. /**
  12969. * Unbind a list of render target textures from the webGL context
  12970. * This is used only when drawBuffer extension or webGL2 are active
  12971. * @param textures defines the render target textures to unbind
  12972. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12973. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12974. */
  12975. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12976. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12977. this._currentRenderTarget = null;
  12978. // If MSAA, we need to bitblt back to main texture
  12979. var gl = this._gl;
  12980. if (textures[0]._MSAAFramebuffer) {
  12981. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12982. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12983. var attachments = textures[0]._attachments;
  12984. if (!attachments) {
  12985. attachments = new Array(textures.length);
  12986. textures[0]._attachments = attachments;
  12987. }
  12988. for (var i = 0; i < textures.length; i++) {
  12989. var texture = textures[i];
  12990. for (var j = 0; j < attachments.length; j++) {
  12991. attachments[j] = gl.NONE;
  12992. }
  12993. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12994. gl.readBuffer(attachments[i]);
  12995. gl.drawBuffers(attachments);
  12996. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12997. }
  12998. for (var i = 0; i < attachments.length; i++) {
  12999. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13000. }
  13001. gl.drawBuffers(attachments);
  13002. }
  13003. for (var i = 0; i < textures.length; i++) {
  13004. var texture = textures[i];
  13005. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13006. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13007. gl.generateMipmap(gl.TEXTURE_2D);
  13008. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13009. }
  13010. }
  13011. if (onBeforeUnbind) {
  13012. if (textures[0]._MSAAFramebuffer) {
  13013. // Bind the correct framebuffer
  13014. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13015. }
  13016. onBeforeUnbind();
  13017. }
  13018. this.bindUnboundFramebuffer(null);
  13019. };
  13020. /**
  13021. * Force the mipmap generation for the given render target texture
  13022. * @param texture defines the render target texture to use
  13023. */
  13024. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13025. if (texture.generateMipMaps) {
  13026. var gl = this._gl;
  13027. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13028. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13029. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13030. }
  13031. };
  13032. /**
  13033. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13034. */
  13035. Engine.prototype.flushFramebuffer = function () {
  13036. this._gl.flush();
  13037. };
  13038. /**
  13039. * Unbind the current render target and bind the default framebuffer
  13040. */
  13041. Engine.prototype.restoreDefaultFramebuffer = function () {
  13042. if (this._currentRenderTarget) {
  13043. this.unBindFramebuffer(this._currentRenderTarget);
  13044. }
  13045. else {
  13046. this.bindUnboundFramebuffer(null);
  13047. }
  13048. if (this._cachedViewport) {
  13049. this.setViewport(this._cachedViewport);
  13050. }
  13051. this.wipeCaches();
  13052. };
  13053. // UBOs
  13054. /**
  13055. * Create an uniform buffer
  13056. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13057. * @param elements defines the content of the uniform buffer
  13058. * @returns the webGL uniform buffer
  13059. */
  13060. Engine.prototype.createUniformBuffer = function (elements) {
  13061. var ubo = this._gl.createBuffer();
  13062. if (!ubo) {
  13063. throw new Error("Unable to create uniform buffer");
  13064. }
  13065. this.bindUniformBuffer(ubo);
  13066. if (elements instanceof Float32Array) {
  13067. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13068. }
  13069. else {
  13070. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13071. }
  13072. this.bindUniformBuffer(null);
  13073. ubo.references = 1;
  13074. return ubo;
  13075. };
  13076. /**
  13077. * Create a dynamic uniform buffer
  13078. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13079. * @param elements defines the content of the uniform buffer
  13080. * @returns the webGL uniform buffer
  13081. */
  13082. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13083. var ubo = this._gl.createBuffer();
  13084. if (!ubo) {
  13085. throw new Error("Unable to create dynamic uniform buffer");
  13086. }
  13087. this.bindUniformBuffer(ubo);
  13088. if (elements instanceof Float32Array) {
  13089. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13090. }
  13091. else {
  13092. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13093. }
  13094. this.bindUniformBuffer(null);
  13095. ubo.references = 1;
  13096. return ubo;
  13097. };
  13098. /**
  13099. * Update an existing uniform buffer
  13100. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13101. * @param uniformBuffer defines the target uniform buffer
  13102. * @param elements defines the content to update
  13103. * @param offset defines the offset in the uniform buffer where update should start
  13104. * @param count defines the size of the data to update
  13105. */
  13106. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13107. this.bindUniformBuffer(uniformBuffer);
  13108. if (offset === undefined) {
  13109. offset = 0;
  13110. }
  13111. if (count === undefined) {
  13112. if (elements instanceof Float32Array) {
  13113. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13114. }
  13115. else {
  13116. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13117. }
  13118. }
  13119. else {
  13120. if (elements instanceof Float32Array) {
  13121. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13122. }
  13123. else {
  13124. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13125. }
  13126. }
  13127. this.bindUniformBuffer(null);
  13128. };
  13129. // VBOs
  13130. Engine.prototype._resetVertexBufferBinding = function () {
  13131. this.bindArrayBuffer(null);
  13132. this._cachedVertexBuffers = null;
  13133. };
  13134. /**
  13135. * Creates a vertex buffer
  13136. * @param data the data for the vertex buffer
  13137. * @returns the new WebGL static buffer
  13138. */
  13139. Engine.prototype.createVertexBuffer = function (data) {
  13140. var vbo = this._gl.createBuffer();
  13141. if (!vbo) {
  13142. throw new Error("Unable to create vertex buffer");
  13143. }
  13144. this.bindArrayBuffer(vbo);
  13145. if (data instanceof Array) {
  13146. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13147. }
  13148. else {
  13149. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13150. }
  13151. this._resetVertexBufferBinding();
  13152. vbo.references = 1;
  13153. return vbo;
  13154. };
  13155. /**
  13156. * Creates a dynamic vertex buffer
  13157. * @param data the data for the dynamic vertex buffer
  13158. * @returns the new WebGL dynamic buffer
  13159. */
  13160. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13161. var vbo = this._gl.createBuffer();
  13162. if (!vbo) {
  13163. throw new Error("Unable to create dynamic vertex buffer");
  13164. }
  13165. this.bindArrayBuffer(vbo);
  13166. if (data instanceof Array) {
  13167. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13168. }
  13169. else {
  13170. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13171. }
  13172. this._resetVertexBufferBinding();
  13173. vbo.references = 1;
  13174. return vbo;
  13175. };
  13176. /**
  13177. * Update a dynamic index buffer
  13178. * @param indexBuffer defines the target index buffer
  13179. * @param indices defines the data to update
  13180. * @param offset defines the offset in the target index buffer where update should start
  13181. */
  13182. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13183. if (offset === void 0) { offset = 0; }
  13184. // Force cache update
  13185. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13186. this.bindIndexBuffer(indexBuffer);
  13187. var arrayBuffer;
  13188. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13189. arrayBuffer = indices;
  13190. }
  13191. else {
  13192. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13193. }
  13194. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13195. this._resetIndexBufferBinding();
  13196. };
  13197. /**
  13198. * Updates a dynamic vertex buffer.
  13199. * @param vertexBuffer the vertex buffer to update
  13200. * @param data the data used to update the vertex buffer
  13201. * @param byteOffset the byte offset of the data
  13202. * @param byteLength the byte length of the data
  13203. */
  13204. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13205. this.bindArrayBuffer(vertexBuffer);
  13206. if (byteOffset === undefined) {
  13207. byteOffset = 0;
  13208. }
  13209. if (byteLength === undefined) {
  13210. if (data instanceof Array) {
  13211. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13212. }
  13213. else {
  13214. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13215. }
  13216. }
  13217. else {
  13218. if (data instanceof Array) {
  13219. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13220. }
  13221. else {
  13222. if (data instanceof ArrayBuffer) {
  13223. data = new Uint8Array(data, byteOffset, byteLength);
  13224. }
  13225. else {
  13226. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13227. }
  13228. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13229. }
  13230. }
  13231. this._resetVertexBufferBinding();
  13232. };
  13233. Engine.prototype._resetIndexBufferBinding = function () {
  13234. this.bindIndexBuffer(null);
  13235. this._cachedIndexBuffer = null;
  13236. };
  13237. /**
  13238. * Creates a new index buffer
  13239. * @param indices defines the content of the index buffer
  13240. * @param updatable defines if the index buffer must be updatable
  13241. * @returns a new webGL buffer
  13242. */
  13243. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13244. var vbo = this._gl.createBuffer();
  13245. if (!vbo) {
  13246. throw new Error("Unable to create index buffer");
  13247. }
  13248. this.bindIndexBuffer(vbo);
  13249. // Check for 32 bits indices
  13250. var arrayBuffer;
  13251. var need32Bits = false;
  13252. if (indices instanceof Uint16Array) {
  13253. arrayBuffer = indices;
  13254. }
  13255. else {
  13256. //check 32 bit support
  13257. if (this._caps.uintIndices) {
  13258. if (indices instanceof Uint32Array) {
  13259. arrayBuffer = indices;
  13260. need32Bits = true;
  13261. }
  13262. else {
  13263. //number[] or Int32Array, check if 32 bit is necessary
  13264. for (var index = 0; index < indices.length; index++) {
  13265. if (indices[index] > 65535) {
  13266. need32Bits = true;
  13267. break;
  13268. }
  13269. }
  13270. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13271. }
  13272. }
  13273. else {
  13274. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13275. arrayBuffer = new Uint16Array(indices);
  13276. }
  13277. }
  13278. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13279. this._resetIndexBufferBinding();
  13280. vbo.references = 1;
  13281. vbo.is32Bits = need32Bits;
  13282. return vbo;
  13283. };
  13284. /**
  13285. * Bind a webGL buffer to the webGL context
  13286. * @param buffer defines the buffer to bind
  13287. */
  13288. Engine.prototype.bindArrayBuffer = function (buffer) {
  13289. if (!this._vaoRecordInProgress) {
  13290. this._unbindVertexArrayObject();
  13291. }
  13292. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13293. };
  13294. /**
  13295. * Bind an uniform buffer to the current webGL context
  13296. * @param buffer defines the buffer to bind
  13297. */
  13298. Engine.prototype.bindUniformBuffer = function (buffer) {
  13299. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13300. };
  13301. /**
  13302. * Bind a buffer to the current webGL context at a given location
  13303. * @param buffer defines the buffer to bind
  13304. * @param location defines the index where to bind the buffer
  13305. */
  13306. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13307. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13308. };
  13309. /**
  13310. * Bind a specific block at a given index in a specific shader program
  13311. * @param shaderProgram defines the shader program
  13312. * @param blockName defines the block name
  13313. * @param index defines the index where to bind the block
  13314. */
  13315. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13316. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13317. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13318. };
  13319. ;
  13320. Engine.prototype.bindIndexBuffer = function (buffer) {
  13321. if (!this._vaoRecordInProgress) {
  13322. this._unbindVertexArrayObject();
  13323. }
  13324. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13325. };
  13326. Engine.prototype.bindBuffer = function (buffer, target) {
  13327. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13328. this._gl.bindBuffer(target, buffer);
  13329. this._currentBoundBuffer[target] = buffer;
  13330. }
  13331. };
  13332. /**
  13333. * update the bound buffer with the given data
  13334. * @param data defines the data to update
  13335. */
  13336. Engine.prototype.updateArrayBuffer = function (data) {
  13337. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13338. };
  13339. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13340. var pointer = this._currentBufferPointers[indx];
  13341. var changed = false;
  13342. if (!pointer.active) {
  13343. changed = true;
  13344. pointer.active = true;
  13345. pointer.index = indx;
  13346. pointer.size = size;
  13347. pointer.type = type;
  13348. pointer.normalized = normalized;
  13349. pointer.stride = stride;
  13350. pointer.offset = offset;
  13351. pointer.buffer = buffer;
  13352. }
  13353. else {
  13354. if (pointer.buffer !== buffer) {
  13355. pointer.buffer = buffer;
  13356. changed = true;
  13357. }
  13358. if (pointer.size !== size) {
  13359. pointer.size = size;
  13360. changed = true;
  13361. }
  13362. if (pointer.type !== type) {
  13363. pointer.type = type;
  13364. changed = true;
  13365. }
  13366. if (pointer.normalized !== normalized) {
  13367. pointer.normalized = normalized;
  13368. changed = true;
  13369. }
  13370. if (pointer.stride !== stride) {
  13371. pointer.stride = stride;
  13372. changed = true;
  13373. }
  13374. if (pointer.offset !== offset) {
  13375. pointer.offset = offset;
  13376. changed = true;
  13377. }
  13378. }
  13379. if (changed || this._vaoRecordInProgress) {
  13380. this.bindArrayBuffer(buffer);
  13381. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13382. }
  13383. };
  13384. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13385. if (indexBuffer == null) {
  13386. return;
  13387. }
  13388. if (this._cachedIndexBuffer !== indexBuffer) {
  13389. this._cachedIndexBuffer = indexBuffer;
  13390. this.bindIndexBuffer(indexBuffer);
  13391. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13392. }
  13393. };
  13394. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13395. var attributes = effect.getAttributesNames();
  13396. if (!this._vaoRecordInProgress) {
  13397. this._unbindVertexArrayObject();
  13398. }
  13399. this.unbindAllAttributes();
  13400. for (var index = 0; index < attributes.length; index++) {
  13401. var order = effect.getAttributeLocation(index);
  13402. if (order >= 0) {
  13403. var vertexBuffer = vertexBuffers[attributes[index]];
  13404. if (!vertexBuffer) {
  13405. continue;
  13406. }
  13407. this._gl.enableVertexAttribArray(order);
  13408. if (!this._vaoRecordInProgress) {
  13409. this._vertexAttribArraysEnabled[order] = true;
  13410. }
  13411. var buffer = vertexBuffer.getBuffer();
  13412. if (buffer) {
  13413. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13414. if (vertexBuffer.getIsInstanced()) {
  13415. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13416. if (!this._vaoRecordInProgress) {
  13417. this._currentInstanceLocations.push(order);
  13418. this._currentInstanceBuffers.push(buffer);
  13419. }
  13420. }
  13421. }
  13422. }
  13423. }
  13424. };
  13425. /**
  13426. * Records a vertex array object
  13427. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13428. * @param vertexBuffers defines the list of vertex buffers to store
  13429. * @param indexBuffer defines the index buffer to store
  13430. * @param effect defines the effect to store
  13431. * @returns the new vertex array object
  13432. */
  13433. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13434. var vao = this._gl.createVertexArray();
  13435. this._vaoRecordInProgress = true;
  13436. this._gl.bindVertexArray(vao);
  13437. this._mustWipeVertexAttributes = true;
  13438. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13439. this.bindIndexBuffer(indexBuffer);
  13440. this._vaoRecordInProgress = false;
  13441. this._gl.bindVertexArray(null);
  13442. return vao;
  13443. };
  13444. /**
  13445. * Bind a specific vertex array object
  13446. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13447. * @param vertexArrayObject defines the vertex array object to bind
  13448. * @param indexBuffer defines the index buffer to bind
  13449. */
  13450. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13451. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13452. this._cachedVertexArrayObject = vertexArrayObject;
  13453. this._gl.bindVertexArray(vertexArrayObject);
  13454. this._cachedVertexBuffers = null;
  13455. this._cachedIndexBuffer = null;
  13456. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13457. this._mustWipeVertexAttributes = true;
  13458. }
  13459. };
  13460. /**
  13461. * Bind webGl buffers directly to the webGL context
  13462. * @param vertexBuffer defines the vertex buffer to bind
  13463. * @param indexBuffer defines the index buffer to bind
  13464. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13465. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13466. * @param effect defines the effect associated with the vertex buffer
  13467. */
  13468. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13469. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13470. this._cachedVertexBuffers = vertexBuffer;
  13471. this._cachedEffectForVertexBuffers = effect;
  13472. var attributesCount = effect.getAttributesCount();
  13473. this._unbindVertexArrayObject();
  13474. this.unbindAllAttributes();
  13475. var offset = 0;
  13476. for (var index = 0; index < attributesCount; index++) {
  13477. if (index < vertexDeclaration.length) {
  13478. var order = effect.getAttributeLocation(index);
  13479. if (order >= 0) {
  13480. this._gl.enableVertexAttribArray(order);
  13481. this._vertexAttribArraysEnabled[order] = true;
  13482. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13483. }
  13484. offset += vertexDeclaration[index] * 4;
  13485. }
  13486. }
  13487. }
  13488. this._bindIndexBufferWithCache(indexBuffer);
  13489. };
  13490. Engine.prototype._unbindVertexArrayObject = function () {
  13491. if (!this._cachedVertexArrayObject) {
  13492. return;
  13493. }
  13494. this._cachedVertexArrayObject = null;
  13495. this._gl.bindVertexArray(null);
  13496. };
  13497. /**
  13498. * Bind a list of vertex buffers to the webGL context
  13499. * @param vertexBuffers defines the list of vertex buffers to bind
  13500. * @param indexBuffer defines the index buffer to bind
  13501. * @param effect defines the effect associated with the vertex buffers
  13502. */
  13503. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13504. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13505. this._cachedVertexBuffers = vertexBuffers;
  13506. this._cachedEffectForVertexBuffers = effect;
  13507. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13508. }
  13509. this._bindIndexBufferWithCache(indexBuffer);
  13510. };
  13511. /**
  13512. * Unbind all instance attributes
  13513. */
  13514. Engine.prototype.unbindInstanceAttributes = function () {
  13515. var boundBuffer;
  13516. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13517. var instancesBuffer = this._currentInstanceBuffers[i];
  13518. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13519. boundBuffer = instancesBuffer;
  13520. this.bindArrayBuffer(instancesBuffer);
  13521. }
  13522. var offsetLocation = this._currentInstanceLocations[i];
  13523. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13524. }
  13525. this._currentInstanceBuffers.length = 0;
  13526. this._currentInstanceLocations.length = 0;
  13527. };
  13528. /**
  13529. * Release and free the memory of a vertex array object
  13530. * @param vao defines the vertex array object to delete
  13531. */
  13532. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13533. this._gl.deleteVertexArray(vao);
  13534. };
  13535. /** @hidden */
  13536. Engine.prototype._releaseBuffer = function (buffer) {
  13537. buffer.references--;
  13538. if (buffer.references === 0) {
  13539. this._gl.deleteBuffer(buffer);
  13540. return true;
  13541. }
  13542. return false;
  13543. };
  13544. /**
  13545. * Creates a webGL buffer to use with instanciation
  13546. * @param capacity defines the size of the buffer
  13547. * @returns the webGL buffer
  13548. */
  13549. Engine.prototype.createInstancesBuffer = function (capacity) {
  13550. var buffer = this._gl.createBuffer();
  13551. if (!buffer) {
  13552. throw new Error("Unable to create instance buffer");
  13553. }
  13554. buffer.capacity = capacity;
  13555. this.bindArrayBuffer(buffer);
  13556. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13557. return buffer;
  13558. };
  13559. /**
  13560. * Delete a webGL buffer used with instanciation
  13561. * @param buffer defines the webGL buffer to delete
  13562. */
  13563. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13564. this._gl.deleteBuffer(buffer);
  13565. };
  13566. /**
  13567. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13568. * @param instancesBuffer defines the webGL buffer to update and bind
  13569. * @param data defines the data to store in the buffer
  13570. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13571. */
  13572. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13573. this.bindArrayBuffer(instancesBuffer);
  13574. if (data) {
  13575. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13576. }
  13577. if (offsetLocations[0].index !== undefined) {
  13578. var stride = 0;
  13579. for (var i = 0; i < offsetLocations.length; i++) {
  13580. var ai = offsetLocations[i];
  13581. stride += ai.attributeSize * 4;
  13582. }
  13583. for (var i = 0; i < offsetLocations.length; i++) {
  13584. var ai = offsetLocations[i];
  13585. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13586. this._gl.enableVertexAttribArray(ai.index);
  13587. this._vertexAttribArraysEnabled[ai.index] = true;
  13588. }
  13589. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13590. this._gl.vertexAttribDivisor(ai.index, 1);
  13591. this._currentInstanceLocations.push(ai.index);
  13592. this._currentInstanceBuffers.push(instancesBuffer);
  13593. }
  13594. }
  13595. else {
  13596. for (var index = 0; index < 4; index++) {
  13597. var offsetLocation = offsetLocations[index];
  13598. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13599. this._gl.enableVertexAttribArray(offsetLocation);
  13600. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13601. }
  13602. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13603. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13604. this._currentInstanceLocations.push(offsetLocation);
  13605. this._currentInstanceBuffers.push(instancesBuffer);
  13606. }
  13607. }
  13608. };
  13609. /**
  13610. * Apply all cached states (depth, culling, stencil and alpha)
  13611. */
  13612. Engine.prototype.applyStates = function () {
  13613. this._depthCullingState.apply(this._gl);
  13614. this._stencilState.apply(this._gl);
  13615. this._alphaState.apply(this._gl);
  13616. };
  13617. /**
  13618. * Send a draw order
  13619. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13620. * @param indexStart defines the starting index
  13621. * @param indexCount defines the number of index to draw
  13622. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13623. */
  13624. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13625. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13626. };
  13627. /**
  13628. * Draw a list of points
  13629. * @param verticesStart defines the index of first vertex to draw
  13630. * @param verticesCount defines the count of vertices to draw
  13631. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13632. */
  13633. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13634. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13635. };
  13636. /**
  13637. * Draw a list of unindexed primitives
  13638. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13639. * @param verticesStart defines the index of first vertex to draw
  13640. * @param verticesCount defines the count of vertices to draw
  13641. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13642. */
  13643. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13644. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13645. };
  13646. /**
  13647. * Draw a list of indexed primitives
  13648. * @param fillMode defines the primitive to use
  13649. * @param indexStart defines the starting index
  13650. * @param indexCount defines the number of index to draw
  13651. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13652. */
  13653. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13654. // Apply states
  13655. this.applyStates();
  13656. this._drawCalls.addCount(1, false);
  13657. // Render
  13658. var drawMode = this._drawMode(fillMode);
  13659. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13660. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13661. if (instancesCount) {
  13662. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13663. }
  13664. else {
  13665. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13666. }
  13667. };
  13668. /**
  13669. * Draw a list of unindexed primitives
  13670. * @param fillMode defines the primitive to use
  13671. * @param verticesStart defines the index of first vertex to draw
  13672. * @param verticesCount defines the count of vertices to draw
  13673. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13674. */
  13675. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13676. // Apply states
  13677. this.applyStates();
  13678. this._drawCalls.addCount(1, false);
  13679. var drawMode = this._drawMode(fillMode);
  13680. if (instancesCount) {
  13681. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13682. }
  13683. else {
  13684. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13685. }
  13686. };
  13687. Engine.prototype._drawMode = function (fillMode) {
  13688. switch (fillMode) {
  13689. // Triangle views
  13690. case BABYLON.Material.TriangleFillMode:
  13691. return this._gl.TRIANGLES;
  13692. case BABYLON.Material.PointFillMode:
  13693. return this._gl.POINTS;
  13694. case BABYLON.Material.WireFrameFillMode:
  13695. return this._gl.LINES;
  13696. // Draw modes
  13697. case BABYLON.Material.PointListDrawMode:
  13698. return this._gl.POINTS;
  13699. case BABYLON.Material.LineListDrawMode:
  13700. return this._gl.LINES;
  13701. case BABYLON.Material.LineLoopDrawMode:
  13702. return this._gl.LINE_LOOP;
  13703. case BABYLON.Material.LineStripDrawMode:
  13704. return this._gl.LINE_STRIP;
  13705. case BABYLON.Material.TriangleStripDrawMode:
  13706. return this._gl.TRIANGLE_STRIP;
  13707. case BABYLON.Material.TriangleFanDrawMode:
  13708. return this._gl.TRIANGLE_FAN;
  13709. default:
  13710. return this._gl.TRIANGLES;
  13711. }
  13712. };
  13713. // Shaders
  13714. /** @hidden */
  13715. Engine.prototype._releaseEffect = function (effect) {
  13716. if (this._compiledEffects[effect._key]) {
  13717. delete this._compiledEffects[effect._key];
  13718. this._deleteProgram(effect.getProgram());
  13719. }
  13720. };
  13721. /** @hidden */
  13722. Engine.prototype._deleteProgram = function (program) {
  13723. if (program) {
  13724. program.__SPECTOR_rebuildProgram = null;
  13725. if (program.transformFeedback) {
  13726. this.deleteTransformFeedback(program.transformFeedback);
  13727. program.transformFeedback = null;
  13728. }
  13729. this._gl.deleteProgram(program);
  13730. }
  13731. };
  13732. /**
  13733. * Create a new effect (used to store vertex/fragment shaders)
  13734. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13735. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13736. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13737. * @param samplers defines an array of string used to represent textures
  13738. * @param defines defines the string containing the defines to use to compile the shaders
  13739. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13740. * @param onCompiled defines a function to call when the effect creation is successful
  13741. * @param onError defines a function to call when the effect creation has failed
  13742. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13743. * @returns the new Effect
  13744. */
  13745. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13746. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13747. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13748. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13749. if (this._compiledEffects[name]) {
  13750. var compiledEffect = this._compiledEffects[name];
  13751. if (onCompiled && compiledEffect.isReady()) {
  13752. onCompiled(compiledEffect);
  13753. }
  13754. return compiledEffect;
  13755. }
  13756. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13757. effect._key = name;
  13758. this._compiledEffects[name] = effect;
  13759. return effect;
  13760. };
  13761. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13762. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13763. };
  13764. ;
  13765. Engine.prototype._compileRawShader = function (source, type) {
  13766. var gl = this._gl;
  13767. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13768. gl.shaderSource(shader, source);
  13769. gl.compileShader(shader);
  13770. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13771. var log = gl.getShaderInfoLog(shader);
  13772. if (log) {
  13773. throw new Error(log);
  13774. }
  13775. }
  13776. if (!shader) {
  13777. throw new Error("Something went wrong while compile the shader.");
  13778. }
  13779. return shader;
  13780. };
  13781. ;
  13782. /**
  13783. * Directly creates a webGL program
  13784. * @param vertexCode defines the vertex shader code to use
  13785. * @param fragmentCode defines the fragment shader code to use
  13786. * @param context defines the webGL context to use (if not set, the current one will be used)
  13787. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13788. * @returns the new webGL program
  13789. */
  13790. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13791. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13792. context = context || this._gl;
  13793. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13794. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13795. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13796. };
  13797. /**
  13798. * Creates a webGL program
  13799. * @param vertexCode defines the vertex shader code to use
  13800. * @param fragmentCode defines the fragment shader code to use
  13801. * @param defines defines the string containing the defines to use to compile the shaders
  13802. * @param context defines the webGL context to use (if not set, the current one will be used)
  13803. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13804. * @returns the new webGL program
  13805. */
  13806. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13807. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13808. context = context || this._gl;
  13809. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13810. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13811. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13812. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13813. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13814. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13815. return program;
  13816. };
  13817. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13818. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13819. var shaderProgram = context.createProgram();
  13820. if (!shaderProgram) {
  13821. throw new Error("Unable to create program");
  13822. }
  13823. context.attachShader(shaderProgram, vertexShader);
  13824. context.attachShader(shaderProgram, fragmentShader);
  13825. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13826. var transformFeedback = this.createTransformFeedback();
  13827. this.bindTransformFeedback(transformFeedback);
  13828. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13829. shaderProgram.transformFeedback = transformFeedback;
  13830. }
  13831. context.linkProgram(shaderProgram);
  13832. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13833. this.bindTransformFeedback(null);
  13834. }
  13835. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13836. if (!linked) {
  13837. var error = context.getProgramInfoLog(shaderProgram);
  13838. if (error) {
  13839. throw new Error(error);
  13840. }
  13841. }
  13842. if (this.validateShaderPrograms) {
  13843. context.validateProgram(shaderProgram);
  13844. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13845. if (!validated) {
  13846. var error = context.getProgramInfoLog(shaderProgram);
  13847. if (error) {
  13848. throw new Error(error);
  13849. }
  13850. }
  13851. }
  13852. context.deleteShader(vertexShader);
  13853. context.deleteShader(fragmentShader);
  13854. return shaderProgram;
  13855. };
  13856. /**
  13857. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13858. * @param shaderProgram defines the webGL program to use
  13859. * @param uniformsNames defines the list of uniform names
  13860. * @returns an array of webGL uniform locations
  13861. */
  13862. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13863. var results = new Array();
  13864. for (var index = 0; index < uniformsNames.length; index++) {
  13865. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13866. }
  13867. return results;
  13868. };
  13869. /**
  13870. * Gets the lsit of active attributes for a given webGL program
  13871. * @param shaderProgram defines the webGL program to use
  13872. * @param attributesNames defines the list of attribute names to get
  13873. * @returns an array of indices indicating the offset of each attribute
  13874. */
  13875. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13876. var results = [];
  13877. for (var index = 0; index < attributesNames.length; index++) {
  13878. try {
  13879. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13880. }
  13881. catch (e) {
  13882. results.push(-1);
  13883. }
  13884. }
  13885. return results;
  13886. };
  13887. /**
  13888. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13889. * @param effect defines the effect to activate
  13890. */
  13891. Engine.prototype.enableEffect = function (effect) {
  13892. if (!effect || effect === this._currentEffect) {
  13893. return;
  13894. }
  13895. // Use program
  13896. this.bindSamplers(effect);
  13897. this._currentEffect = effect;
  13898. if (effect.onBind) {
  13899. effect.onBind(effect);
  13900. }
  13901. if (effect._onBindObservable) {
  13902. effect._onBindObservable.notifyObservers(effect);
  13903. }
  13904. };
  13905. /**
  13906. * Set the value of an uniform to an array of int32
  13907. * @param uniform defines the webGL uniform location where to store the value
  13908. * @param array defines the array of int32 to store
  13909. */
  13910. Engine.prototype.setIntArray = function (uniform, array) {
  13911. if (!uniform)
  13912. return;
  13913. this._gl.uniform1iv(uniform, array);
  13914. };
  13915. /**
  13916. * Set the value of an uniform to an array of int32 (stored as vec2)
  13917. * @param uniform defines the webGL uniform location where to store the value
  13918. * @param array defines the array of int32 to store
  13919. */
  13920. Engine.prototype.setIntArray2 = function (uniform, array) {
  13921. if (!uniform || array.length % 2 !== 0)
  13922. return;
  13923. this._gl.uniform2iv(uniform, array);
  13924. };
  13925. /**
  13926. * Set the value of an uniform to an array of int32 (stored as vec3)
  13927. * @param uniform defines the webGL uniform location where to store the value
  13928. * @param array defines the array of int32 to store
  13929. */
  13930. Engine.prototype.setIntArray3 = function (uniform, array) {
  13931. if (!uniform || array.length % 3 !== 0)
  13932. return;
  13933. this._gl.uniform3iv(uniform, array);
  13934. };
  13935. /**
  13936. * Set the value of an uniform to an array of int32 (stored as vec4)
  13937. * @param uniform defines the webGL uniform location where to store the value
  13938. * @param array defines the array of int32 to store
  13939. */
  13940. Engine.prototype.setIntArray4 = function (uniform, array) {
  13941. if (!uniform || array.length % 4 !== 0)
  13942. return;
  13943. this._gl.uniform4iv(uniform, array);
  13944. };
  13945. /**
  13946. * Set the value of an uniform to an array of float32
  13947. * @param uniform defines the webGL uniform location where to store the value
  13948. * @param array defines the array of float32 to store
  13949. */
  13950. Engine.prototype.setFloatArray = function (uniform, array) {
  13951. if (!uniform)
  13952. return;
  13953. this._gl.uniform1fv(uniform, array);
  13954. };
  13955. /**
  13956. * Set the value of an uniform to an array of float32 (stored as vec2)
  13957. * @param uniform defines the webGL uniform location where to store the value
  13958. * @param array defines the array of float32 to store
  13959. */
  13960. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13961. if (!uniform || array.length % 2 !== 0)
  13962. return;
  13963. this._gl.uniform2fv(uniform, array);
  13964. };
  13965. /**
  13966. * Set the value of an uniform to an array of float32 (stored as vec3)
  13967. * @param uniform defines the webGL uniform location where to store the value
  13968. * @param array defines the array of float32 to store
  13969. */
  13970. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13971. if (!uniform || array.length % 3 !== 0)
  13972. return;
  13973. this._gl.uniform3fv(uniform, array);
  13974. };
  13975. /**
  13976. * Set the value of an uniform to an array of float32 (stored as vec4)
  13977. * @param uniform defines the webGL uniform location where to store the value
  13978. * @param array defines the array of float32 to store
  13979. */
  13980. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13981. if (!uniform || array.length % 4 !== 0)
  13982. return;
  13983. this._gl.uniform4fv(uniform, array);
  13984. };
  13985. /**
  13986. * Set the value of an uniform to an array of number
  13987. * @param uniform defines the webGL uniform location where to store the value
  13988. * @param array defines the array of number to store
  13989. */
  13990. Engine.prototype.setArray = function (uniform, array) {
  13991. if (!uniform)
  13992. return;
  13993. this._gl.uniform1fv(uniform, array);
  13994. };
  13995. /**
  13996. * Set the value of an uniform to an array of number (stored as vec2)
  13997. * @param uniform defines the webGL uniform location where to store the value
  13998. * @param array defines the array of number to store
  13999. */
  14000. Engine.prototype.setArray2 = function (uniform, array) {
  14001. if (!uniform || array.length % 2 !== 0)
  14002. return;
  14003. this._gl.uniform2fv(uniform, array);
  14004. };
  14005. /**
  14006. * Set the value of an uniform to an array of number (stored as vec3)
  14007. * @param uniform defines the webGL uniform location where to store the value
  14008. * @param array defines the array of number to store
  14009. */
  14010. Engine.prototype.setArray3 = function (uniform, array) {
  14011. if (!uniform || array.length % 3 !== 0)
  14012. return;
  14013. this._gl.uniform3fv(uniform, array);
  14014. };
  14015. /**
  14016. * Set the value of an uniform to an array of number (stored as vec4)
  14017. * @param uniform defines the webGL uniform location where to store the value
  14018. * @param array defines the array of number to store
  14019. */
  14020. Engine.prototype.setArray4 = function (uniform, array) {
  14021. if (!uniform || array.length % 4 !== 0)
  14022. return;
  14023. this._gl.uniform4fv(uniform, array);
  14024. };
  14025. /**
  14026. * Set the value of an uniform to an array of float32 (stored as matrices)
  14027. * @param uniform defines the webGL uniform location where to store the value
  14028. * @param matrices defines the array of float32 to store
  14029. */
  14030. Engine.prototype.setMatrices = function (uniform, matrices) {
  14031. if (!uniform)
  14032. return;
  14033. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14034. };
  14035. /**
  14036. * Set the value of an uniform to a matrix
  14037. * @param uniform defines the webGL uniform location where to store the value
  14038. * @param matrix defines the matrix to store
  14039. */
  14040. Engine.prototype.setMatrix = function (uniform, matrix) {
  14041. if (!uniform)
  14042. return;
  14043. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14044. };
  14045. /**
  14046. * Set the value of an uniform to a matrix (3x3)
  14047. * @param uniform defines the webGL uniform location where to store the value
  14048. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14049. */
  14050. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14051. if (!uniform)
  14052. return;
  14053. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14054. };
  14055. /**
  14056. * Set the value of an uniform to a matrix (2x2)
  14057. * @param uniform defines the webGL uniform location where to store the value
  14058. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14059. */
  14060. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14061. if (!uniform)
  14062. return;
  14063. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14064. };
  14065. /**
  14066. * Set the value of an uniform to a number (int)
  14067. * @param uniform defines the webGL uniform location where to store the value
  14068. * @param value defines the int number to store
  14069. */
  14070. Engine.prototype.setInt = function (uniform, value) {
  14071. if (!uniform)
  14072. return;
  14073. this._gl.uniform1i(uniform, value);
  14074. };
  14075. /**
  14076. * Set the value of an uniform to a number (float)
  14077. * @param uniform defines the webGL uniform location where to store the value
  14078. * @param value defines the float number to store
  14079. */
  14080. Engine.prototype.setFloat = function (uniform, value) {
  14081. if (!uniform)
  14082. return;
  14083. this._gl.uniform1f(uniform, value);
  14084. };
  14085. /**
  14086. * Set the value of an uniform to a vec2
  14087. * @param uniform defines the webGL uniform location where to store the value
  14088. * @param x defines the 1st component of the value
  14089. * @param y defines the 2nd component of the value
  14090. */
  14091. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14092. if (!uniform)
  14093. return;
  14094. this._gl.uniform2f(uniform, x, y);
  14095. };
  14096. /**
  14097. * Set the value of an uniform to a vec3
  14098. * @param uniform defines the webGL uniform location where to store the value
  14099. * @param x defines the 1st component of the value
  14100. * @param y defines the 2nd component of the value
  14101. * @param z defines the 3rd component of the value
  14102. */
  14103. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14104. if (!uniform)
  14105. return;
  14106. this._gl.uniform3f(uniform, x, y, z);
  14107. };
  14108. /**
  14109. * Set the value of an uniform to a boolean
  14110. * @param uniform defines the webGL uniform location where to store the value
  14111. * @param bool defines the boolean to store
  14112. */
  14113. Engine.prototype.setBool = function (uniform, bool) {
  14114. if (!uniform)
  14115. return;
  14116. this._gl.uniform1i(uniform, bool);
  14117. };
  14118. /**
  14119. * Set the value of an uniform to a vec4
  14120. * @param uniform defines the webGL uniform location where to store the value
  14121. * @param x defines the 1st component of the value
  14122. * @param y defines the 2nd component of the value
  14123. * @param z defines the 3rd component of the value
  14124. * @param w defines the 4th component of the value
  14125. */
  14126. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14127. if (!uniform)
  14128. return;
  14129. this._gl.uniform4f(uniform, x, y, z, w);
  14130. };
  14131. /**
  14132. * Set the value of an uniform to a Color3
  14133. * @param uniform defines the webGL uniform location where to store the value
  14134. * @param color3 defines the color to store
  14135. */
  14136. Engine.prototype.setColor3 = function (uniform, color3) {
  14137. if (!uniform)
  14138. return;
  14139. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14140. };
  14141. /**
  14142. * Set the value of an uniform to a Color3 and an alpha value
  14143. * @param uniform defines the webGL uniform location where to store the value
  14144. * @param color3 defines the color to store
  14145. * @param alpha defines the alpha component to store
  14146. */
  14147. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14148. if (!uniform)
  14149. return;
  14150. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14151. };
  14152. /**
  14153. * Sets a Color4 on a uniform variable
  14154. * @param uniform defines the uniform location
  14155. * @param color4 defines the value to be set
  14156. */
  14157. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14158. if (!uniform)
  14159. return;
  14160. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14161. };
  14162. // States
  14163. /**
  14164. * Set various states to the webGL context
  14165. * @param culling defines backface culling state
  14166. * @param zOffset defines the value to apply to zOffset (0 by default)
  14167. * @param force defines if states must be applied even if cache is up to date
  14168. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14169. */
  14170. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14171. if (zOffset === void 0) { zOffset = 0; }
  14172. if (reverseSide === void 0) { reverseSide = false; }
  14173. // Culling
  14174. if (this._depthCullingState.cull !== culling || force) {
  14175. this._depthCullingState.cull = culling;
  14176. }
  14177. // Cull face
  14178. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14179. if (this._depthCullingState.cullFace !== cullFace || force) {
  14180. this._depthCullingState.cullFace = cullFace;
  14181. }
  14182. // Z offset
  14183. this.setZOffset(zOffset);
  14184. // Front face
  14185. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14186. if (this._depthCullingState.frontFace !== frontFace || force) {
  14187. this._depthCullingState.frontFace = frontFace;
  14188. }
  14189. };
  14190. /**
  14191. * Set the z offset to apply to current rendering
  14192. * @param value defines the offset to apply
  14193. */
  14194. Engine.prototype.setZOffset = function (value) {
  14195. this._depthCullingState.zOffset = value;
  14196. };
  14197. /**
  14198. * Gets the current value of the zOffset
  14199. * @returns the current zOffset state
  14200. */
  14201. Engine.prototype.getZOffset = function () {
  14202. return this._depthCullingState.zOffset;
  14203. };
  14204. /**
  14205. * Enable or disable depth buffering
  14206. * @param enable defines the state to set
  14207. */
  14208. Engine.prototype.setDepthBuffer = function (enable) {
  14209. this._depthCullingState.depthTest = enable;
  14210. };
  14211. /**
  14212. * Gets a boolean indicating if depth writing is enabled
  14213. * @returns the current depth writing state
  14214. */
  14215. Engine.prototype.getDepthWrite = function () {
  14216. return this._depthCullingState.depthMask;
  14217. };
  14218. /**
  14219. * Enable or disable depth writing
  14220. * @param enable defines the state to set
  14221. */
  14222. Engine.prototype.setDepthWrite = function (enable) {
  14223. this._depthCullingState.depthMask = enable;
  14224. };
  14225. /**
  14226. * Enable or disable color writing
  14227. * @param enable defines the state to set
  14228. */
  14229. Engine.prototype.setColorWrite = function (enable) {
  14230. this._gl.colorMask(enable, enable, enable, enable);
  14231. this._colorWrite = enable;
  14232. };
  14233. /**
  14234. * Gets a boolean indicating if color writing is enabled
  14235. * @returns the current color writing state
  14236. */
  14237. Engine.prototype.getColorWrite = function () {
  14238. return this._colorWrite;
  14239. };
  14240. /**
  14241. * Sets alpha constants used by some alpha blending modes
  14242. * @param r defines the red component
  14243. * @param g defines the green component
  14244. * @param b defines the blue component
  14245. * @param a defines the alpha component
  14246. */
  14247. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14248. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14249. };
  14250. /**
  14251. * Sets the current alpha mode
  14252. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14253. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14254. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14255. */
  14256. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14257. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14258. if (this._alphaMode === mode) {
  14259. return;
  14260. }
  14261. switch (mode) {
  14262. case Engine.ALPHA_DISABLE:
  14263. this._alphaState.alphaBlend = false;
  14264. break;
  14265. case Engine.ALPHA_PREMULTIPLIED:
  14266. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14267. this._alphaState.alphaBlend = true;
  14268. break;
  14269. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14270. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14271. this._alphaState.alphaBlend = true;
  14272. break;
  14273. case Engine.ALPHA_COMBINE:
  14274. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14275. this._alphaState.alphaBlend = true;
  14276. break;
  14277. case Engine.ALPHA_ONEONE:
  14278. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14279. this._alphaState.alphaBlend = true;
  14280. break;
  14281. case Engine.ALPHA_ADD:
  14282. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14283. this._alphaState.alphaBlend = true;
  14284. break;
  14285. case Engine.ALPHA_SUBTRACT:
  14286. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14287. this._alphaState.alphaBlend = true;
  14288. break;
  14289. case Engine.ALPHA_MULTIPLY:
  14290. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14291. this._alphaState.alphaBlend = true;
  14292. break;
  14293. case Engine.ALPHA_MAXIMIZED:
  14294. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14295. this._alphaState.alphaBlend = true;
  14296. break;
  14297. case Engine.ALPHA_INTERPOLATE:
  14298. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14299. this._alphaState.alphaBlend = true;
  14300. break;
  14301. case Engine.ALPHA_SCREENMODE:
  14302. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14303. this._alphaState.alphaBlend = true;
  14304. break;
  14305. }
  14306. if (!noDepthWriteChange) {
  14307. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14308. }
  14309. this._alphaMode = mode;
  14310. };
  14311. /**
  14312. * Gets the current alpha mode
  14313. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14314. * @returns the current alpha mode
  14315. */
  14316. Engine.prototype.getAlphaMode = function () {
  14317. return this._alphaMode;
  14318. };
  14319. // Textures
  14320. /**
  14321. * Clears the list of texture accessible through engine.
  14322. * This can help preventing texture load conflict due to name collision.
  14323. */
  14324. Engine.prototype.clearInternalTexturesCache = function () {
  14325. this._internalTexturesCache = [];
  14326. };
  14327. /**
  14328. * Force the entire cache to be cleared
  14329. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14330. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14331. */
  14332. Engine.prototype.wipeCaches = function (bruteForce) {
  14333. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14334. return;
  14335. }
  14336. this._currentEffect = null;
  14337. this._viewportCached.x = 0;
  14338. this._viewportCached.y = 0;
  14339. this._viewportCached.z = 0;
  14340. this._viewportCached.w = 0;
  14341. if (bruteForce) {
  14342. this.resetTextureCache();
  14343. this._currentProgram = null;
  14344. this._stencilState.reset();
  14345. this._depthCullingState.reset();
  14346. this.setDepthFunctionToLessOrEqual();
  14347. this._alphaState.reset();
  14348. this._unpackFlipYCached = null;
  14349. }
  14350. this._resetVertexBufferBinding();
  14351. this._cachedIndexBuffer = null;
  14352. this._cachedEffectForVertexBuffers = null;
  14353. this._unbindVertexArrayObject();
  14354. this.bindIndexBuffer(null);
  14355. };
  14356. /**
  14357. * Set the compressed texture format to use, based on the formats you have, and the formats
  14358. * supported by the hardware / browser.
  14359. *
  14360. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14361. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14362. * to API arguments needed to compressed textures. This puts the burden on the container
  14363. * generator to house the arcane code for determining these for current & future formats.
  14364. *
  14365. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14366. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14367. *
  14368. * Note: The result of this call is not taken into account when a texture is base64.
  14369. *
  14370. * @param formatsAvailable defines the list of those format families you have created
  14371. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14372. *
  14373. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14374. * @returns The extension selected.
  14375. */
  14376. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14377. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14378. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14379. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14380. return this._textureFormatInUse = this._texturesSupported[i];
  14381. }
  14382. }
  14383. }
  14384. // actively set format to nothing, to allow this to be called more than once
  14385. // and possibly fail the 2nd time
  14386. this._textureFormatInUse = null;
  14387. return null;
  14388. };
  14389. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14390. var gl = this._gl;
  14391. var magFilter = gl.NEAREST;
  14392. var minFilter = gl.NEAREST;
  14393. switch (samplingMode) {
  14394. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14395. magFilter = gl.LINEAR;
  14396. if (generateMipMaps) {
  14397. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14398. }
  14399. else {
  14400. minFilter = gl.LINEAR;
  14401. }
  14402. break;
  14403. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14404. magFilter = gl.LINEAR;
  14405. if (generateMipMaps) {
  14406. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14407. }
  14408. else {
  14409. minFilter = gl.LINEAR;
  14410. }
  14411. break;
  14412. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14413. magFilter = gl.NEAREST;
  14414. if (generateMipMaps) {
  14415. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14416. }
  14417. else {
  14418. minFilter = gl.NEAREST;
  14419. }
  14420. break;
  14421. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14422. magFilter = gl.NEAREST;
  14423. if (generateMipMaps) {
  14424. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14425. }
  14426. else {
  14427. minFilter = gl.NEAREST;
  14428. }
  14429. break;
  14430. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14431. magFilter = gl.NEAREST;
  14432. if (generateMipMaps) {
  14433. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14434. }
  14435. else {
  14436. minFilter = gl.LINEAR;
  14437. }
  14438. break;
  14439. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14440. magFilter = gl.NEAREST;
  14441. if (generateMipMaps) {
  14442. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14443. }
  14444. else {
  14445. minFilter = gl.LINEAR;
  14446. }
  14447. break;
  14448. case Engine.TEXTURE_NEAREST_LINEAR:
  14449. magFilter = gl.NEAREST;
  14450. minFilter = gl.LINEAR;
  14451. break;
  14452. case Engine.TEXTURE_NEAREST_NEAREST:
  14453. magFilter = gl.NEAREST;
  14454. minFilter = gl.NEAREST;
  14455. break;
  14456. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14457. magFilter = gl.LINEAR;
  14458. if (generateMipMaps) {
  14459. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14460. }
  14461. else {
  14462. minFilter = gl.NEAREST;
  14463. }
  14464. break;
  14465. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14466. magFilter = gl.LINEAR;
  14467. if (generateMipMaps) {
  14468. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14469. }
  14470. else {
  14471. minFilter = gl.NEAREST;
  14472. }
  14473. break;
  14474. case Engine.TEXTURE_LINEAR_LINEAR:
  14475. magFilter = gl.LINEAR;
  14476. minFilter = gl.LINEAR;
  14477. break;
  14478. case Engine.TEXTURE_LINEAR_NEAREST:
  14479. magFilter = gl.LINEAR;
  14480. minFilter = gl.NEAREST;
  14481. break;
  14482. }
  14483. return {
  14484. min: minFilter,
  14485. mag: magFilter
  14486. };
  14487. };
  14488. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14489. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14490. var img;
  14491. var onload = function () {
  14492. loadedImages[index] = img;
  14493. loadedImages._internalCount++;
  14494. if (scene) {
  14495. scene._removePendingData(img);
  14496. }
  14497. if (loadedImages._internalCount === 6) {
  14498. onfinish(loadedImages);
  14499. }
  14500. };
  14501. var onerror = function (message, exception) {
  14502. if (scene) {
  14503. scene._removePendingData(img);
  14504. }
  14505. if (onErrorCallBack) {
  14506. onErrorCallBack(message, exception);
  14507. }
  14508. };
  14509. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14510. if (scene) {
  14511. scene._addPendingData(img);
  14512. }
  14513. };
  14514. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14515. if (onError === void 0) { onError = null; }
  14516. var loadedImages = [];
  14517. loadedImages._internalCount = 0;
  14518. for (var index = 0; index < 6; index++) {
  14519. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14520. }
  14521. };
  14522. ;
  14523. /** @hidden */
  14524. Engine.prototype._createTexture = function () {
  14525. var texture = this._gl.createTexture();
  14526. if (!texture) {
  14527. throw new Error("Unable to create texture");
  14528. }
  14529. return texture;
  14530. };
  14531. /**
  14532. * Usually called from BABYLON.Texture.ts.
  14533. * Passed information to create a WebGLTexture
  14534. * @param urlArg defines a value which contains one of the following:
  14535. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14536. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14537. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14538. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14539. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14540. * @param scene needed for loading to the correct scene
  14541. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14542. * @param onLoad optional callback to be called upon successful completion
  14543. * @param onError optional callback to be called upon failure
  14544. * @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
  14545. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14546. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14547. * @param forcedExtension defines the extension to use to pick the right loader
  14548. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14549. */
  14550. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14551. var _this = this;
  14552. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14553. if (onLoad === void 0) { onLoad = null; }
  14554. if (onError === void 0) { onError = null; }
  14555. if (buffer === void 0) { buffer = null; }
  14556. if (fallback === void 0) { fallback = null; }
  14557. if (format === void 0) { format = null; }
  14558. if (forcedExtension === void 0) { forcedExtension = null; }
  14559. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14560. var fromData = url.substr(0, 5) === "data:";
  14561. var fromBlob = url.substr(0, 5) === "blob:";
  14562. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14563. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14564. // establish the file extension, if possible
  14565. var lastDot = url.lastIndexOf('.');
  14566. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14567. var loader = null;
  14568. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14569. var availableLoader = _a[_i];
  14570. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14571. loader = availableLoader;
  14572. break;
  14573. }
  14574. }
  14575. if (loader) {
  14576. url = loader.transformUrl(url, this._textureFormatInUse);
  14577. }
  14578. if (scene) {
  14579. scene._addPendingData(texture);
  14580. }
  14581. texture.url = url;
  14582. texture.generateMipMaps = !noMipmap;
  14583. texture.samplingMode = samplingMode;
  14584. texture.invertY = invertY;
  14585. if (!this._doNotHandleContextLost) {
  14586. // Keep a link to the buffer only if we plan to handle context lost
  14587. texture._buffer = buffer;
  14588. }
  14589. var onLoadObserver = null;
  14590. if (onLoad && !fallback) {
  14591. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14592. }
  14593. if (!fallback)
  14594. this._internalTexturesCache.push(texture);
  14595. var onInternalError = function (message, exception) {
  14596. if (scene) {
  14597. scene._removePendingData(texture);
  14598. }
  14599. var customFallback = false;
  14600. if (loader) {
  14601. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14602. if (fallbackUrl) {
  14603. // Add Back
  14604. customFallback = true;
  14605. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14606. }
  14607. }
  14608. if (!customFallback) {
  14609. if (onLoadObserver) {
  14610. texture.onLoadedObservable.remove(onLoadObserver);
  14611. }
  14612. if (BABYLON.Tools.UseFallbackTexture) {
  14613. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14614. }
  14615. }
  14616. if (onError) {
  14617. onError(message || "Unknown error", exception);
  14618. }
  14619. };
  14620. // processing for non-image formats
  14621. if (loader) {
  14622. var callback = function (data) {
  14623. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14624. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14625. done();
  14626. return false;
  14627. }, samplingMode);
  14628. });
  14629. };
  14630. if (!buffer) {
  14631. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14632. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14633. });
  14634. }
  14635. else {
  14636. callback(buffer);
  14637. }
  14638. }
  14639. else {
  14640. var onload = function (img) {
  14641. if (fromBlob && !_this._doNotHandleContextLost) {
  14642. // We need to store the image if we need to rebuild the texture
  14643. // in case of a webgl context lost
  14644. texture._buffer = img;
  14645. }
  14646. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14647. var gl = _this._gl;
  14648. var isPot = (img.width === potWidth && img.height === potHeight);
  14649. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14650. if (isPot) {
  14651. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14652. return false;
  14653. }
  14654. var maxTextureSize = _this._caps.maxTextureSize;
  14655. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14656. _this._prepareWorkingCanvas();
  14657. if (!_this._workingCanvas || !_this._workingContext) {
  14658. return false;
  14659. }
  14660. _this._workingCanvas.width = potWidth;
  14661. _this._workingCanvas.height = potHeight;
  14662. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14663. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14664. texture.width = potWidth;
  14665. texture.height = potHeight;
  14666. return false;
  14667. }
  14668. else {
  14669. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14670. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14671. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14672. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14673. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14674. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14675. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14676. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14677. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14678. _this._releaseTexture(source_1);
  14679. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14680. continuationCallback();
  14681. });
  14682. }
  14683. return true;
  14684. }, samplingMode);
  14685. };
  14686. if (!fromData || isBase64) {
  14687. if (buffer instanceof HTMLImageElement) {
  14688. onload(buffer);
  14689. }
  14690. else {
  14691. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14692. }
  14693. }
  14694. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14695. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14696. }
  14697. else {
  14698. onload(buffer);
  14699. }
  14700. }
  14701. return texture;
  14702. };
  14703. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14704. var _this = this;
  14705. var rtt = this.createRenderTargetTexture({
  14706. width: destination.width,
  14707. height: destination.height,
  14708. }, {
  14709. generateMipMaps: false,
  14710. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14711. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14712. generateDepthBuffer: false,
  14713. generateStencilBuffer: false
  14714. });
  14715. if (!this._rescalePostProcess) {
  14716. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14717. }
  14718. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14719. _this._rescalePostProcess.onApply = function (effect) {
  14720. effect._bindTexture("textureSampler", source);
  14721. };
  14722. var hostingScene = scene;
  14723. if (!hostingScene) {
  14724. hostingScene = _this.scenes[_this.scenes.length - 1];
  14725. }
  14726. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14727. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14728. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14729. _this.unBindFramebuffer(rtt);
  14730. _this._releaseTexture(rtt);
  14731. if (onComplete) {
  14732. onComplete();
  14733. }
  14734. });
  14735. };
  14736. /**
  14737. * Update a raw texture
  14738. * @param texture defines the texture to update
  14739. * @param data defines the data to store in the texture
  14740. * @param format defines the format of the data
  14741. * @param invertY defines if data must be stored with Y axis inverted
  14742. * @param compression defines the compression used (null by default)
  14743. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14744. */
  14745. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14746. if (compression === void 0) { compression = null; }
  14747. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14748. if (!texture) {
  14749. return;
  14750. }
  14751. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14752. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14753. // babylon's internalFormat but gl's texImage2D format
  14754. var internalFormat = this._getInternalFormat(format);
  14755. var textureType = this._getWebGLTextureType(type);
  14756. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14757. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14758. if (!this._doNotHandleContextLost) {
  14759. texture._bufferView = data;
  14760. texture.format = format;
  14761. texture.type = type;
  14762. texture.invertY = invertY;
  14763. texture._compression = compression;
  14764. }
  14765. if (texture.width % 4 !== 0) {
  14766. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14767. }
  14768. if (compression && data) {
  14769. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14770. }
  14771. else {
  14772. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14773. }
  14774. if (texture.generateMipMaps) {
  14775. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14776. }
  14777. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14778. // this.resetTextureCache();
  14779. texture.isReady = true;
  14780. };
  14781. /**
  14782. * Creates a raw texture
  14783. * @param data defines the data to store in the texture
  14784. * @param width defines the width of the texture
  14785. * @param height defines the height of the texture
  14786. * @param format defines the format of the data
  14787. * @param generateMipMaps defines if the engine should generate the mip levels
  14788. * @param invertY defines if data must be stored with Y axis inverted
  14789. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14790. * @param compression defines the compression used (null by default)
  14791. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14792. * @returns the raw texture inside an InternalTexture
  14793. */
  14794. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14795. if (compression === void 0) { compression = null; }
  14796. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14797. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14798. texture.baseWidth = width;
  14799. texture.baseHeight = height;
  14800. texture.width = width;
  14801. texture.height = height;
  14802. texture.format = format;
  14803. texture.generateMipMaps = generateMipMaps;
  14804. texture.samplingMode = samplingMode;
  14805. texture.invertY = invertY;
  14806. texture._compression = compression;
  14807. texture.type = type;
  14808. if (!this._doNotHandleContextLost) {
  14809. texture._bufferView = data;
  14810. }
  14811. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14812. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14813. // Filters
  14814. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14815. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14816. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14817. if (generateMipMaps) {
  14818. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14819. }
  14820. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14821. this._internalTexturesCache.push(texture);
  14822. return texture;
  14823. };
  14824. /** @hidden */
  14825. Engine.prototype._unpackFlipY = function (value) {
  14826. if (this._unpackFlipYCached !== value) {
  14827. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14828. if (this.enableUnpackFlipYCached) {
  14829. this._unpackFlipYCached = value;
  14830. }
  14831. }
  14832. };
  14833. /** @hidden */
  14834. Engine.prototype._getUnpackAlignement = function () {
  14835. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14836. };
  14837. /**
  14838. * Creates a dynamic texture
  14839. * @param width defines the width of the texture
  14840. * @param height defines the height of the texture
  14841. * @param generateMipMaps defines if the engine should generate the mip levels
  14842. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14843. * @returns the dynamic texture inside an InternalTexture
  14844. */
  14845. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14846. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14847. texture.baseWidth = width;
  14848. texture.baseHeight = height;
  14849. if (generateMipMaps) {
  14850. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14851. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14852. }
  14853. // this.resetTextureCache();
  14854. texture.width = width;
  14855. texture.height = height;
  14856. texture.isReady = false;
  14857. texture.generateMipMaps = generateMipMaps;
  14858. texture.samplingMode = samplingMode;
  14859. this.updateTextureSamplingMode(samplingMode, texture);
  14860. this._internalTexturesCache.push(texture);
  14861. return texture;
  14862. };
  14863. /**
  14864. * Update the sampling mode of a given texture
  14865. * @param samplingMode defines the required sampling mode
  14866. * @param texture defines the texture to update
  14867. */
  14868. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14869. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14870. if (texture.isCube) {
  14871. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14872. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14873. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14874. }
  14875. else if (texture.is3D) {
  14876. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14877. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14878. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14879. }
  14880. else {
  14881. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14882. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14883. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14884. }
  14885. texture.samplingMode = samplingMode;
  14886. };
  14887. /**
  14888. * Update the content of a dynamic texture
  14889. * @param texture defines the texture to update
  14890. * @param canvas defines the canvas containing the source
  14891. * @param invertY defines if data must be stored with Y axis inverted
  14892. * @param premulAlpha defines if alpha is stored as premultiplied
  14893. * @param format defines the format of the data
  14894. */
  14895. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14896. if (premulAlpha === void 0) { premulAlpha = false; }
  14897. if (!texture) {
  14898. return;
  14899. }
  14900. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14901. this._unpackFlipY(invertY);
  14902. if (premulAlpha) {
  14903. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14904. }
  14905. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14906. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14907. if (texture.generateMipMaps) {
  14908. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14909. }
  14910. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14911. if (premulAlpha) {
  14912. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14913. }
  14914. texture.isReady = true;
  14915. };
  14916. /**
  14917. * Update a video texture
  14918. * @param texture defines the texture to update
  14919. * @param video defines the video element to use
  14920. * @param invertY defines if data must be stored with Y axis inverted
  14921. */
  14922. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14923. if (!texture || texture._isDisabled) {
  14924. return;
  14925. }
  14926. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14927. this._unpackFlipY(!invertY); // Video are upside down by default
  14928. try {
  14929. // Testing video texture support
  14930. if (this._videoTextureSupported === undefined) {
  14931. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14932. if (this._gl.getError() !== 0) {
  14933. this._videoTextureSupported = false;
  14934. }
  14935. else {
  14936. this._videoTextureSupported = true;
  14937. }
  14938. }
  14939. // Copy video through the current working canvas if video texture is not supported
  14940. if (!this._videoTextureSupported) {
  14941. if (!texture._workingCanvas) {
  14942. texture._workingCanvas = document.createElement("canvas");
  14943. var context = texture._workingCanvas.getContext("2d");
  14944. if (!context) {
  14945. throw new Error("Unable to get 2d context");
  14946. }
  14947. texture._workingContext = context;
  14948. texture._workingCanvas.width = texture.width;
  14949. texture._workingCanvas.height = texture.height;
  14950. }
  14951. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14952. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14953. }
  14954. else {
  14955. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14956. }
  14957. if (texture.generateMipMaps) {
  14958. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14959. }
  14960. if (!wasPreviouslyBound) {
  14961. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14962. }
  14963. // this.resetTextureCache();
  14964. texture.isReady = true;
  14965. }
  14966. catch (ex) {
  14967. // Something unexpected
  14968. // Let's disable the texture
  14969. texture._isDisabled = true;
  14970. }
  14971. };
  14972. /**
  14973. * Updates a depth texture Comparison Mode and Function.
  14974. * If the comparison Function is equal to 0, the mode will be set to none.
  14975. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14976. * @param texture The texture to set the comparison function for
  14977. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14978. */
  14979. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14980. if (this.webGLVersion === 1) {
  14981. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14982. return;
  14983. }
  14984. var gl = this._gl;
  14985. if (texture.isCube) {
  14986. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14987. if (comparisonFunction === 0) {
  14988. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14989. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14990. }
  14991. else {
  14992. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14993. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14994. }
  14995. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14996. }
  14997. else {
  14998. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14999. if (comparisonFunction === 0) {
  15000. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15001. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15002. }
  15003. else {
  15004. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15005. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15006. }
  15007. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15008. }
  15009. texture._comparisonFunction = comparisonFunction;
  15010. };
  15011. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15012. var width = size.width || size;
  15013. var height = size.height || size;
  15014. internalTexture.baseWidth = width;
  15015. internalTexture.baseHeight = height;
  15016. internalTexture.width = width;
  15017. internalTexture.height = height;
  15018. internalTexture.isReady = true;
  15019. internalTexture.samples = 1;
  15020. internalTexture.generateMipMaps = false;
  15021. internalTexture._generateDepthBuffer = true;
  15022. internalTexture._generateStencilBuffer = generateStencil;
  15023. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15024. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15025. internalTexture._comparisonFunction = comparisonFunction;
  15026. var gl = this._gl;
  15027. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15028. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15029. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15030. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15031. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15032. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15033. if (comparisonFunction === 0) {
  15034. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15035. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15036. }
  15037. else {
  15038. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15039. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15040. }
  15041. };
  15042. /**
  15043. * Creates a depth stencil texture.
  15044. * This is only available in WebGL 2 or with the depth texture extension available.
  15045. * @param size The size of face edge in the texture.
  15046. * @param options The options defining the texture.
  15047. * @returns The texture
  15048. */
  15049. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15050. if (options.isCube) {
  15051. var width = size.width || size;
  15052. return this._createDepthStencilCubeTexture(width, options);
  15053. }
  15054. else {
  15055. return this._createDepthStencilTexture(size, options);
  15056. }
  15057. };
  15058. /**
  15059. * Creates a depth stencil texture.
  15060. * This is only available in WebGL 2 or with the depth texture extension available.
  15061. * @param size The size of face edge in the texture.
  15062. * @param options The options defining the texture.
  15063. * @returns The texture
  15064. */
  15065. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15066. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15067. if (!this._caps.depthTextureExtension) {
  15068. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15069. return internalTexture;
  15070. }
  15071. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15072. var gl = this._gl;
  15073. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15074. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15075. if (this.webGLVersion > 1) {
  15076. if (internalOptions.generateStencil) {
  15077. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15078. }
  15079. else {
  15080. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15081. }
  15082. }
  15083. else {
  15084. if (internalOptions.generateStencil) {
  15085. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15086. }
  15087. else {
  15088. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15089. }
  15090. }
  15091. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15092. return internalTexture;
  15093. };
  15094. /**
  15095. * Creates a depth stencil cube texture.
  15096. * This is only available in WebGL 2.
  15097. * @param size The size of face edge in the cube texture.
  15098. * @param options The options defining the cube texture.
  15099. * @returns The cube texture
  15100. */
  15101. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15102. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15103. internalTexture.isCube = true;
  15104. if (this.webGLVersion === 1) {
  15105. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15106. return internalTexture;
  15107. }
  15108. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15109. var gl = this._gl;
  15110. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15111. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15112. // Create the depth/stencil buffer
  15113. for (var face = 0; face < 6; face++) {
  15114. if (internalOptions.generateStencil) {
  15115. 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);
  15116. }
  15117. else {
  15118. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15119. }
  15120. }
  15121. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15122. return internalTexture;
  15123. };
  15124. /**
  15125. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15126. * @param renderTarget The render target to set the frame buffer for
  15127. */
  15128. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15129. // Create the framebuffer
  15130. var internalTexture = renderTarget.getInternalTexture();
  15131. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15132. return;
  15133. }
  15134. var gl = this._gl;
  15135. var depthStencilTexture = renderTarget.depthStencilTexture;
  15136. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15137. if (depthStencilTexture.isCube) {
  15138. if (depthStencilTexture._generateStencilBuffer) {
  15139. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15140. }
  15141. else {
  15142. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15143. }
  15144. }
  15145. else {
  15146. if (depthStencilTexture._generateStencilBuffer) {
  15147. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15148. }
  15149. else {
  15150. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15151. }
  15152. }
  15153. this.bindUnboundFramebuffer(null);
  15154. };
  15155. /**
  15156. * Creates a new render target texture
  15157. * @param size defines the size of the texture
  15158. * @param options defines the options used to create the texture
  15159. * @returns a new render target texture stored in an InternalTexture
  15160. */
  15161. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15162. var fullOptions = new RenderTargetCreationOptions();
  15163. if (options !== undefined && typeof options === "object") {
  15164. fullOptions.generateMipMaps = options.generateMipMaps;
  15165. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15166. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15167. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15168. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15169. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15170. }
  15171. else {
  15172. fullOptions.generateMipMaps = options;
  15173. fullOptions.generateDepthBuffer = true;
  15174. fullOptions.generateStencilBuffer = false;
  15175. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15176. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15177. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15178. }
  15179. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15180. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15181. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15182. }
  15183. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15184. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15185. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15186. }
  15187. var gl = this._gl;
  15188. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15189. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15190. var width = size.width || size;
  15191. var height = size.height || size;
  15192. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15193. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15194. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15195. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15196. }
  15197. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15198. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15201. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15202. // Create the framebuffer
  15203. var currentFrameBuffer = this._currentFramebuffer;
  15204. var framebuffer = gl.createFramebuffer();
  15205. this.bindUnboundFramebuffer(framebuffer);
  15206. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15207. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15208. if (fullOptions.generateMipMaps) {
  15209. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15210. }
  15211. // Unbind
  15212. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15213. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15214. this.bindUnboundFramebuffer(currentFrameBuffer);
  15215. texture._framebuffer = framebuffer;
  15216. texture.baseWidth = width;
  15217. texture.baseHeight = height;
  15218. texture.width = width;
  15219. texture.height = height;
  15220. texture.isReady = true;
  15221. texture.samples = 1;
  15222. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15223. texture.samplingMode = fullOptions.samplingMode;
  15224. texture.type = fullOptions.type;
  15225. texture.format = fullOptions.format;
  15226. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15227. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15228. // this.resetTextureCache();
  15229. this._internalTexturesCache.push(texture);
  15230. return texture;
  15231. };
  15232. /**
  15233. * Create a multi render target texture
  15234. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15235. * @param size defines the size of the texture
  15236. * @param options defines the creation options
  15237. * @returns the cube texture as an InternalTexture
  15238. */
  15239. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15240. var generateMipMaps = false;
  15241. var generateDepthBuffer = true;
  15242. var generateStencilBuffer = false;
  15243. var generateDepthTexture = false;
  15244. var textureCount = 1;
  15245. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15246. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15247. var types = new Array();
  15248. var samplingModes = new Array();
  15249. if (options !== undefined) {
  15250. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15251. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15252. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15253. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15254. textureCount = options.textureCount || 1;
  15255. if (options.types) {
  15256. types = options.types;
  15257. }
  15258. if (options.samplingModes) {
  15259. samplingModes = options.samplingModes;
  15260. }
  15261. }
  15262. var gl = this._gl;
  15263. // Create the framebuffer
  15264. var framebuffer = gl.createFramebuffer();
  15265. this.bindUnboundFramebuffer(framebuffer);
  15266. var width = size.width || size;
  15267. var height = size.height || size;
  15268. var textures = [];
  15269. var attachments = [];
  15270. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15271. for (var i = 0; i < textureCount; i++) {
  15272. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15273. var type = types[i] || defaultType;
  15274. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15275. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15276. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15277. }
  15278. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15279. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15280. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15281. }
  15282. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15283. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15284. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15285. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15286. }
  15287. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15288. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15289. textures.push(texture);
  15290. attachments.push(attachment);
  15291. gl.activeTexture(gl["TEXTURE" + i]);
  15292. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15293. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15294. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15296. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15297. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15298. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15299. if (generateMipMaps) {
  15300. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15301. }
  15302. // Unbind
  15303. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15304. texture._framebuffer = framebuffer;
  15305. texture._depthStencilBuffer = depthStencilBuffer;
  15306. texture.baseWidth = width;
  15307. texture.baseHeight = height;
  15308. texture.width = width;
  15309. texture.height = height;
  15310. texture.isReady = true;
  15311. texture.samples = 1;
  15312. texture.generateMipMaps = generateMipMaps;
  15313. texture.samplingMode = samplingMode;
  15314. texture.type = type;
  15315. texture._generateDepthBuffer = generateDepthBuffer;
  15316. texture._generateStencilBuffer = generateStencilBuffer;
  15317. texture._attachments = attachments;
  15318. this._internalTexturesCache.push(texture);
  15319. }
  15320. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15321. // Depth texture
  15322. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15323. gl.activeTexture(gl.TEXTURE0);
  15324. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15325. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15326. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15327. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15328. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15329. 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);
  15330. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15331. depthTexture._framebuffer = framebuffer;
  15332. depthTexture.baseWidth = width;
  15333. depthTexture.baseHeight = height;
  15334. depthTexture.width = width;
  15335. depthTexture.height = height;
  15336. depthTexture.isReady = true;
  15337. depthTexture.samples = 1;
  15338. depthTexture.generateMipMaps = generateMipMaps;
  15339. depthTexture.samplingMode = gl.NEAREST;
  15340. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15341. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15342. textures.push(depthTexture);
  15343. this._internalTexturesCache.push(depthTexture);
  15344. }
  15345. gl.drawBuffers(attachments);
  15346. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15347. this.bindUnboundFramebuffer(null);
  15348. this.resetTextureCache();
  15349. return textures;
  15350. };
  15351. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15352. if (samples === void 0) { samples = 1; }
  15353. var depthStencilBuffer = null;
  15354. var gl = this._gl;
  15355. // Create the depth/stencil buffer
  15356. if (generateStencilBuffer) {
  15357. depthStencilBuffer = gl.createRenderbuffer();
  15358. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15359. if (samples > 1) {
  15360. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15361. }
  15362. else {
  15363. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15364. }
  15365. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15366. }
  15367. else if (generateDepthBuffer) {
  15368. depthStencilBuffer = gl.createRenderbuffer();
  15369. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15370. if (samples > 1) {
  15371. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15372. }
  15373. else {
  15374. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15375. }
  15376. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15377. }
  15378. return depthStencilBuffer;
  15379. };
  15380. /**
  15381. * Updates the sample count of a render target texture
  15382. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15383. * @param texture defines the texture to update
  15384. * @param samples defines the sample count to set
  15385. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15386. */
  15387. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15388. if (this.webGLVersion < 2 || !texture) {
  15389. return 1;
  15390. }
  15391. if (texture.samples === samples) {
  15392. return samples;
  15393. }
  15394. var gl = this._gl;
  15395. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15396. // Dispose previous render buffers
  15397. if (texture._depthStencilBuffer) {
  15398. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15399. texture._depthStencilBuffer = null;
  15400. }
  15401. if (texture._MSAAFramebuffer) {
  15402. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15403. texture._MSAAFramebuffer = null;
  15404. }
  15405. if (texture._MSAARenderBuffer) {
  15406. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15407. texture._MSAARenderBuffer = null;
  15408. }
  15409. if (samples > 1) {
  15410. var framebuffer = gl.createFramebuffer();
  15411. if (!framebuffer) {
  15412. throw new Error("Unable to create multi sampled framebuffer");
  15413. }
  15414. texture._MSAAFramebuffer = framebuffer;
  15415. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15416. var colorRenderbuffer = gl.createRenderbuffer();
  15417. if (!colorRenderbuffer) {
  15418. throw new Error("Unable to create multi sampled framebuffer");
  15419. }
  15420. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15421. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15422. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15423. texture._MSAARenderBuffer = colorRenderbuffer;
  15424. }
  15425. else {
  15426. this.bindUnboundFramebuffer(texture._framebuffer);
  15427. }
  15428. texture.samples = samples;
  15429. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15430. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15431. this.bindUnboundFramebuffer(null);
  15432. return samples;
  15433. };
  15434. /**
  15435. * Update the sample count for a given multiple render target texture
  15436. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15437. * @param textures defines the textures to update
  15438. * @param samples defines the sample count to set
  15439. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15440. */
  15441. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15442. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15443. return 1;
  15444. }
  15445. if (textures[0].samples === samples) {
  15446. return samples;
  15447. }
  15448. var gl = this._gl;
  15449. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15450. // Dispose previous render buffers
  15451. if (textures[0]._depthStencilBuffer) {
  15452. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15453. textures[0]._depthStencilBuffer = null;
  15454. }
  15455. if (textures[0]._MSAAFramebuffer) {
  15456. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15457. textures[0]._MSAAFramebuffer = null;
  15458. }
  15459. for (var i = 0; i < textures.length; i++) {
  15460. if (textures[i]._MSAARenderBuffer) {
  15461. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15462. textures[i]._MSAARenderBuffer = null;
  15463. }
  15464. }
  15465. if (samples > 1) {
  15466. var framebuffer = gl.createFramebuffer();
  15467. if (!framebuffer) {
  15468. throw new Error("Unable to create multi sampled framebuffer");
  15469. }
  15470. this.bindUnboundFramebuffer(framebuffer);
  15471. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15472. var attachments = [];
  15473. for (var i = 0; i < textures.length; i++) {
  15474. var texture = textures[i];
  15475. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15476. var colorRenderbuffer = gl.createRenderbuffer();
  15477. if (!colorRenderbuffer) {
  15478. throw new Error("Unable to create multi sampled framebuffer");
  15479. }
  15480. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15481. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15482. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15483. texture._MSAAFramebuffer = framebuffer;
  15484. texture._MSAARenderBuffer = colorRenderbuffer;
  15485. texture.samples = samples;
  15486. texture._depthStencilBuffer = depthStencilBuffer;
  15487. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15488. attachments.push(attachment);
  15489. }
  15490. gl.drawBuffers(attachments);
  15491. }
  15492. else {
  15493. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15494. }
  15495. this.bindUnboundFramebuffer(null);
  15496. return samples;
  15497. };
  15498. /** @hidden */
  15499. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15500. if (faceIndex === void 0) { faceIndex = 0; }
  15501. if (lod === void 0) { lod = 0; }
  15502. var gl = this._gl;
  15503. var target = gl.TEXTURE_2D;
  15504. if (texture.isCube) {
  15505. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15506. }
  15507. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15508. };
  15509. /** @hidden */
  15510. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15511. if (faceIndex === void 0) { faceIndex = 0; }
  15512. if (lod === void 0) { lod = 0; }
  15513. var gl = this._gl;
  15514. var textureType = this._getWebGLTextureType(texture.type);
  15515. var format = this._getInternalFormat(texture.format);
  15516. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15517. this._unpackFlipY(texture.invertY);
  15518. var target = gl.TEXTURE_2D;
  15519. if (texture.isCube) {
  15520. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15521. }
  15522. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15523. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15524. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15525. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15526. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15527. };
  15528. /** @hidden */
  15529. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15530. if (faceIndex === void 0) { faceIndex = 0; }
  15531. if (lod === void 0) { lod = 0; }
  15532. var gl = this._gl;
  15533. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15534. this._bindTextureDirectly(bindTarget, texture, true);
  15535. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15536. this._bindTextureDirectly(bindTarget, null, true);
  15537. };
  15538. /** @hidden */
  15539. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15540. if (faceIndex === void 0) { faceIndex = 0; }
  15541. if (lod === void 0) { lod = 0; }
  15542. var gl = this._gl;
  15543. var textureType = this._getWebGLTextureType(texture.type);
  15544. var format = this._getInternalFormat(texture.format);
  15545. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15546. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15547. this._bindTextureDirectly(bindTarget, texture, true);
  15548. this._unpackFlipY(texture.invertY);
  15549. var target = gl.TEXTURE_2D;
  15550. if (texture.isCube) {
  15551. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15552. }
  15553. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15554. this._bindTextureDirectly(bindTarget, null, true);
  15555. };
  15556. /**
  15557. * Creates a new render target cube texture
  15558. * @param size defines the size of the texture
  15559. * @param options defines the options used to create the texture
  15560. * @returns a new render target cube texture stored in an InternalTexture
  15561. */
  15562. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15563. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15564. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15565. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15566. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15567. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15568. }
  15569. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15570. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15571. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15572. }
  15573. var gl = this._gl;
  15574. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15575. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15576. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15577. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15578. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15579. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15580. }
  15581. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15582. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15583. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15584. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15585. for (var face = 0; face < 6; face++) {
  15586. 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);
  15587. }
  15588. // Create the framebuffer
  15589. var framebuffer = gl.createFramebuffer();
  15590. this.bindUnboundFramebuffer(framebuffer);
  15591. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15592. // MipMaps
  15593. if (fullOptions.generateMipMaps) {
  15594. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15595. }
  15596. // Unbind
  15597. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15598. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15599. this.bindUnboundFramebuffer(null);
  15600. texture._framebuffer = framebuffer;
  15601. texture.width = size;
  15602. texture.height = size;
  15603. texture.isReady = true;
  15604. texture.isCube = true;
  15605. texture.samples = 1;
  15606. texture.generateMipMaps = fullOptions.generateMipMaps;
  15607. texture.samplingMode = fullOptions.samplingMode;
  15608. texture.type = fullOptions.type;
  15609. texture.format = fullOptions.format;
  15610. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15611. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15612. this._internalTexturesCache.push(texture);
  15613. return texture;
  15614. };
  15615. /**
  15616. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15617. * @param rootUrl defines the url where the file to load is located
  15618. * @param scene defines the current scene
  15619. * @param lodScale defines scale to apply to the mip map selection
  15620. * @param lodOffset defines offset to apply to the mip map selection
  15621. * @param onLoad defines an optional callback raised when the texture is loaded
  15622. * @param onError defines an optional callback raised if there is an issue to load the texture
  15623. * @param format defines the format of the data
  15624. * @param forcedExtension defines the extension to use to pick the right loader
  15625. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15626. * @returns the cube texture as an InternalTexture
  15627. */
  15628. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15629. var _this = this;
  15630. if (onLoad === void 0) { onLoad = null; }
  15631. if (onError === void 0) { onError = null; }
  15632. if (forcedExtension === void 0) { forcedExtension = null; }
  15633. if (createPolynomials === void 0) { createPolynomials = true; }
  15634. var callback = function (loadData) {
  15635. if (!loadData) {
  15636. if (onLoad) {
  15637. onLoad(null);
  15638. }
  15639. return;
  15640. }
  15641. var texture = loadData.texture;
  15642. if (!createPolynomials) {
  15643. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15644. }
  15645. else if (loadData.info.sphericalPolynomial) {
  15646. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15647. }
  15648. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15649. if (_this._caps.textureLOD) {
  15650. // Do not add extra process if texture lod is supported.
  15651. if (onLoad) {
  15652. onLoad(texture);
  15653. }
  15654. return;
  15655. }
  15656. var mipSlices = 3;
  15657. var gl = _this._gl;
  15658. var width = loadData.width;
  15659. if (!width) {
  15660. return;
  15661. }
  15662. var textures = [];
  15663. for (var i = 0; i < mipSlices; i++) {
  15664. //compute LOD from even spacing in smoothness (matching shader calculation)
  15665. var smoothness = i / (mipSlices - 1);
  15666. var roughness = 1 - smoothness;
  15667. var minLODIndex = lodOffset; // roughness = 0
  15668. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15669. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15670. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15671. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15672. glTextureFromLod.type = texture.type;
  15673. glTextureFromLod.format = texture.format;
  15674. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15675. glTextureFromLod.height = glTextureFromLod.width;
  15676. glTextureFromLod.isCube = true;
  15677. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15678. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15679. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15680. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15681. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15682. if (loadData.isDDS) {
  15683. var info = loadData.info;
  15684. var data = loadData.data;
  15685. _this._unpackFlipY(info.isCompressed);
  15686. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15687. }
  15688. else {
  15689. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15690. }
  15691. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15692. // Wrap in a base texture for easy binding.
  15693. var lodTexture = new BABYLON.BaseTexture(scene);
  15694. lodTexture.isCube = true;
  15695. lodTexture._texture = glTextureFromLod;
  15696. glTextureFromLod.isReady = true;
  15697. textures.push(lodTexture);
  15698. }
  15699. texture._lodTextureHigh = textures[2];
  15700. texture._lodTextureMid = textures[1];
  15701. texture._lodTextureLow = textures[0];
  15702. if (onLoad) {
  15703. onLoad(texture);
  15704. }
  15705. };
  15706. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15707. };
  15708. /**
  15709. * Creates a cube texture
  15710. * @param rootUrl defines the url where the files to load is located
  15711. * @param scene defines the current scene
  15712. * @param files defines the list of files to load (1 per face)
  15713. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15714. * @param onLoad defines an optional callback raised when the texture is loaded
  15715. * @param onError defines an optional callback raised if there is an issue to load the texture
  15716. * @param format defines the format of the data
  15717. * @param forcedExtension defines the extension to use to pick the right loader
  15718. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15719. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15720. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15721. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15722. * @returns the cube texture as an InternalTexture
  15723. */
  15724. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15725. var _this = this;
  15726. if (onLoad === void 0) { onLoad = null; }
  15727. if (onError === void 0) { onError = null; }
  15728. if (forcedExtension === void 0) { forcedExtension = null; }
  15729. if (createPolynomials === void 0) { createPolynomials = false; }
  15730. if (lodScale === void 0) { lodScale = 0; }
  15731. if (lodOffset === void 0) { lodOffset = 0; }
  15732. if (fallback === void 0) { fallback = null; }
  15733. var gl = this._gl;
  15734. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15735. texture.isCube = true;
  15736. texture.url = rootUrl;
  15737. texture.generateMipMaps = !noMipmap;
  15738. texture._lodGenerationScale = lodScale;
  15739. texture._lodGenerationOffset = lodOffset;
  15740. if (!this._doNotHandleContextLost) {
  15741. texture._extension = forcedExtension;
  15742. texture._files = files;
  15743. }
  15744. var lastDot = rootUrl.lastIndexOf('.');
  15745. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15746. var loader = null;
  15747. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15748. var availableLoader = _a[_i];
  15749. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15750. loader = availableLoader;
  15751. break;
  15752. }
  15753. }
  15754. var onInternalError = function (request, exception) {
  15755. if (loader) {
  15756. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15757. if (fallbackUrl) {
  15758. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15759. }
  15760. }
  15761. if (onError && request) {
  15762. onError(request.status + " " + request.statusText, exception);
  15763. }
  15764. };
  15765. if (loader) {
  15766. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15767. var onloaddata = function (data) {
  15768. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15769. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15770. };
  15771. if (files && files.length === 6) {
  15772. if (loader.supportCascades) {
  15773. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15774. }
  15775. else if (onError) {
  15776. onError("Textures type does not support cascades.");
  15777. }
  15778. }
  15779. else {
  15780. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15781. }
  15782. }
  15783. else {
  15784. if (!files) {
  15785. throw new Error("Cannot load cubemap because files were not defined");
  15786. }
  15787. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15788. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15789. var height = width;
  15790. _this._prepareWorkingCanvas();
  15791. if (!_this._workingCanvas || !_this._workingContext) {
  15792. return;
  15793. }
  15794. _this._workingCanvas.width = width;
  15795. _this._workingCanvas.height = height;
  15796. var faces = [
  15797. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15798. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15799. ];
  15800. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15801. _this._unpackFlipY(false);
  15802. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15803. for (var index = 0; index < faces.length; index++) {
  15804. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15805. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15806. }
  15807. if (!noMipmap) {
  15808. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15809. }
  15810. _this._setCubeMapTextureParams(!noMipmap);
  15811. texture.width = width;
  15812. texture.height = height;
  15813. texture.isReady = true;
  15814. if (format) {
  15815. texture.format = format;
  15816. }
  15817. texture.onLoadedObservable.notifyObservers(texture);
  15818. texture.onLoadedObservable.clear();
  15819. if (onLoad) {
  15820. onLoad();
  15821. }
  15822. }, files, onError);
  15823. }
  15824. this._internalTexturesCache.push(texture);
  15825. return texture;
  15826. };
  15827. /**
  15828. * @hidden
  15829. */
  15830. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15831. var gl = this._gl;
  15832. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15833. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15834. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15835. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15836. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15837. // this.resetTextureCache();
  15838. };
  15839. /**
  15840. * Update a raw cube texture
  15841. * @param texture defines the texture to udpdate
  15842. * @param data defines the data to store
  15843. * @param format defines the data format
  15844. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15845. * @param invertY defines if data must be stored with Y axis inverted
  15846. * @param compression defines the compression used (null by default)
  15847. * @param level defines which level of the texture to update
  15848. */
  15849. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15850. if (compression === void 0) { compression = null; }
  15851. if (level === void 0) { level = 0; }
  15852. texture._bufferViewArray = data;
  15853. texture.format = format;
  15854. texture.type = type;
  15855. texture.invertY = invertY;
  15856. texture._compression = compression;
  15857. var gl = this._gl;
  15858. var textureType = this._getWebGLTextureType(type);
  15859. var internalFormat = this._getInternalFormat(format);
  15860. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15861. var needConversion = false;
  15862. if (internalFormat === gl.RGB) {
  15863. internalFormat = gl.RGBA;
  15864. needConversion = true;
  15865. }
  15866. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15867. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15868. if (texture.width % 4 !== 0) {
  15869. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15870. }
  15871. // Data are known to be in +X +Y +Z -X -Y -Z
  15872. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15873. var faceData = data[faceIndex];
  15874. if (compression) {
  15875. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15876. }
  15877. else {
  15878. if (needConversion) {
  15879. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15880. }
  15881. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15882. }
  15883. }
  15884. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15885. if (isPot && texture.generateMipMaps && level === 0) {
  15886. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15887. }
  15888. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15889. // this.resetTextureCache();
  15890. texture.isReady = true;
  15891. };
  15892. /**
  15893. * Creates a new raw cube texture
  15894. * @param data defines the array of data to use to create each face
  15895. * @param size defines the size of the textures
  15896. * @param format defines the format of the data
  15897. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15898. * @param generateMipMaps defines if the engine should generate the mip levels
  15899. * @param invertY defines if data must be stored with Y axis inverted
  15900. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15901. * @param compression defines the compression used (null by default)
  15902. * @returns the cube texture as an InternalTexture
  15903. */
  15904. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15905. if (compression === void 0) { compression = null; }
  15906. var gl = this._gl;
  15907. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15908. texture.isCube = true;
  15909. texture.format = format;
  15910. texture.type = type;
  15911. if (!this._doNotHandleContextLost) {
  15912. texture._bufferViewArray = data;
  15913. }
  15914. var textureType = this._getWebGLTextureType(type);
  15915. var internalFormat = this._getInternalFormat(format);
  15916. if (internalFormat === gl.RGB) {
  15917. internalFormat = gl.RGBA;
  15918. }
  15919. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15920. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15921. generateMipMaps = false;
  15922. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15923. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15924. }
  15925. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15926. generateMipMaps = false;
  15927. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15928. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15929. }
  15930. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15931. generateMipMaps = false;
  15932. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15933. }
  15934. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15935. generateMipMaps = false;
  15936. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15937. }
  15938. var width = size;
  15939. var height = width;
  15940. texture.width = width;
  15941. texture.height = height;
  15942. // Double check on POT to generate Mips.
  15943. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15944. if (!isPot) {
  15945. generateMipMaps = false;
  15946. }
  15947. // Upload data if needed. The texture won't be ready until then.
  15948. if (data) {
  15949. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15950. }
  15951. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15952. // Filters
  15953. if (data && generateMipMaps) {
  15954. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15955. }
  15956. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15957. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15958. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15959. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15960. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15961. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15962. texture.generateMipMaps = generateMipMaps;
  15963. return texture;
  15964. };
  15965. /**
  15966. * Creates a new raw cube texture from a specified url
  15967. * @param url defines the url where the data is located
  15968. * @param scene defines the current scene
  15969. * @param size defines the size of the textures
  15970. * @param format defines the format of the data
  15971. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15972. * @param noMipmap defines if the engine should avoid generating the mip levels
  15973. * @param callback defines a callback used to extract texture data from loaded data
  15974. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15975. * @param onLoad defines a callback called when texture is loaded
  15976. * @param onError defines a callback called if there is an error
  15977. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15978. * @param invertY defines if data must be stored with Y axis inverted
  15979. * @returns the cube texture as an InternalTexture
  15980. */
  15981. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15982. var _this = this;
  15983. if (onLoad === void 0) { onLoad = null; }
  15984. if (onError === void 0) { onError = null; }
  15985. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15986. if (invertY === void 0) { invertY = false; }
  15987. var gl = this._gl;
  15988. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15989. scene._addPendingData(texture);
  15990. texture.url = url;
  15991. this._internalTexturesCache.push(texture);
  15992. var onerror = function (request, exception) {
  15993. scene._removePendingData(texture);
  15994. if (onError && request) {
  15995. onError(request.status + " " + request.statusText, exception);
  15996. }
  15997. };
  15998. var internalCallback = function (data) {
  15999. var width = texture.width;
  16000. var faceDataArrays = callback(data);
  16001. if (!faceDataArrays) {
  16002. return;
  16003. }
  16004. if (mipmapGenerator) {
  16005. var textureType = _this._getWebGLTextureType(type);
  16006. var internalFormat = _this._getInternalFormat(format);
  16007. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16008. var needConversion = false;
  16009. if (internalFormat === gl.RGB) {
  16010. internalFormat = gl.RGBA;
  16011. needConversion = true;
  16012. }
  16013. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16014. _this._unpackFlipY(false);
  16015. var mipData = mipmapGenerator(faceDataArrays);
  16016. for (var level = 0; level < mipData.length; level++) {
  16017. var mipSize = width >> level;
  16018. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16019. var mipFaceData = mipData[level][faceIndex];
  16020. if (needConversion) {
  16021. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16022. }
  16023. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16024. }
  16025. }
  16026. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16027. }
  16028. else {
  16029. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16030. }
  16031. texture.isReady = true;
  16032. // this.resetTextureCache();
  16033. scene._removePendingData(texture);
  16034. if (onLoad) {
  16035. onLoad();
  16036. }
  16037. };
  16038. this._loadFile(url, function (data) {
  16039. internalCallback(data);
  16040. }, undefined, scene.database, true, onerror);
  16041. return texture;
  16042. };
  16043. ;
  16044. /**
  16045. * Update a raw 3D texture
  16046. * @param texture defines the texture to update
  16047. * @param data defines the data to store
  16048. * @param format defines the data format
  16049. * @param invertY defines if data must be stored with Y axis inverted
  16050. * @param compression defines the used compression (can be null)
  16051. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16052. */
  16053. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16054. if (compression === void 0) { compression = null; }
  16055. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16056. var internalType = this._getWebGLTextureType(textureType);
  16057. var internalFormat = this._getInternalFormat(format);
  16058. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16059. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16060. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16061. if (!this._doNotHandleContextLost) {
  16062. texture._bufferView = data;
  16063. texture.format = format;
  16064. texture.invertY = invertY;
  16065. texture._compression = compression;
  16066. }
  16067. if (texture.width % 4 !== 0) {
  16068. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16069. }
  16070. if (compression && data) {
  16071. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16072. }
  16073. else {
  16074. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16075. }
  16076. if (texture.generateMipMaps) {
  16077. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16078. }
  16079. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16080. // this.resetTextureCache();
  16081. texture.isReady = true;
  16082. };
  16083. /**
  16084. * Creates a new raw 3D texture
  16085. * @param data defines the data used to create the texture
  16086. * @param width defines the width of the texture
  16087. * @param height defines the height of the texture
  16088. * @param depth defines the depth of the texture
  16089. * @param format defines the format of the texture
  16090. * @param generateMipMaps defines if the engine must generate mip levels
  16091. * @param invertY defines if data must be stored with Y axis inverted
  16092. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16093. * @param compression defines the compressed used (can be null)
  16094. * @param textureType defines the compressed used (can be null)
  16095. * @returns a new raw 3D texture (stored in an InternalTexture)
  16096. */
  16097. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16098. if (compression === void 0) { compression = null; }
  16099. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16100. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16101. texture.baseWidth = width;
  16102. texture.baseHeight = height;
  16103. texture.baseDepth = depth;
  16104. texture.width = width;
  16105. texture.height = height;
  16106. texture.depth = depth;
  16107. texture.format = format;
  16108. texture.type = textureType;
  16109. texture.generateMipMaps = generateMipMaps;
  16110. texture.samplingMode = samplingMode;
  16111. texture.is3D = true;
  16112. if (!this._doNotHandleContextLost) {
  16113. texture._bufferView = data;
  16114. }
  16115. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16116. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16117. // Filters
  16118. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16119. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16120. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16121. if (generateMipMaps) {
  16122. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16123. }
  16124. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16125. this._internalTexturesCache.push(texture);
  16126. return texture;
  16127. };
  16128. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16129. var gl = this._gl;
  16130. if (!gl) {
  16131. return;
  16132. }
  16133. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16134. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16135. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16136. if (!noMipmap && !isCompressed) {
  16137. gl.generateMipmap(gl.TEXTURE_2D);
  16138. }
  16139. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16140. // this.resetTextureCache();
  16141. if (scene) {
  16142. scene._removePendingData(texture);
  16143. }
  16144. texture.onLoadedObservable.notifyObservers(texture);
  16145. texture.onLoadedObservable.clear();
  16146. };
  16147. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16148. var _this = this;
  16149. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16150. var maxTextureSize = this.getCaps().maxTextureSize;
  16151. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16152. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16153. var gl = this._gl;
  16154. if (!gl) {
  16155. return;
  16156. }
  16157. if (!texture._webGLTexture) {
  16158. // this.resetTextureCache();
  16159. if (scene) {
  16160. scene._removePendingData(texture);
  16161. }
  16162. return;
  16163. }
  16164. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16165. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16166. texture.baseWidth = width;
  16167. texture.baseHeight = height;
  16168. texture.width = potWidth;
  16169. texture.height = potHeight;
  16170. texture.isReady = true;
  16171. if (processFunction(potWidth, potHeight, function () {
  16172. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16173. })) {
  16174. // Returning as texture needs extra async steps
  16175. return;
  16176. }
  16177. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16178. };
  16179. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16180. // Create new RGBA data container.
  16181. var rgbaData;
  16182. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16183. rgbaData = new Float32Array(width * height * 4);
  16184. }
  16185. else {
  16186. rgbaData = new Uint32Array(width * height * 4);
  16187. }
  16188. // Convert each pixel.
  16189. for (var x = 0; x < width; x++) {
  16190. for (var y = 0; y < height; y++) {
  16191. var index = (y * width + x) * 3;
  16192. var newIndex = (y * width + x) * 4;
  16193. // Map Old Value to new value.
  16194. rgbaData[newIndex + 0] = rgbData[index + 0];
  16195. rgbaData[newIndex + 1] = rgbData[index + 1];
  16196. rgbaData[newIndex + 2] = rgbData[index + 2];
  16197. // Add fully opaque alpha channel.
  16198. rgbaData[newIndex + 3] = 1;
  16199. }
  16200. }
  16201. return rgbaData;
  16202. };
  16203. /** @hidden */
  16204. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16205. var gl = this._gl;
  16206. if (texture._framebuffer) {
  16207. gl.deleteFramebuffer(texture._framebuffer);
  16208. texture._framebuffer = null;
  16209. }
  16210. if (texture._depthStencilBuffer) {
  16211. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16212. texture._depthStencilBuffer = null;
  16213. }
  16214. if (texture._MSAAFramebuffer) {
  16215. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16216. texture._MSAAFramebuffer = null;
  16217. }
  16218. if (texture._MSAARenderBuffer) {
  16219. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16220. texture._MSAARenderBuffer = null;
  16221. }
  16222. };
  16223. /** @hidden */
  16224. Engine.prototype._releaseTexture = function (texture) {
  16225. var gl = this._gl;
  16226. this._releaseFramebufferObjects(texture);
  16227. gl.deleteTexture(texture._webGLTexture);
  16228. // Unbind channels
  16229. this.unbindAllTextures();
  16230. var index = this._internalTexturesCache.indexOf(texture);
  16231. if (index !== -1) {
  16232. this._internalTexturesCache.splice(index, 1);
  16233. }
  16234. // Integrated fixed lod samplers.
  16235. if (texture._lodTextureHigh) {
  16236. texture._lodTextureHigh.dispose();
  16237. }
  16238. if (texture._lodTextureMid) {
  16239. texture._lodTextureMid.dispose();
  16240. }
  16241. if (texture._lodTextureLow) {
  16242. texture._lodTextureLow.dispose();
  16243. }
  16244. // Set output texture of post process to null if the texture has been released/disposed
  16245. this.scenes.forEach(function (scene) {
  16246. scene.postProcesses.forEach(function (postProcess) {
  16247. if (postProcess._outputTexture == texture) {
  16248. postProcess._outputTexture = null;
  16249. }
  16250. });
  16251. scene.cameras.forEach(function (camera) {
  16252. camera._postProcesses.forEach(function (postProcess) {
  16253. if (postProcess) {
  16254. if (postProcess._outputTexture == texture) {
  16255. postProcess._outputTexture = null;
  16256. }
  16257. }
  16258. });
  16259. });
  16260. });
  16261. };
  16262. Engine.prototype.setProgram = function (program) {
  16263. if (this._currentProgram !== program) {
  16264. this._gl.useProgram(program);
  16265. this._currentProgram = program;
  16266. }
  16267. };
  16268. /**
  16269. * Binds an effect to the webGL context
  16270. * @param effect defines the effect to bind
  16271. */
  16272. Engine.prototype.bindSamplers = function (effect) {
  16273. this.setProgram(effect.getProgram());
  16274. var samplers = effect.getSamplers();
  16275. for (var index = 0; index < samplers.length; index++) {
  16276. var uniform = effect.getUniform(samplers[index]);
  16277. if (uniform) {
  16278. this._boundUniforms[index] = uniform;
  16279. }
  16280. }
  16281. this._currentEffect = null;
  16282. };
  16283. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16284. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16285. return;
  16286. }
  16287. // Remove
  16288. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16289. // Bind last to it
  16290. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16291. // Bind to dummy
  16292. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16293. };
  16294. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16295. if (!internalTexture) {
  16296. return -1;
  16297. }
  16298. internalTexture._initialSlot = channel;
  16299. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16300. if (channel !== internalTexture._designatedSlot) {
  16301. this._textureCollisions.addCount(1, false);
  16302. }
  16303. }
  16304. else {
  16305. if (channel !== internalTexture._designatedSlot) {
  16306. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16307. return internalTexture._designatedSlot;
  16308. }
  16309. else {
  16310. // No slot for this texture, let's pick a new one (if we find a free slot)
  16311. if (this._nextFreeTextureSlots.length) {
  16312. return this._nextFreeTextureSlots[0];
  16313. }
  16314. // We need to recycle the oldest bound texture, sorry.
  16315. this._textureCollisions.addCount(1, false);
  16316. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16317. }
  16318. }
  16319. }
  16320. return channel;
  16321. };
  16322. Engine.prototype._linkTrackers = function (previous, next) {
  16323. previous.next = next;
  16324. next.previous = previous;
  16325. };
  16326. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16327. var currentSlot = internalTexture._designatedSlot;
  16328. if (currentSlot === -1) {
  16329. return -1;
  16330. }
  16331. internalTexture._designatedSlot = -1;
  16332. if (this.disableTextureBindingOptimization) {
  16333. return -1;
  16334. }
  16335. // Remove from bound list
  16336. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16337. // Free the slot
  16338. this._boundTexturesCache[currentSlot] = null;
  16339. this._nextFreeTextureSlots.push(currentSlot);
  16340. return currentSlot;
  16341. };
  16342. Engine.prototype._activateCurrentTexture = function () {
  16343. if (this._currentTextureChannel !== this._activeChannel) {
  16344. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16345. this._currentTextureChannel = this._activeChannel;
  16346. }
  16347. };
  16348. /** @hidden */
  16349. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16350. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16351. if (force === void 0) { force = false; }
  16352. var wasPreviouslyBound = false;
  16353. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16354. this._activeChannel = texture._designatedSlot;
  16355. }
  16356. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16357. var isTextureForRendering = texture && texture._initialSlot > -1;
  16358. if (currentTextureBound !== texture || force) {
  16359. if (currentTextureBound) {
  16360. this._removeDesignatedSlot(currentTextureBound);
  16361. }
  16362. this._activateCurrentTexture();
  16363. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16364. this._boundTexturesCache[this._activeChannel] = texture;
  16365. if (texture) {
  16366. if (!this.disableTextureBindingOptimization) {
  16367. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16368. if (slotIndex > -1) {
  16369. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16370. }
  16371. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16372. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16373. }
  16374. texture._designatedSlot = this._activeChannel;
  16375. }
  16376. }
  16377. else if (forTextureDataUpdate) {
  16378. wasPreviouslyBound = true;
  16379. this._activateCurrentTexture();
  16380. }
  16381. if (isTextureForRendering && !forTextureDataUpdate) {
  16382. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16383. }
  16384. return wasPreviouslyBound;
  16385. };
  16386. /** @hidden */
  16387. Engine.prototype._bindTexture = function (channel, texture) {
  16388. if (channel < 0) {
  16389. return;
  16390. }
  16391. if (texture) {
  16392. channel = this._getCorrectTextureChannel(channel, texture);
  16393. }
  16394. this._activeChannel = channel;
  16395. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16396. };
  16397. /**
  16398. * Sets a texture to the webGL context from a postprocess
  16399. * @param channel defines the channel to use
  16400. * @param postProcess defines the source postprocess
  16401. */
  16402. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16403. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16404. };
  16405. /**
  16406. * Binds the output of the passed in post process to the texture channel specified
  16407. * @param channel The channel the texture should be bound to
  16408. * @param postProcess The post process which's output should be bound
  16409. */
  16410. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16411. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16412. };
  16413. /**
  16414. * Unbind all textures from the webGL context
  16415. */
  16416. Engine.prototype.unbindAllTextures = function () {
  16417. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16418. this._activeChannel = channel;
  16419. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16420. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16421. if (this.webGLVersion > 1) {
  16422. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16423. }
  16424. }
  16425. };
  16426. /**
  16427. * Sets a texture to the according uniform.
  16428. * @param channel The texture channel
  16429. * @param uniform The uniform to set
  16430. * @param texture The texture to apply
  16431. */
  16432. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16433. if (channel < 0) {
  16434. return;
  16435. }
  16436. if (uniform) {
  16437. this._boundUniforms[channel] = uniform;
  16438. }
  16439. this._setTexture(channel, texture);
  16440. };
  16441. /**
  16442. * Sets a depth stencil texture from a render target to the according uniform.
  16443. * @param channel The texture channel
  16444. * @param uniform The uniform to set
  16445. * @param texture The render target texture containing the depth stencil texture to apply
  16446. */
  16447. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16448. if (channel < 0) {
  16449. return;
  16450. }
  16451. if (uniform) {
  16452. this._boundUniforms[channel] = uniform;
  16453. }
  16454. if (!texture || !texture.depthStencilTexture) {
  16455. this._setTexture(channel, null);
  16456. }
  16457. else {
  16458. this._setTexture(channel, texture, false, true);
  16459. }
  16460. };
  16461. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16462. var uniform = this._boundUniforms[sourceSlot];
  16463. if (uniform._currentState === destination) {
  16464. return;
  16465. }
  16466. this._gl.uniform1i(uniform, destination);
  16467. uniform._currentState = destination;
  16468. };
  16469. Engine.prototype._getTextureWrapMode = function (mode) {
  16470. switch (mode) {
  16471. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16472. return this._gl.REPEAT;
  16473. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16474. return this._gl.CLAMP_TO_EDGE;
  16475. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16476. return this._gl.MIRRORED_REPEAT;
  16477. }
  16478. return this._gl.REPEAT;
  16479. };
  16480. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16481. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16482. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16483. // Not ready?
  16484. if (!texture) {
  16485. if (this._boundTexturesCache[channel] != null) {
  16486. this._activeChannel = channel;
  16487. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16488. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16489. if (this.webGLVersion > 1) {
  16490. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16491. }
  16492. }
  16493. return false;
  16494. }
  16495. // Video
  16496. if (texture.video) {
  16497. this._activeChannel = channel;
  16498. texture.update();
  16499. }
  16500. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16501. texture.delayLoad();
  16502. return false;
  16503. }
  16504. var internalTexture;
  16505. if (depthStencilTexture) {
  16506. internalTexture = texture.depthStencilTexture;
  16507. }
  16508. else if (texture.isReady()) {
  16509. internalTexture = texture.getInternalTexture();
  16510. }
  16511. else if (texture.isCube) {
  16512. internalTexture = this.emptyCubeTexture;
  16513. }
  16514. else if (texture.is3D) {
  16515. internalTexture = this.emptyTexture3D;
  16516. }
  16517. else {
  16518. internalTexture = this.emptyTexture;
  16519. }
  16520. if (!isPartOfTextureArray) {
  16521. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16522. }
  16523. var needToBind = true;
  16524. if (this._boundTexturesCache[channel] === internalTexture) {
  16525. this._moveBoundTextureOnTop(internalTexture);
  16526. if (!isPartOfTextureArray) {
  16527. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16528. }
  16529. needToBind = false;
  16530. }
  16531. this._activeChannel = channel;
  16532. if (internalTexture && internalTexture.is3D) {
  16533. if (needToBind) {
  16534. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16535. }
  16536. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16537. internalTexture._cachedWrapU = texture.wrapU;
  16538. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16539. }
  16540. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16541. internalTexture._cachedWrapV = texture.wrapV;
  16542. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16543. }
  16544. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16545. internalTexture._cachedWrapR = texture.wrapR;
  16546. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16547. }
  16548. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16549. }
  16550. else if (internalTexture && internalTexture.isCube) {
  16551. if (needToBind) {
  16552. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16553. }
  16554. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16555. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16556. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16557. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16558. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16559. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16560. }
  16561. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16562. }
  16563. else {
  16564. if (needToBind) {
  16565. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16566. }
  16567. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16568. internalTexture._cachedWrapU = texture.wrapU;
  16569. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16570. }
  16571. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16572. internalTexture._cachedWrapV = texture.wrapV;
  16573. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16574. }
  16575. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16576. }
  16577. return true;
  16578. };
  16579. /**
  16580. * Sets an array of texture to the webGL context
  16581. * @param channel defines the channel where the texture array must be set
  16582. * @param uniform defines the associated uniform location
  16583. * @param textures defines the array of textures to bind
  16584. */
  16585. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16586. if (channel < 0 || !uniform) {
  16587. return;
  16588. }
  16589. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16590. this._textureUnits = new Int32Array(textures.length);
  16591. }
  16592. for (var i = 0; i < textures.length; i++) {
  16593. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16594. }
  16595. this._gl.uniform1iv(uniform, this._textureUnits);
  16596. for (var index = 0; index < textures.length; index++) {
  16597. this._setTexture(this._textureUnits[index], textures[index], true);
  16598. }
  16599. };
  16600. /** @hidden */
  16601. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16602. var internalTexture = texture.getInternalTexture();
  16603. if (!internalTexture) {
  16604. return;
  16605. }
  16606. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16607. var value = texture.anisotropicFilteringLevel;
  16608. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16609. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16610. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16611. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16612. }
  16613. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16614. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16615. internalTexture._cachedAnisotropicFilteringLevel = value;
  16616. }
  16617. };
  16618. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16619. this._bindTextureDirectly(target, texture, true, true);
  16620. this._gl.texParameterf(target, parameter, value);
  16621. };
  16622. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16623. if (texture) {
  16624. this._bindTextureDirectly(target, texture, true, true);
  16625. }
  16626. this._gl.texParameteri(target, parameter, value);
  16627. };
  16628. /**
  16629. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16630. * @param x defines the x coordinate of the rectangle where pixels must be read
  16631. * @param y defines the y coordinate of the rectangle where pixels must be read
  16632. * @param width defines the width of the rectangle where pixels must be read
  16633. * @param height defines the height of the rectangle where pixels must be read
  16634. * @returns a Uint8Array containing RGBA colors
  16635. */
  16636. Engine.prototype.readPixels = function (x, y, width, height) {
  16637. var data = new Uint8Array(height * width * 4);
  16638. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16639. return data;
  16640. };
  16641. /**
  16642. * Add an externaly attached data from its key.
  16643. * This method call will fail and return false, if such key already exists.
  16644. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16645. * @param key the unique key that identifies the data
  16646. * @param data the data object to associate to the key for this Engine instance
  16647. * @return true if no such key were already present and the data was added successfully, false otherwise
  16648. */
  16649. Engine.prototype.addExternalData = function (key, data) {
  16650. if (!this._externalData) {
  16651. this._externalData = new BABYLON.StringDictionary();
  16652. }
  16653. return this._externalData.add(key, data);
  16654. };
  16655. /**
  16656. * Get an externaly attached data from its key
  16657. * @param key the unique key that identifies the data
  16658. * @return the associated data, if present (can be null), or undefined if not present
  16659. */
  16660. Engine.prototype.getExternalData = function (key) {
  16661. if (!this._externalData) {
  16662. this._externalData = new BABYLON.StringDictionary();
  16663. }
  16664. return this._externalData.get(key);
  16665. };
  16666. /**
  16667. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16668. * @param key the unique key that identifies the data
  16669. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16670. * @return the associated data, can be null if the factory returned null.
  16671. */
  16672. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16673. if (!this._externalData) {
  16674. this._externalData = new BABYLON.StringDictionary();
  16675. }
  16676. return this._externalData.getOrAddWithFactory(key, factory);
  16677. };
  16678. /**
  16679. * Remove an externaly attached data from the Engine instance
  16680. * @param key the unique key that identifies the data
  16681. * @return true if the data was successfully removed, false if it doesn't exist
  16682. */
  16683. Engine.prototype.removeExternalData = function (key) {
  16684. if (!this._externalData) {
  16685. this._externalData = new BABYLON.StringDictionary();
  16686. }
  16687. return this._externalData.remove(key);
  16688. };
  16689. /**
  16690. * Unbind all vertex attributes from the webGL context
  16691. */
  16692. Engine.prototype.unbindAllAttributes = function () {
  16693. if (this._mustWipeVertexAttributes) {
  16694. this._mustWipeVertexAttributes = false;
  16695. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16696. this._gl.disableVertexAttribArray(i);
  16697. this._vertexAttribArraysEnabled[i] = false;
  16698. this._currentBufferPointers[i].active = false;
  16699. }
  16700. return;
  16701. }
  16702. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16703. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16704. continue;
  16705. }
  16706. this._gl.disableVertexAttribArray(i);
  16707. this._vertexAttribArraysEnabled[i] = false;
  16708. this._currentBufferPointers[i].active = false;
  16709. }
  16710. };
  16711. /**
  16712. * 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
  16713. */
  16714. Engine.prototype.releaseEffects = function () {
  16715. for (var name in this._compiledEffects) {
  16716. this._deleteProgram(this._compiledEffects[name]._program);
  16717. }
  16718. this._compiledEffects = {};
  16719. };
  16720. /**
  16721. * Dispose and release all associated resources
  16722. */
  16723. Engine.prototype.dispose = function () {
  16724. this.hideLoadingUI();
  16725. this.stopRenderLoop();
  16726. // Release postProcesses
  16727. while (this.postProcesses.length) {
  16728. this.postProcesses[0].dispose();
  16729. }
  16730. // Empty texture
  16731. if (this._emptyTexture) {
  16732. this._releaseTexture(this._emptyTexture);
  16733. this._emptyTexture = null;
  16734. }
  16735. if (this._emptyCubeTexture) {
  16736. this._releaseTexture(this._emptyCubeTexture);
  16737. this._emptyCubeTexture = null;
  16738. }
  16739. // Rescale PP
  16740. if (this._rescalePostProcess) {
  16741. this._rescalePostProcess.dispose();
  16742. }
  16743. // Release scenes
  16744. while (this.scenes.length) {
  16745. this.scenes[0].dispose();
  16746. }
  16747. // Release audio engine
  16748. if (Engine.audioEngine) {
  16749. Engine.audioEngine.dispose();
  16750. }
  16751. // Release effects
  16752. this.releaseEffects();
  16753. // Unbind
  16754. this.unbindAllAttributes();
  16755. this._boundUniforms = [];
  16756. if (this._dummyFramebuffer) {
  16757. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16758. }
  16759. //WebVR
  16760. this.disableVR();
  16761. // Events
  16762. if (BABYLON.Tools.IsWindowObjectExist()) {
  16763. window.removeEventListener("blur", this._onBlur);
  16764. window.removeEventListener("focus", this._onFocus);
  16765. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16766. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16767. if (this._renderingCanvas) {
  16768. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16769. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16770. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16771. if (!this._doNotHandleContextLost) {
  16772. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16773. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16774. }
  16775. }
  16776. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16777. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16778. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16779. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16780. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16781. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16782. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16783. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16784. if (this._onVrDisplayConnect) {
  16785. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16786. if (this._onVrDisplayDisconnect) {
  16787. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16788. }
  16789. if (this._onVrDisplayPresentChange) {
  16790. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16791. }
  16792. this._onVrDisplayConnect = null;
  16793. this._onVrDisplayDisconnect = null;
  16794. }
  16795. }
  16796. // Remove from Instances
  16797. var index = Engine.Instances.indexOf(this);
  16798. if (index >= 0) {
  16799. Engine.Instances.splice(index, 1);
  16800. }
  16801. this._workingCanvas = null;
  16802. this._workingContext = null;
  16803. this._currentBufferPointers = [];
  16804. this._renderingCanvas = null;
  16805. this._currentProgram = null;
  16806. this._bindedRenderFunction = null;
  16807. this.onResizeObservable.clear();
  16808. this.onCanvasBlurObservable.clear();
  16809. this.onCanvasFocusObservable.clear();
  16810. this.onCanvasPointerOutObservable.clear();
  16811. this.onBeginFrameObservable.clear();
  16812. this.onEndFrameObservable.clear();
  16813. BABYLON.Effect.ResetCache();
  16814. // Abort active requests
  16815. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16816. var request = _a[_i];
  16817. request.abort();
  16818. }
  16819. };
  16820. // Loading screen
  16821. /**
  16822. * Display the loading screen
  16823. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16824. */
  16825. Engine.prototype.displayLoadingUI = function () {
  16826. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16827. return;
  16828. }
  16829. var loadingScreen = this.loadingScreen;
  16830. if (loadingScreen) {
  16831. loadingScreen.displayLoadingUI();
  16832. }
  16833. };
  16834. /**
  16835. * Hide the loading screen
  16836. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16837. */
  16838. Engine.prototype.hideLoadingUI = function () {
  16839. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16840. return;
  16841. }
  16842. var loadingScreen = this.loadingScreen;
  16843. if (loadingScreen) {
  16844. loadingScreen.hideLoadingUI();
  16845. }
  16846. };
  16847. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16848. /**
  16849. * Gets the current loading screen object
  16850. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16851. */
  16852. get: function () {
  16853. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16854. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16855. return this._loadingScreen;
  16856. },
  16857. /**
  16858. * Sets the current loading screen object
  16859. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16860. */
  16861. set: function (loadingScreen) {
  16862. this._loadingScreen = loadingScreen;
  16863. },
  16864. enumerable: true,
  16865. configurable: true
  16866. });
  16867. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16868. /**
  16869. * Sets the current loading screen text
  16870. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16871. */
  16872. set: function (text) {
  16873. this.loadingScreen.loadingUIText = text;
  16874. },
  16875. enumerable: true,
  16876. configurable: true
  16877. });
  16878. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16879. /**
  16880. * Sets the current loading screen background color
  16881. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16882. */
  16883. set: function (color) {
  16884. this.loadingScreen.loadingUIBackgroundColor = color;
  16885. },
  16886. enumerable: true,
  16887. configurable: true
  16888. });
  16889. /**
  16890. * Attach a new callback raised when context lost event is fired
  16891. * @param callback defines the callback to call
  16892. */
  16893. Engine.prototype.attachContextLostEvent = function (callback) {
  16894. if (this._renderingCanvas) {
  16895. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16896. }
  16897. };
  16898. /**
  16899. * Attach a new callback raised when context restored event is fired
  16900. * @param callback defines the callback to call
  16901. */
  16902. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16903. if (this._renderingCanvas) {
  16904. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16905. }
  16906. };
  16907. /**
  16908. * Gets the source code of the vertex shader associated with a specific webGL program
  16909. * @param program defines the program to use
  16910. * @returns a string containing the source code of the vertex shader associated with the program
  16911. */
  16912. Engine.prototype.getVertexShaderSource = function (program) {
  16913. var shaders = this._gl.getAttachedShaders(program);
  16914. if (!shaders) {
  16915. return null;
  16916. }
  16917. return this._gl.getShaderSource(shaders[0]);
  16918. };
  16919. /**
  16920. * Gets the source code of the fragment shader associated with a specific webGL program
  16921. * @param program defines the program to use
  16922. * @returns a string containing the source code of the fragment shader associated with the program
  16923. */
  16924. Engine.prototype.getFragmentShaderSource = function (program) {
  16925. var shaders = this._gl.getAttachedShaders(program);
  16926. if (!shaders) {
  16927. return null;
  16928. }
  16929. return this._gl.getShaderSource(shaders[1]);
  16930. };
  16931. /**
  16932. * Get the current error code of the webGL context
  16933. * @returns the error code
  16934. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16935. */
  16936. Engine.prototype.getError = function () {
  16937. return this._gl.getError();
  16938. };
  16939. // FPS
  16940. /**
  16941. * Gets the current framerate
  16942. * @returns a number representing the framerate
  16943. */
  16944. Engine.prototype.getFps = function () {
  16945. return this._fps;
  16946. };
  16947. /**
  16948. * Gets the time spent between current and previous frame
  16949. * @returns a number representing the delta time in ms
  16950. */
  16951. Engine.prototype.getDeltaTime = function () {
  16952. return this._deltaTime;
  16953. };
  16954. Engine.prototype._measureFps = function () {
  16955. this._performanceMonitor.sampleFrame();
  16956. this._fps = this._performanceMonitor.averageFPS;
  16957. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16958. };
  16959. /** @hidden */
  16960. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16961. if (faceIndex === void 0) { faceIndex = -1; }
  16962. if (level === void 0) { level = 0; }
  16963. var gl = this._gl;
  16964. if (!this._dummyFramebuffer) {
  16965. var dummy = gl.createFramebuffer();
  16966. if (!dummy) {
  16967. throw new Error("Unable to create dummy framebuffer");
  16968. }
  16969. this._dummyFramebuffer = dummy;
  16970. }
  16971. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16972. if (faceIndex > -1) {
  16973. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16974. }
  16975. else {
  16976. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16977. }
  16978. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16979. var buffer;
  16980. switch (readType) {
  16981. case gl.UNSIGNED_BYTE:
  16982. buffer = new Uint8Array(4 * width * height);
  16983. readType = gl.UNSIGNED_BYTE;
  16984. break;
  16985. default:
  16986. buffer = new Float32Array(4 * width * height);
  16987. readType = gl.FLOAT;
  16988. break;
  16989. }
  16990. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16991. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16992. return buffer;
  16993. };
  16994. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16995. if (this._webGLVersion > 1) {
  16996. return this._caps.colorBufferFloat;
  16997. }
  16998. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16999. };
  17000. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17001. if (this._webGLVersion > 1) {
  17002. return this._caps.colorBufferFloat;
  17003. }
  17004. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17005. };
  17006. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17007. Engine.prototype._canRenderToFramebuffer = function (type) {
  17008. var gl = this._gl;
  17009. //clear existing errors
  17010. while (gl.getError() !== gl.NO_ERROR) { }
  17011. var successful = true;
  17012. var texture = gl.createTexture();
  17013. gl.bindTexture(gl.TEXTURE_2D, texture);
  17014. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17016. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17017. var fb = gl.createFramebuffer();
  17018. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17019. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17020. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17021. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17022. successful = successful && (gl.getError() === gl.NO_ERROR);
  17023. //try render by clearing frame buffer's color buffer
  17024. if (successful) {
  17025. gl.clear(gl.COLOR_BUFFER_BIT);
  17026. successful = successful && (gl.getError() === gl.NO_ERROR);
  17027. }
  17028. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17029. if (successful) {
  17030. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17031. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17032. var readFormat = gl.RGBA;
  17033. var readType = gl.UNSIGNED_BYTE;
  17034. var buffer = new Uint8Array(4);
  17035. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17036. successful = successful && (gl.getError() === gl.NO_ERROR);
  17037. }
  17038. //clean up
  17039. gl.deleteTexture(texture);
  17040. gl.deleteFramebuffer(fb);
  17041. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17042. //clear accumulated errors
  17043. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17044. return successful;
  17045. };
  17046. /** @hidden */
  17047. Engine.prototype._getWebGLTextureType = function (type) {
  17048. if (this._webGLVersion === 1) {
  17049. switch (type) {
  17050. case Engine.TEXTURETYPE_FLOAT:
  17051. return this._gl.FLOAT;
  17052. case Engine.TEXTURETYPE_HALF_FLOAT:
  17053. return this._gl.HALF_FLOAT_OES;
  17054. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17055. return this._gl.UNSIGNED_BYTE;
  17056. }
  17057. return this._gl.UNSIGNED_BYTE;
  17058. }
  17059. switch (type) {
  17060. case Engine.TEXTURETYPE_BYTE:
  17061. return this._gl.BYTE;
  17062. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17063. return this._gl.UNSIGNED_BYTE;
  17064. case Engine.TEXTURETYPE_SHORT:
  17065. return this._gl.SHORT;
  17066. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17067. return this._gl.UNSIGNED_SHORT;
  17068. case Engine.TEXTURETYPE_INT:
  17069. return this._gl.INT;
  17070. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17071. return this._gl.UNSIGNED_INT;
  17072. case Engine.TEXTURETYPE_FLOAT:
  17073. return this._gl.FLOAT;
  17074. case Engine.TEXTURETYPE_HALF_FLOAT:
  17075. return this._gl.HALF_FLOAT;
  17076. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17077. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17078. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17079. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17080. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17081. return this._gl.UNSIGNED_SHORT_5_6_5;
  17082. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17083. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17084. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17085. return this._gl.UNSIGNED_INT_24_8;
  17086. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17087. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17088. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17089. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17090. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17091. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17092. }
  17093. return this._gl.UNSIGNED_BYTE;
  17094. };
  17095. ;
  17096. Engine.prototype._getInternalFormat = function (format) {
  17097. var internalFormat = this._gl.RGBA;
  17098. switch (format) {
  17099. case Engine.TEXTUREFORMAT_ALPHA:
  17100. internalFormat = this._gl.ALPHA;
  17101. break;
  17102. case Engine.TEXTUREFORMAT_LUMINANCE:
  17103. internalFormat = this._gl.LUMINANCE;
  17104. break;
  17105. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17106. internalFormat = this._gl.LUMINANCE_ALPHA;
  17107. break;
  17108. case Engine.TEXTUREFORMAT_RED:
  17109. internalFormat = this._gl.RED;
  17110. break;
  17111. case Engine.TEXTUREFORMAT_RG:
  17112. internalFormat = this._gl.RG;
  17113. break;
  17114. case Engine.TEXTUREFORMAT_RGB:
  17115. internalFormat = this._gl.RGB;
  17116. break;
  17117. case Engine.TEXTUREFORMAT_RGBA:
  17118. internalFormat = this._gl.RGBA;
  17119. break;
  17120. }
  17121. if (this._webGLVersion > 1) {
  17122. switch (format) {
  17123. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17124. internalFormat = this._gl.RED_INTEGER;
  17125. break;
  17126. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17127. internalFormat = this._gl.RG_INTEGER;
  17128. break;
  17129. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17130. internalFormat = this._gl.RGB_INTEGER;
  17131. break;
  17132. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17133. internalFormat = this._gl.RGBA_INTEGER;
  17134. break;
  17135. }
  17136. }
  17137. return internalFormat;
  17138. };
  17139. /** @hidden */
  17140. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17141. if (this._webGLVersion === 1) {
  17142. if (format !== undefined) {
  17143. switch (format) {
  17144. case Engine.TEXTUREFORMAT_ALPHA:
  17145. return this._gl.ALPHA;
  17146. case Engine.TEXTUREFORMAT_LUMINANCE:
  17147. return this._gl.LUMINANCE;
  17148. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17149. return this._gl.LUMINANCE_ALPHA;
  17150. }
  17151. }
  17152. return this._gl.RGBA;
  17153. }
  17154. switch (type) {
  17155. case Engine.TEXTURETYPE_BYTE:
  17156. switch (format) {
  17157. case Engine.TEXTUREFORMAT_RED:
  17158. return this._gl.R8_SNORM;
  17159. case Engine.TEXTUREFORMAT_RG:
  17160. return this._gl.RG8_SNORM;
  17161. case Engine.TEXTUREFORMAT_RGB:
  17162. return this._gl.RGB8_SNORM;
  17163. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17164. return this._gl.R8I;
  17165. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17166. return this._gl.RG8I;
  17167. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17168. return this._gl.RGB8I;
  17169. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17170. return this._gl.RGBA8I;
  17171. default:
  17172. return this._gl.RGBA8_SNORM;
  17173. }
  17174. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17175. switch (format) {
  17176. case Engine.TEXTUREFORMAT_RED:
  17177. return this._gl.R8;
  17178. case Engine.TEXTUREFORMAT_RG:
  17179. return this._gl.RG8;
  17180. case Engine.TEXTUREFORMAT_RGB:
  17181. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17182. case Engine.TEXTUREFORMAT_RGBA:
  17183. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17184. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17185. return this._gl.R8UI;
  17186. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17187. return this._gl.RG8UI;
  17188. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17189. return this._gl.RGB8UI;
  17190. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17191. return this._gl.RGBA8UI;
  17192. default:
  17193. return this._gl.RGBA8;
  17194. }
  17195. case Engine.TEXTURETYPE_SHORT:
  17196. switch (format) {
  17197. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17198. return this._gl.R16I;
  17199. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17200. return this._gl.RG16I;
  17201. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17202. return this._gl.RGB16I;
  17203. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17204. return this._gl.RGBA16I;
  17205. default:
  17206. return this._gl.RGBA16I;
  17207. }
  17208. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17209. switch (format) {
  17210. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17211. return this._gl.R16UI;
  17212. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17213. return this._gl.RG16UI;
  17214. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17215. return this._gl.RGB16UI;
  17216. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17217. return this._gl.RGBA16UI;
  17218. default:
  17219. return this._gl.RGBA16UI;
  17220. }
  17221. case Engine.TEXTURETYPE_INT:
  17222. switch (format) {
  17223. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17224. return this._gl.R32I;
  17225. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17226. return this._gl.RG32I;
  17227. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17228. return this._gl.RGB32I;
  17229. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17230. return this._gl.RGBA32I;
  17231. default:
  17232. return this._gl.RGBA32I;
  17233. }
  17234. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17235. switch (format) {
  17236. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17237. return this._gl.R32UI;
  17238. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17239. return this._gl.RG32UI;
  17240. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17241. return this._gl.RGB32UI;
  17242. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17243. return this._gl.RGBA32UI;
  17244. default:
  17245. return this._gl.RGBA32UI;
  17246. }
  17247. case Engine.TEXTURETYPE_FLOAT:
  17248. switch (format) {
  17249. case Engine.TEXTUREFORMAT_RED:
  17250. return this._gl.R32F; // By default. Other possibility is R16F.
  17251. case Engine.TEXTUREFORMAT_RG:
  17252. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17253. case Engine.TEXTUREFORMAT_RGB:
  17254. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17255. case Engine.TEXTUREFORMAT_RGBA:
  17256. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17257. default:
  17258. return this._gl.RGBA32F;
  17259. }
  17260. case Engine.TEXTURETYPE_HALF_FLOAT:
  17261. switch (format) {
  17262. case Engine.TEXTUREFORMAT_RED:
  17263. return this._gl.R16F;
  17264. case Engine.TEXTUREFORMAT_RG:
  17265. return this._gl.RG16F;
  17266. case Engine.TEXTUREFORMAT_RGB:
  17267. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17268. case Engine.TEXTUREFORMAT_RGBA:
  17269. return this._gl.RGBA16F;
  17270. default:
  17271. return this._gl.RGBA16F;
  17272. }
  17273. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17274. return this._gl.RGB565;
  17275. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17276. return this._gl.R11F_G11F_B10F;
  17277. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17278. return this._gl.RGB9_E5;
  17279. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17280. return this._gl.RGBA4;
  17281. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17282. return this._gl.RGB5_A1;
  17283. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17284. switch (format) {
  17285. case Engine.TEXTUREFORMAT_RGBA:
  17286. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17287. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17288. return this._gl.RGB10_A2UI;
  17289. default:
  17290. return this._gl.RGB10_A2;
  17291. }
  17292. }
  17293. return this._gl.RGBA8;
  17294. };
  17295. ;
  17296. /** @hidden */
  17297. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17298. if (type === Engine.TEXTURETYPE_FLOAT) {
  17299. return this._gl.RGBA32F;
  17300. }
  17301. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17302. return this._gl.RGBA16F;
  17303. }
  17304. return this._gl.RGBA8;
  17305. };
  17306. ;
  17307. /** @hidden */
  17308. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17309. var _this = this;
  17310. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17311. this._activeRequests.push(request);
  17312. request.onCompleteObservable.add(function (request) {
  17313. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17314. });
  17315. return request;
  17316. };
  17317. /** @hidden */
  17318. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17319. var _this = this;
  17320. return new Promise(function (resolve, reject) {
  17321. _this._loadFile(url, function (data) {
  17322. resolve(data);
  17323. }, undefined, database, useArrayBuffer, function (request, exception) {
  17324. reject(exception);
  17325. });
  17326. });
  17327. };
  17328. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17329. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17330. var onload = function (data) {
  17331. loadedFiles[index] = data;
  17332. loadedFiles._internalCount++;
  17333. if (loadedFiles._internalCount === 6) {
  17334. onfinish(loadedFiles);
  17335. }
  17336. };
  17337. var onerror = function (request, exception) {
  17338. if (onErrorCallBack && request) {
  17339. onErrorCallBack(request.status + " " + request.statusText, exception);
  17340. }
  17341. };
  17342. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17343. };
  17344. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17345. if (onError === void 0) { onError = null; }
  17346. var loadedFiles = [];
  17347. loadedFiles._internalCount = 0;
  17348. for (var index = 0; index < 6; index++) {
  17349. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17350. }
  17351. };
  17352. // Statics
  17353. /**
  17354. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17355. * @returns true if the engine can be created
  17356. * @ignorenaming
  17357. */
  17358. Engine.isSupported = function () {
  17359. try {
  17360. var tempcanvas = document.createElement("canvas");
  17361. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17362. return gl != null && !!window.WebGLRenderingContext;
  17363. }
  17364. catch (e) {
  17365. return false;
  17366. }
  17367. };
  17368. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17369. Engine.ExceptionList = [
  17370. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17371. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17372. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17373. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17374. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17375. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17376. ];
  17377. /** Gets the list of created engines */
  17378. Engine.Instances = new Array();
  17379. /**
  17380. * Hidden
  17381. */
  17382. Engine._TextureLoaders = [];
  17383. // Const statics
  17384. /** Defines that alpha blending is disabled */
  17385. Engine.ALPHA_DISABLE = 0;
  17386. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17387. Engine.ALPHA_ADD = 1;
  17388. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17389. Engine.ALPHA_COMBINE = 2;
  17390. /** Defines that alpha blending to DEST - SRC * DEST */
  17391. Engine.ALPHA_SUBTRACT = 3;
  17392. /** Defines that alpha blending to SRC * DEST */
  17393. Engine.ALPHA_MULTIPLY = 4;
  17394. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17395. Engine.ALPHA_MAXIMIZED = 5;
  17396. /** Defines that alpha blending to SRC + DEST */
  17397. Engine.ALPHA_ONEONE = 6;
  17398. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17399. Engine.ALPHA_PREMULTIPLIED = 7;
  17400. /**
  17401. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17402. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17403. */
  17404. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17405. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17406. Engine.ALPHA_INTERPOLATE = 9;
  17407. /**
  17408. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17409. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17410. */
  17411. Engine.ALPHA_SCREENMODE = 10;
  17412. /** Defines that the ressource is not delayed*/
  17413. Engine.DELAYLOADSTATE_NONE = 0;
  17414. /** Defines that the ressource was successfully delay loaded */
  17415. Engine.DELAYLOADSTATE_LOADED = 1;
  17416. /** Defines that the ressource is currently delay loading */
  17417. Engine.DELAYLOADSTATE_LOADING = 2;
  17418. /** Defines that the ressource is delayed and has not started loading */
  17419. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17420. // Depht or Stencil test Constants.
  17421. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17422. Engine.NEVER = 0x0200;
  17423. /** 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 */
  17424. Engine.ALWAYS = 0x0207;
  17425. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17426. Engine.LESS = 0x0201;
  17427. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17428. Engine.EQUAL = 0x0202;
  17429. /** 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 */
  17430. Engine.LEQUAL = 0x0203;
  17431. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17432. Engine.GREATER = 0x0204;
  17433. /** 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 */
  17434. Engine.GEQUAL = 0x0206;
  17435. /** 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 */
  17436. Engine.NOTEQUAL = 0x0205;
  17437. // Stencil Actions Constants.
  17438. /** Passed to stencilOperation to specify that stencil value must be kept */
  17439. Engine.KEEP = 0x1E00;
  17440. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17441. Engine.REPLACE = 0x1E01;
  17442. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17443. Engine.INCR = 0x1E02;
  17444. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17445. Engine.DECR = 0x1E03;
  17446. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17447. Engine.INVERT = 0x150A;
  17448. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17449. Engine.INCR_WRAP = 0x8507;
  17450. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17451. Engine.DECR_WRAP = 0x8508;
  17452. /** Texture is not repeating outside of 0..1 UVs */
  17453. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17454. /** Texture is repeating outside of 0..1 UVs */
  17455. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17456. /** Texture is repeating and mirrored */
  17457. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17458. /** ALPHA */
  17459. Engine.TEXTUREFORMAT_ALPHA = 0;
  17460. /** LUMINANCE */
  17461. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17462. /** LUMINANCE_ALPHA */
  17463. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17464. /** RGB */
  17465. Engine.TEXTUREFORMAT_RGB = 4;
  17466. /** RGBA */
  17467. Engine.TEXTUREFORMAT_RGBA = 5;
  17468. /** RED */
  17469. Engine.TEXTUREFORMAT_RED = 6;
  17470. /** RED (2nd reference) */
  17471. Engine.TEXTUREFORMAT_R = 6;
  17472. /** RG */
  17473. Engine.TEXTUREFORMAT_RG = 7;
  17474. /** RED_INTEGER */
  17475. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17476. /** RED_INTEGER (2nd reference) */
  17477. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17478. /** RG_INTEGER */
  17479. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17480. /** RGB_INTEGER */
  17481. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17482. /** RGBA_INTEGER */
  17483. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17484. /** UNSIGNED_BYTE */
  17485. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17486. /** UNSIGNED_BYTE (2nd reference) */
  17487. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17488. /** FLOAT */
  17489. Engine.TEXTURETYPE_FLOAT = 1;
  17490. /** HALF_FLOAT */
  17491. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17492. /** BYTE */
  17493. Engine.TEXTURETYPE_BYTE = 3;
  17494. /** SHORT */
  17495. Engine.TEXTURETYPE_SHORT = 4;
  17496. /** UNSIGNED_SHORT */
  17497. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17498. /** INT */
  17499. Engine.TEXTURETYPE_INT = 6;
  17500. /** UNSIGNED_INT */
  17501. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17502. /** UNSIGNED_SHORT_4_4_4_4 */
  17503. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17504. /** UNSIGNED_SHORT_5_5_5_1 */
  17505. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17506. /** UNSIGNED_SHORT_5_6_5 */
  17507. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17508. /** UNSIGNED_INT_2_10_10_10_REV */
  17509. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17510. /** UNSIGNED_INT_24_8 */
  17511. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17512. /** UNSIGNED_INT_10F_11F_11F_REV */
  17513. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17514. /** UNSIGNED_INT_5_9_9_9_REV */
  17515. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17516. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17517. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17518. /** nearest is mag = nearest and min = nearest and mip = linear */
  17519. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17520. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17521. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17522. /** Trilinear is mag = linear and min = linear and mip = linear */
  17523. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17524. /** nearest is mag = nearest and min = nearest and mip = linear */
  17525. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17526. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17527. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17528. /** Trilinear is mag = linear and min = linear and mip = linear */
  17529. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17530. /** mag = nearest and min = nearest and mip = nearest */
  17531. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17532. /** mag = nearest and min = linear and mip = nearest */
  17533. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17534. /** mag = nearest and min = linear and mip = linear */
  17535. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17536. /** mag = nearest and min = linear and mip = none */
  17537. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17538. /** mag = nearest and min = nearest and mip = none */
  17539. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17540. /** mag = linear and min = nearest and mip = nearest */
  17541. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17542. /** mag = linear and min = nearest and mip = linear */
  17543. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17544. /** mag = linear and min = linear and mip = none */
  17545. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17546. /** mag = linear and min = nearest and mip = none */
  17547. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17548. /** Explicit coordinates mode */
  17549. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17550. /** Spherical coordinates mode */
  17551. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17552. /** Planar coordinates mode */
  17553. Engine.TEXTURE_PLANAR_MODE = 2;
  17554. /** Cubic coordinates mode */
  17555. Engine.TEXTURE_CUBIC_MODE = 3;
  17556. /** Projection coordinates mode */
  17557. Engine.TEXTURE_PROJECTION_MODE = 4;
  17558. /** Skybox coordinates mode */
  17559. Engine.TEXTURE_SKYBOX_MODE = 5;
  17560. /** Inverse Cubic coordinates mode */
  17561. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17562. /** Equirectangular coordinates mode */
  17563. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17564. /** Equirectangular Fixed coordinates mode */
  17565. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17566. /** Equirectangular Fixed Mirrored coordinates mode */
  17567. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17568. // Texture rescaling mode
  17569. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17570. Engine.SCALEMODE_FLOOR = 1;
  17571. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17572. Engine.SCALEMODE_NEAREST = 2;
  17573. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17574. Engine.SCALEMODE_CEILING = 3;
  17575. // Updatable statics so stick with vars here
  17576. /**
  17577. * Gets or sets the epsilon value used by collision engine
  17578. */
  17579. Engine.CollisionsEpsilon = 0.001;
  17580. /**
  17581. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17582. */
  17583. Engine.CodeRepository = "src/";
  17584. /**
  17585. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17586. */
  17587. Engine.ShadersRepository = "src/Shaders/";
  17588. return Engine;
  17589. }());
  17590. BABYLON.Engine = Engine;
  17591. })(BABYLON || (BABYLON = {}));
  17592. //# sourceMappingURL=babylon.engine.js.map
  17593. var BABYLON;
  17594. (function (BABYLON) {
  17595. /**
  17596. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17597. */
  17598. var Node = /** @class */ (function () {
  17599. /**
  17600. * Creates a new Node
  17601. * @param {string} name - the name and id to be given to this node
  17602. * @param {BABYLON.Scene} the scene this node will be added to
  17603. */
  17604. function Node(name, scene) {
  17605. if (scene === void 0) { scene = null; }
  17606. /**
  17607. * Gets or sets a string used to store user defined state for the node
  17608. */
  17609. this.state = "";
  17610. /**
  17611. * Gets or sets an object used to store user defined information for the node
  17612. */
  17613. this.metadata = null;
  17614. /**
  17615. * Gets or sets a boolean used to define if the node must be serialized
  17616. */
  17617. this.doNotSerialize = false;
  17618. /** @hidden */
  17619. this._isDisposed = false;
  17620. /**
  17621. * Gets a list of Animations associated with the node
  17622. */
  17623. this.animations = new Array();
  17624. this._ranges = {};
  17625. this._isEnabled = true;
  17626. this._isReady = true;
  17627. /** @hidden */
  17628. this._currentRenderId = -1;
  17629. this._parentRenderId = -1;
  17630. this._childRenderId = -1;
  17631. /** @hidden */
  17632. this._worldMatrix = BABYLON.Matrix.Zero();
  17633. /** @hidden */
  17634. this._worldMatrixDeterminant = 0;
  17635. this._animationPropertiesOverride = null;
  17636. /**
  17637. * An event triggered when the mesh is disposed
  17638. */
  17639. this.onDisposeObservable = new BABYLON.Observable();
  17640. // Behaviors
  17641. this._behaviors = new Array();
  17642. this.name = name;
  17643. this.id = name;
  17644. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17645. this.uniqueId = this._scene.getUniqueId();
  17646. this._initCache();
  17647. this._scene.rootNodes.push(this);
  17648. }
  17649. /**
  17650. * Add a new node constructor
  17651. * @param type defines the type name of the node to construct
  17652. * @param constructorFunc defines the constructor function
  17653. */
  17654. Node.AddNodeConstructor = function (type, constructorFunc) {
  17655. this._NodeConstructors[type] = constructorFunc;
  17656. };
  17657. /**
  17658. * Returns a node constructor based on type name
  17659. * @param type defines the type name
  17660. * @param name defines the new node name
  17661. * @param scene defines the hosting scene
  17662. * @param options defines optional options to transmit to constructors
  17663. * @returns the new constructor or null
  17664. */
  17665. Node.Construct = function (type, name, scene, options) {
  17666. var constructorFunc = this._NodeConstructors[type];
  17667. if (!constructorFunc) {
  17668. return null;
  17669. }
  17670. return constructorFunc(name, scene, options);
  17671. };
  17672. /**
  17673. * Gets a boolean indicating if the node has been disposed
  17674. * @returns true if the node was disposed
  17675. */
  17676. Node.prototype.isDisposed = function () {
  17677. return this._isDisposed;
  17678. };
  17679. Object.defineProperty(Node.prototype, "parent", {
  17680. get: function () {
  17681. return this._parentNode;
  17682. },
  17683. /**
  17684. * Gets or sets the parent of the node
  17685. */
  17686. set: function (parent) {
  17687. if (this._parentNode === parent) {
  17688. return;
  17689. }
  17690. var previousParentNode = this._parentNode;
  17691. // Remove self from list of children of parent
  17692. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17693. var index = this._parentNode._children.indexOf(this);
  17694. if (index !== -1) {
  17695. this._parentNode._children.splice(index, 1);
  17696. }
  17697. if (!parent) {
  17698. // Need to add this node to the rootNodes
  17699. this._scene.rootNodes.push(this);
  17700. }
  17701. }
  17702. // Store new parent
  17703. this._parentNode = parent;
  17704. // Add as child to new parent
  17705. if (this._parentNode) {
  17706. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17707. this._parentNode._children = new Array();
  17708. }
  17709. this._parentNode._children.push(this);
  17710. if (!previousParentNode) {
  17711. // Need to remove from rootNodes
  17712. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17713. if (rootNodeIndex > -1) {
  17714. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17715. }
  17716. }
  17717. }
  17718. },
  17719. enumerable: true,
  17720. configurable: true
  17721. });
  17722. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17723. /**
  17724. * Gets or sets the animation properties override
  17725. */
  17726. get: function () {
  17727. if (!this._animationPropertiesOverride) {
  17728. return this._scene.animationPropertiesOverride;
  17729. }
  17730. return this._animationPropertiesOverride;
  17731. },
  17732. set: function (value) {
  17733. this._animationPropertiesOverride = value;
  17734. },
  17735. enumerable: true,
  17736. configurable: true
  17737. });
  17738. /**
  17739. * Gets a string idenfifying the name of the class
  17740. * @returns "Node" string
  17741. */
  17742. Node.prototype.getClassName = function () {
  17743. return "Node";
  17744. };
  17745. Object.defineProperty(Node.prototype, "onDispose", {
  17746. /**
  17747. * Sets a callback that will be raised when the node will be disposed
  17748. */
  17749. set: function (callback) {
  17750. if (this._onDisposeObserver) {
  17751. this.onDisposeObservable.remove(this._onDisposeObserver);
  17752. }
  17753. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17754. },
  17755. enumerable: true,
  17756. configurable: true
  17757. });
  17758. /**
  17759. * Gets the scene of the node
  17760. * @returns a {BABYLON.Scene}
  17761. */
  17762. Node.prototype.getScene = function () {
  17763. return this._scene;
  17764. };
  17765. /**
  17766. * Gets the engine of the node
  17767. * @returns a {BABYLON.Engine}
  17768. */
  17769. Node.prototype.getEngine = function () {
  17770. return this._scene.getEngine();
  17771. };
  17772. /**
  17773. * Attach a behavior to the node
  17774. * @see http://doc.babylonjs.com/features/behaviour
  17775. * @param behavior defines the behavior to attach
  17776. * @returns the current Node
  17777. */
  17778. Node.prototype.addBehavior = function (behavior) {
  17779. var _this = this;
  17780. var index = this._behaviors.indexOf(behavior);
  17781. if (index !== -1) {
  17782. return this;
  17783. }
  17784. behavior.init();
  17785. if (this._scene.isLoading) {
  17786. // We defer the attach when the scene will be loaded
  17787. this._scene.onDataLoadedObservable.addOnce(function () {
  17788. behavior.attach(_this);
  17789. });
  17790. }
  17791. else {
  17792. behavior.attach(this);
  17793. }
  17794. this._behaviors.push(behavior);
  17795. return this;
  17796. };
  17797. /**
  17798. * Remove an attached behavior
  17799. * @see http://doc.babylonjs.com/features/behaviour
  17800. * @param behavior defines the behavior to attach
  17801. * @returns the current Node
  17802. */
  17803. Node.prototype.removeBehavior = function (behavior) {
  17804. var index = this._behaviors.indexOf(behavior);
  17805. if (index === -1) {
  17806. return this;
  17807. }
  17808. this._behaviors[index].detach();
  17809. this._behaviors.splice(index, 1);
  17810. return this;
  17811. };
  17812. Object.defineProperty(Node.prototype, "behaviors", {
  17813. /**
  17814. * Gets the list of attached behaviors
  17815. * @see http://doc.babylonjs.com/features/behaviour
  17816. */
  17817. get: function () {
  17818. return this._behaviors;
  17819. },
  17820. enumerable: true,
  17821. configurable: true
  17822. });
  17823. /**
  17824. * Gets an attached behavior by name
  17825. * @param name defines the name of the behavior to look for
  17826. * @see http://doc.babylonjs.com/features/behaviour
  17827. * @returns null if behavior was not found else the requested behavior
  17828. */
  17829. Node.prototype.getBehaviorByName = function (name) {
  17830. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17831. var behavior = _a[_i];
  17832. if (behavior.name === name) {
  17833. return behavior;
  17834. }
  17835. }
  17836. return null;
  17837. };
  17838. /**
  17839. * Returns the latest update of the World matrix
  17840. * @returns a Matrix
  17841. */
  17842. Node.prototype.getWorldMatrix = function () {
  17843. if (this._currentRenderId !== this.getScene().getRenderId()) {
  17844. this.computeWorldMatrix();
  17845. }
  17846. return this._worldMatrix;
  17847. };
  17848. /** @hidden */
  17849. Node.prototype._getWorldMatrixDeterminant = function () {
  17850. return this._worldMatrixDeterminant;
  17851. };
  17852. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  17853. /**
  17854. * Returns directly the latest state of the mesh World matrix.
  17855. * A Matrix is returned.
  17856. */
  17857. get: function () {
  17858. return this._worldMatrix;
  17859. },
  17860. enumerable: true,
  17861. configurable: true
  17862. });
  17863. // override it in derived class if you add new variables to the cache
  17864. // and call the parent class method
  17865. /** @hidden */
  17866. Node.prototype._initCache = function () {
  17867. this._cache = {};
  17868. this._cache.parent = undefined;
  17869. };
  17870. /** @hidden */
  17871. Node.prototype.updateCache = function (force) {
  17872. if (!force && this.isSynchronized())
  17873. return;
  17874. this._cache.parent = this.parent;
  17875. this._updateCache();
  17876. };
  17877. // override it in derived class if you add new variables to the cache
  17878. // and call the parent class method if !ignoreParentClass
  17879. /** @hidden */
  17880. Node.prototype._updateCache = function (ignoreParentClass) {
  17881. };
  17882. // override it in derived class if you add new variables to the cache
  17883. /** @hidden */
  17884. Node.prototype._isSynchronized = function () {
  17885. return true;
  17886. };
  17887. /** @hidden */
  17888. Node.prototype._markSyncedWithParent = function () {
  17889. if (this._parentNode) {
  17890. this._parentRenderId = this._parentNode._childRenderId;
  17891. }
  17892. };
  17893. /** @hidden */
  17894. Node.prototype.isSynchronizedWithParent = function () {
  17895. if (!this._parentNode) {
  17896. return true;
  17897. }
  17898. if (this._parentRenderId !== this._parentNode._childRenderId) {
  17899. return false;
  17900. }
  17901. return this._parentNode.isSynchronized();
  17902. };
  17903. /** @hidden */
  17904. Node.prototype.isSynchronized = function () {
  17905. if (this._cache.parent != this._parentNode) {
  17906. this._cache.parent = this._parentNode;
  17907. return false;
  17908. }
  17909. if (this._parentNode) {
  17910. if (!this.isSynchronizedWithParent()) {
  17911. return false;
  17912. }
  17913. }
  17914. return this._isSynchronized();
  17915. };
  17916. /**
  17917. * Is this node ready to be used/rendered
  17918. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17919. * @return true if the node is ready
  17920. */
  17921. Node.prototype.isReady = function (completeCheck) {
  17922. if (completeCheck === void 0) { completeCheck = false; }
  17923. return this._isReady;
  17924. };
  17925. /**
  17926. * Is this node enabled?
  17927. * 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
  17928. * @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
  17929. * @return whether this node (and its parent) is enabled
  17930. */
  17931. Node.prototype.isEnabled = function (checkAncestors) {
  17932. if (checkAncestors === void 0) { checkAncestors = true; }
  17933. if (checkAncestors === false) {
  17934. return this._isEnabled;
  17935. }
  17936. if (this._isEnabled === false) {
  17937. return false;
  17938. }
  17939. if (this._parentNode !== undefined && this._parentNode !== null) {
  17940. return this._parentNode.isEnabled(checkAncestors);
  17941. }
  17942. return true;
  17943. };
  17944. /**
  17945. * Set the enabled state of this node
  17946. * @param value defines the new enabled state
  17947. */
  17948. Node.prototype.setEnabled = function (value) {
  17949. this._isEnabled = value;
  17950. };
  17951. /**
  17952. * Is this node a descendant of the given node?
  17953. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17954. * @param ancestor defines the parent node to inspect
  17955. * @returns a boolean indicating if this node is a descendant of the given node
  17956. */
  17957. Node.prototype.isDescendantOf = function (ancestor) {
  17958. if (this.parent) {
  17959. if (this.parent === ancestor) {
  17960. return true;
  17961. }
  17962. return this.parent.isDescendantOf(ancestor);
  17963. }
  17964. return false;
  17965. };
  17966. /** @hidden */
  17967. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17968. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17969. if (!this._children) {
  17970. return;
  17971. }
  17972. for (var index = 0; index < this._children.length; index++) {
  17973. var item = this._children[index];
  17974. if (!predicate || predicate(item)) {
  17975. results.push(item);
  17976. }
  17977. if (!directDescendantsOnly) {
  17978. item._getDescendants(results, false, predicate);
  17979. }
  17980. }
  17981. };
  17982. /**
  17983. * Will return all nodes that have this node as ascendant
  17984. * @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
  17985. * @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
  17986. * @return all children nodes of all types
  17987. */
  17988. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17989. var results = new Array();
  17990. this._getDescendants(results, directDescendantsOnly, predicate);
  17991. return results;
  17992. };
  17993. /**
  17994. * Get all child-meshes of this node
  17995. * @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
  17996. * @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
  17997. * @returns an array of {BABYLON.AbstractMesh}
  17998. */
  17999. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18000. var results = [];
  18001. this._getDescendants(results, directDescendantsOnly, function (node) {
  18002. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18003. });
  18004. return results;
  18005. };
  18006. /**
  18007. * Get all child-transformNodes of this node
  18008. * @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
  18009. * @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
  18010. * @returns an array of {BABYLON.TransformNode}
  18011. */
  18012. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18013. var results = [];
  18014. this._getDescendants(results, directDescendantsOnly, function (node) {
  18015. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18016. });
  18017. return results;
  18018. };
  18019. /**
  18020. * Get all direct children of this node
  18021. * @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
  18022. * @returns an array of {BABYLON.Node}
  18023. */
  18024. Node.prototype.getChildren = function (predicate) {
  18025. if (!predicate) {
  18026. return this._children;
  18027. }
  18028. return this.getDescendants(true, predicate);
  18029. };
  18030. /** @hidden */
  18031. Node.prototype._setReady = function (state) {
  18032. if (state === this._isReady) {
  18033. return;
  18034. }
  18035. if (!state) {
  18036. this._isReady = false;
  18037. return;
  18038. }
  18039. if (this.onReady) {
  18040. this.onReady(this);
  18041. }
  18042. this._isReady = true;
  18043. };
  18044. /**
  18045. * Get an animation by name
  18046. * @param name defines the name of the animation to look for
  18047. * @returns null if not found else the requested animation
  18048. */
  18049. Node.prototype.getAnimationByName = function (name) {
  18050. for (var i = 0; i < this.animations.length; i++) {
  18051. var animation = this.animations[i];
  18052. if (animation.name === name) {
  18053. return animation;
  18054. }
  18055. }
  18056. return null;
  18057. };
  18058. /**
  18059. * Creates an animation range for this node
  18060. * @param name defines the name of the range
  18061. * @param from defines the starting key
  18062. * @param to defines the end key
  18063. */
  18064. Node.prototype.createAnimationRange = function (name, from, to) {
  18065. // check name not already in use
  18066. if (!this._ranges[name]) {
  18067. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18068. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18069. if (this.animations[i]) {
  18070. this.animations[i].createRange(name, from, to);
  18071. }
  18072. }
  18073. }
  18074. };
  18075. /**
  18076. * Delete a specific animation range
  18077. * @param name defines the name of the range to delete
  18078. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18079. */
  18080. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18081. if (deleteFrames === void 0) { deleteFrames = true; }
  18082. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18083. if (this.animations[i]) {
  18084. this.animations[i].deleteRange(name, deleteFrames);
  18085. }
  18086. }
  18087. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18088. };
  18089. /**
  18090. * Get an animation range by name
  18091. * @param name defines the name of the animation range to look for
  18092. * @returns null if not found else the requested animation range
  18093. */
  18094. Node.prototype.getAnimationRange = function (name) {
  18095. return this._ranges[name];
  18096. };
  18097. /**
  18098. * Will start the animation sequence
  18099. * @param name defines the range frames for animation sequence
  18100. * @param loop defines if the animation should loop (false by default)
  18101. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18102. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18103. * @returns the object created for this animation. If range does not exist, it will return null
  18104. */
  18105. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18106. var range = this.getAnimationRange(name);
  18107. if (!range) {
  18108. return null;
  18109. }
  18110. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18111. };
  18112. /**
  18113. * Serialize animation ranges into a JSON compatible object
  18114. * @returns serialization object
  18115. */
  18116. Node.prototype.serializeAnimationRanges = function () {
  18117. var serializationRanges = [];
  18118. for (var name in this._ranges) {
  18119. var localRange = this._ranges[name];
  18120. if (!localRange) {
  18121. continue;
  18122. }
  18123. var range = {};
  18124. range.name = name;
  18125. range.from = localRange.from;
  18126. range.to = localRange.to;
  18127. serializationRanges.push(range);
  18128. }
  18129. return serializationRanges;
  18130. };
  18131. /**
  18132. * Computes the world matrix of the node
  18133. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18134. * @returns the world matrix
  18135. */
  18136. Node.prototype.computeWorldMatrix = function (force) {
  18137. if (!this._worldMatrix) {
  18138. this._worldMatrix = BABYLON.Matrix.Identity();
  18139. }
  18140. return this._worldMatrix;
  18141. };
  18142. /**
  18143. * Releases resources associated with this node.
  18144. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18145. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18146. */
  18147. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18148. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18149. if (!doNotRecurse) {
  18150. var nodes = this.getDescendants(true);
  18151. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18152. var node = nodes_1[_i];
  18153. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18154. }
  18155. }
  18156. else {
  18157. var transformNodes = this.getChildTransformNodes(true);
  18158. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18159. var transformNode = transformNodes_1[_a];
  18160. transformNode.parent = null;
  18161. transformNode.computeWorldMatrix(true);
  18162. }
  18163. }
  18164. if (!this.parent) {
  18165. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18166. if (rootNodeIndex > -1) {
  18167. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18168. }
  18169. }
  18170. else {
  18171. this.parent = null;
  18172. }
  18173. // Callback
  18174. this.onDisposeObservable.notifyObservers(this);
  18175. this.onDisposeObservable.clear();
  18176. // Behaviors
  18177. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18178. var behavior = _c[_b];
  18179. behavior.detach();
  18180. }
  18181. this._behaviors = [];
  18182. this._isDisposed = true;
  18183. };
  18184. /**
  18185. * Parse animation range data from a serialization object and store them into a given node
  18186. * @param node defines where to store the animation ranges
  18187. * @param parsedNode defines the serialization object to read data from
  18188. * @param scene defines the hosting scene
  18189. */
  18190. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18191. if (parsedNode.ranges) {
  18192. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18193. var data = parsedNode.ranges[index];
  18194. node.createAnimationRange(data.name, data.from, data.to);
  18195. }
  18196. }
  18197. };
  18198. Node._NodeConstructors = {};
  18199. __decorate([
  18200. BABYLON.serialize()
  18201. ], Node.prototype, "name", void 0);
  18202. __decorate([
  18203. BABYLON.serialize()
  18204. ], Node.prototype, "id", void 0);
  18205. __decorate([
  18206. BABYLON.serialize()
  18207. ], Node.prototype, "uniqueId", void 0);
  18208. __decorate([
  18209. BABYLON.serialize()
  18210. ], Node.prototype, "state", void 0);
  18211. __decorate([
  18212. BABYLON.serialize()
  18213. ], Node.prototype, "metadata", void 0);
  18214. return Node;
  18215. }());
  18216. BABYLON.Node = Node;
  18217. })(BABYLON || (BABYLON = {}));
  18218. //# sourceMappingURL=babylon.node.js.map
  18219. var BABYLON;
  18220. (function (BABYLON) {
  18221. // This matrix is used as a value to reset the bounding box.
  18222. var _identityMatrix = BABYLON.Matrix.Identity();
  18223. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18224. var BoundingSphere = /** @class */ (function () {
  18225. /**
  18226. * Creates a new bounding sphere
  18227. * @param min defines the minimum vector (in local space)
  18228. * @param max defines the maximum vector (in local space)
  18229. */
  18230. function BoundingSphere(min, max) {
  18231. this.center = BABYLON.Vector3.Zero();
  18232. this.centerWorld = BABYLON.Vector3.Zero();
  18233. this.reConstruct(min, max);
  18234. }
  18235. /**
  18236. * Recreates the entire bounding sphere from scratch
  18237. * @param min defines the new minimum vector (in local space)
  18238. * @param max defines the new maximum vector (in local space)
  18239. */
  18240. BoundingSphere.prototype.reConstruct = function (min, max) {
  18241. this.minimum = min.clone();
  18242. this.maximum = max.clone();
  18243. var distance = BABYLON.Vector3.Distance(min, max);
  18244. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18245. this.radius = distance * 0.5;
  18246. this.centerWorld.set(0, 0, 0);
  18247. this._update(_identityMatrix);
  18248. };
  18249. /**
  18250. * Scale the current bounding sphere by applying a scale factor
  18251. * @param factor defines the scale factor to apply
  18252. * @returns the current bounding box
  18253. */
  18254. BoundingSphere.prototype.scale = function (factor) {
  18255. var newRadius = this.radius * factor;
  18256. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18257. var min = this.center.subtract(_tempRadiusVector);
  18258. var max = this.center.add(_tempRadiusVector);
  18259. this.reConstruct(min, max);
  18260. return this;
  18261. };
  18262. // Methods
  18263. /** @hidden */
  18264. BoundingSphere.prototype._update = function (world) {
  18265. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18266. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18267. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18268. };
  18269. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18270. for (var i = 0; i < 6; i++) {
  18271. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18272. return false;
  18273. }
  18274. return true;
  18275. };
  18276. BoundingSphere.prototype.intersectsPoint = function (point) {
  18277. var x = this.centerWorld.x - point.x;
  18278. var y = this.centerWorld.y - point.y;
  18279. var z = this.centerWorld.z - point.z;
  18280. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18281. if (this.radiusWorld < distance)
  18282. return false;
  18283. return true;
  18284. };
  18285. // Statics
  18286. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18287. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18288. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18289. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18290. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18291. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18292. return false;
  18293. return true;
  18294. };
  18295. return BoundingSphere;
  18296. }());
  18297. BABYLON.BoundingSphere = BoundingSphere;
  18298. })(BABYLON || (BABYLON = {}));
  18299. //# sourceMappingURL=babylon.boundingSphere.js.map
  18300. var BABYLON;
  18301. (function (BABYLON) {
  18302. var BoundingBox = /** @class */ (function () {
  18303. /**
  18304. * Creates a new bounding box
  18305. * @param min defines the minimum vector (in local space)
  18306. * @param max defines the maximum vector (in local space)
  18307. */
  18308. function BoundingBox(min, max) {
  18309. this.vectorsWorld = new Array();
  18310. this.reConstruct(min, max);
  18311. }
  18312. // Methods
  18313. /**
  18314. * Recreates the entire bounding box from scratch
  18315. * @param min defines the new minimum vector (in local space)
  18316. * @param max defines the new maximum vector (in local space)
  18317. */
  18318. BoundingBox.prototype.reConstruct = function (min, max) {
  18319. this.minimum = min.clone();
  18320. this.maximum = max.clone();
  18321. // Bounding vectors
  18322. this.vectors = [
  18323. this.minimum.clone(),
  18324. this.maximum.clone(),
  18325. this.minimum.clone(),
  18326. this.minimum.clone(),
  18327. this.minimum.clone(),
  18328. this.maximum.clone(),
  18329. this.maximum.clone(),
  18330. this.maximum.clone()
  18331. ];
  18332. this.vectors[2].x = this.maximum.x;
  18333. this.vectors[3].y = this.maximum.y;
  18334. this.vectors[4].z = this.maximum.z;
  18335. this.vectors[5].z = this.minimum.z;
  18336. this.vectors[6].x = this.minimum.x;
  18337. this.vectors[7].y = this.minimum.y;
  18338. // OBB
  18339. this.center = this.maximum.add(this.minimum).scale(0.5);
  18340. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18341. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18342. // World
  18343. for (var index = 0; index < this.vectors.length; index++) {
  18344. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18345. }
  18346. this.minimumWorld = BABYLON.Vector3.Zero();
  18347. this.maximumWorld = BABYLON.Vector3.Zero();
  18348. this.centerWorld = BABYLON.Vector3.Zero();
  18349. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18350. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18351. };
  18352. /**
  18353. * Scale the current bounding box by applying a scale factor
  18354. * @param factor defines the scale factor to apply
  18355. * @returns the current bounding box
  18356. */
  18357. BoundingBox.prototype.scale = function (factor) {
  18358. var diff = this.maximum.subtract(this.minimum);
  18359. var distance = diff.length() * factor;
  18360. diff.normalize();
  18361. var newRadius = diff.scale(distance / 2);
  18362. var min = this.center.subtract(newRadius);
  18363. var max = this.center.add(newRadius);
  18364. this.reConstruct(min, max);
  18365. return this;
  18366. };
  18367. BoundingBox.prototype.getWorldMatrix = function () {
  18368. return this._worldMatrix;
  18369. };
  18370. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18371. this._worldMatrix.copyFrom(matrix);
  18372. return this;
  18373. };
  18374. /** @hidden */
  18375. BoundingBox.prototype._update = function (world) {
  18376. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18377. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18378. for (var index = 0; index < this.vectors.length; index++) {
  18379. var v = this.vectorsWorld[index];
  18380. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18381. if (v.x < this.minimumWorld.x)
  18382. this.minimumWorld.x = v.x;
  18383. if (v.y < this.minimumWorld.y)
  18384. this.minimumWorld.y = v.y;
  18385. if (v.z < this.minimumWorld.z)
  18386. this.minimumWorld.z = v.z;
  18387. if (v.x > this.maximumWorld.x)
  18388. this.maximumWorld.x = v.x;
  18389. if (v.y > this.maximumWorld.y)
  18390. this.maximumWorld.y = v.y;
  18391. if (v.z > this.maximumWorld.z)
  18392. this.maximumWorld.z = v.z;
  18393. }
  18394. // Extend
  18395. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18396. this.extendSizeWorld.scaleInPlace(0.5);
  18397. // OBB
  18398. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18399. this.centerWorld.scaleInPlace(0.5);
  18400. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18401. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18402. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18403. this._worldMatrix = world;
  18404. };
  18405. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18406. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18407. };
  18408. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18409. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18410. };
  18411. BoundingBox.prototype.intersectsPoint = function (point) {
  18412. var delta = -BABYLON.Epsilon;
  18413. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18414. return false;
  18415. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18416. return false;
  18417. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18418. return false;
  18419. return true;
  18420. };
  18421. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18422. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18423. };
  18424. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18425. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18426. return false;
  18427. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18428. return false;
  18429. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18430. return false;
  18431. return true;
  18432. };
  18433. // Statics
  18434. BoundingBox.Intersects = function (box0, box1) {
  18435. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18436. return false;
  18437. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18438. return false;
  18439. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18440. return false;
  18441. return true;
  18442. };
  18443. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18444. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18445. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18446. return (num <= (sphereRadius * sphereRadius));
  18447. };
  18448. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18449. for (var p = 0; p < 6; p++) {
  18450. for (var i = 0; i < 8; i++) {
  18451. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18452. return false;
  18453. }
  18454. }
  18455. }
  18456. return true;
  18457. };
  18458. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18459. for (var p = 0; p < 6; p++) {
  18460. var inCount = 8;
  18461. for (var i = 0; i < 8; i++) {
  18462. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18463. --inCount;
  18464. }
  18465. else {
  18466. break;
  18467. }
  18468. }
  18469. if (inCount === 0)
  18470. return false;
  18471. }
  18472. return true;
  18473. };
  18474. return BoundingBox;
  18475. }());
  18476. BABYLON.BoundingBox = BoundingBox;
  18477. })(BABYLON || (BABYLON = {}));
  18478. //# sourceMappingURL=babylon.boundingBox.js.map
  18479. var BABYLON;
  18480. (function (BABYLON) {
  18481. var computeBoxExtents = function (axis, box) {
  18482. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18483. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18484. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18485. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18486. var r = r0 + r1 + r2;
  18487. return {
  18488. min: p - r,
  18489. max: p + r
  18490. };
  18491. };
  18492. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18493. var axisOverlap = function (axis, box0, box1) {
  18494. var result0 = computeBoxExtents(axis, box0);
  18495. var result1 = computeBoxExtents(axis, box1);
  18496. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18497. };
  18498. var BoundingInfo = /** @class */ (function () {
  18499. function BoundingInfo(minimum, maximum) {
  18500. this.minimum = minimum;
  18501. this.maximum = maximum;
  18502. this._isLocked = false;
  18503. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18504. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18505. }
  18506. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18507. get: function () {
  18508. return this._isLocked;
  18509. },
  18510. set: function (value) {
  18511. this._isLocked = value;
  18512. },
  18513. enumerable: true,
  18514. configurable: true
  18515. });
  18516. // Methods
  18517. BoundingInfo.prototype.update = function (world) {
  18518. if (this._isLocked) {
  18519. return;
  18520. }
  18521. this.boundingBox._update(world);
  18522. this.boundingSphere._update(world);
  18523. };
  18524. /**
  18525. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18526. * @param center New center of the bounding info
  18527. * @param extend New extend of the bounding info
  18528. */
  18529. BoundingInfo.prototype.centerOn = function (center, extend) {
  18530. this.minimum = center.subtract(extend);
  18531. this.maximum = center.add(extend);
  18532. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18533. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18534. return this;
  18535. };
  18536. /**
  18537. * Scale the current bounding info by applying a scale factor
  18538. * @param factor defines the scale factor to apply
  18539. * @returns the current bounding info
  18540. */
  18541. BoundingInfo.prototype.scale = function (factor) {
  18542. this.boundingBox.scale(factor);
  18543. this.boundingSphere.scale(factor);
  18544. return this;
  18545. };
  18546. /**
  18547. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18548. * @param frustumPlanes defines the frustum to test
  18549. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18550. * @returns true if the bounding info is in the frustum planes
  18551. */
  18552. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18553. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18554. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18555. return false;
  18556. }
  18557. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18558. return true;
  18559. }
  18560. return this.boundingBox.isInFrustum(frustumPlanes);
  18561. };
  18562. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18563. /**
  18564. * Gets the world distance between the min and max points of the bounding box
  18565. */
  18566. get: function () {
  18567. var boundingBox = this.boundingBox;
  18568. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18569. return size.length();
  18570. },
  18571. enumerable: true,
  18572. configurable: true
  18573. });
  18574. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18575. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18576. };
  18577. /** @hidden */
  18578. BoundingInfo.prototype._checkCollision = function (collider) {
  18579. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18580. };
  18581. BoundingInfo.prototype.intersectsPoint = function (point) {
  18582. if (!this.boundingSphere.centerWorld) {
  18583. return false;
  18584. }
  18585. if (!this.boundingSphere.intersectsPoint(point)) {
  18586. return false;
  18587. }
  18588. if (!this.boundingBox.intersectsPoint(point)) {
  18589. return false;
  18590. }
  18591. return true;
  18592. };
  18593. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18594. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18595. return false;
  18596. }
  18597. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18598. return false;
  18599. }
  18600. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18601. return false;
  18602. }
  18603. if (!precise) {
  18604. return true;
  18605. }
  18606. var box0 = this.boundingBox;
  18607. var box1 = boundingInfo.boundingBox;
  18608. if (!axisOverlap(box0.directions[0], box0, box1))
  18609. return false;
  18610. if (!axisOverlap(box0.directions[1], box0, box1))
  18611. return false;
  18612. if (!axisOverlap(box0.directions[2], box0, box1))
  18613. return false;
  18614. if (!axisOverlap(box1.directions[0], box0, box1))
  18615. return false;
  18616. if (!axisOverlap(box1.directions[1], box0, box1))
  18617. return false;
  18618. if (!axisOverlap(box1.directions[2], box0, box1))
  18619. return false;
  18620. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18621. return false;
  18622. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18623. return false;
  18624. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18625. return false;
  18626. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18627. return false;
  18628. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18629. return false;
  18630. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18631. return false;
  18632. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18633. return false;
  18634. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18635. return false;
  18636. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18637. return false;
  18638. return true;
  18639. };
  18640. return BoundingInfo;
  18641. }());
  18642. BABYLON.BoundingInfo = BoundingInfo;
  18643. })(BABYLON || (BABYLON = {}));
  18644. //# sourceMappingURL=babylon.boundingInfo.js.map
  18645. var BABYLON;
  18646. (function (BABYLON) {
  18647. var TransformNode = /** @class */ (function (_super) {
  18648. __extends(TransformNode, _super);
  18649. function TransformNode(name, scene, isPure) {
  18650. if (scene === void 0) { scene = null; }
  18651. if (isPure === void 0) { isPure = true; }
  18652. var _this = _super.call(this, name, scene) || this;
  18653. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18654. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18655. _this._up = new BABYLON.Vector3(0, 1, 0);
  18656. _this._right = new BABYLON.Vector3(1, 0, 0);
  18657. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18658. // Properties
  18659. _this._position = BABYLON.Vector3.Zero();
  18660. _this._rotation = BABYLON.Vector3.Zero();
  18661. _this._scaling = BABYLON.Vector3.One();
  18662. _this._isDirty = false;
  18663. /**
  18664. * Set the billboard mode. Default is 0.
  18665. *
  18666. * | Value | Type | Description |
  18667. * | --- | --- | --- |
  18668. * | 0 | BILLBOARDMODE_NONE | |
  18669. * | 1 | BILLBOARDMODE_X | |
  18670. * | 2 | BILLBOARDMODE_Y | |
  18671. * | 4 | BILLBOARDMODE_Z | |
  18672. * | 7 | BILLBOARDMODE_ALL | |
  18673. *
  18674. */
  18675. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18676. _this.scalingDeterminant = 1;
  18677. _this.infiniteDistance = false;
  18678. /**
  18679. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18680. * By default the system will update normals to compensate
  18681. */
  18682. _this.ignoreNonUniformScaling = false;
  18683. _this._localWorld = BABYLON.Matrix.Zero();
  18684. _this._absolutePosition = BABYLON.Vector3.Zero();
  18685. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18686. _this._postMultiplyPivotMatrix = false;
  18687. _this._isWorldMatrixFrozen = false;
  18688. /**
  18689. * An event triggered after the world matrix is updated
  18690. */
  18691. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18692. _this._nonUniformScaling = false;
  18693. if (isPure) {
  18694. _this.getScene().addTransformNode(_this);
  18695. }
  18696. return _this;
  18697. }
  18698. /**
  18699. * Gets a string identifying the name of the class
  18700. * @returns "TransformNode" string
  18701. */
  18702. TransformNode.prototype.getClassName = function () {
  18703. return "TransformNode";
  18704. };
  18705. Object.defineProperty(TransformNode.prototype, "position", {
  18706. /**
  18707. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  18708. */
  18709. get: function () {
  18710. return this._position;
  18711. },
  18712. set: function (newPosition) {
  18713. this._position = newPosition;
  18714. this._isDirty = true;
  18715. },
  18716. enumerable: true,
  18717. configurable: true
  18718. });
  18719. Object.defineProperty(TransformNode.prototype, "rotation", {
  18720. /**
  18721. * 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)).
  18722. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  18723. */
  18724. get: function () {
  18725. return this._rotation;
  18726. },
  18727. set: function (newRotation) {
  18728. this._rotation = newRotation;
  18729. this._isDirty = true;
  18730. },
  18731. enumerable: true,
  18732. configurable: true
  18733. });
  18734. Object.defineProperty(TransformNode.prototype, "scaling", {
  18735. /**
  18736. * 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)).
  18737. */
  18738. get: function () {
  18739. return this._scaling;
  18740. },
  18741. set: function (newScaling) {
  18742. this._scaling = newScaling;
  18743. this._isDirty = true;
  18744. },
  18745. enumerable: true,
  18746. configurable: true
  18747. });
  18748. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18749. /**
  18750. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  18751. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  18752. */
  18753. get: function () {
  18754. return this._rotationQuaternion;
  18755. },
  18756. set: function (quaternion) {
  18757. this._rotationQuaternion = quaternion;
  18758. //reset the rotation vector.
  18759. if (quaternion && this.rotation.length()) {
  18760. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18761. }
  18762. },
  18763. enumerable: true,
  18764. configurable: true
  18765. });
  18766. Object.defineProperty(TransformNode.prototype, "forward", {
  18767. /**
  18768. * The forward direction of that transform in world space.
  18769. */
  18770. get: function () {
  18771. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18772. },
  18773. enumerable: true,
  18774. configurable: true
  18775. });
  18776. Object.defineProperty(TransformNode.prototype, "up", {
  18777. /**
  18778. * The up direction of that transform in world space.
  18779. */
  18780. get: function () {
  18781. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18782. },
  18783. enumerable: true,
  18784. configurable: true
  18785. });
  18786. Object.defineProperty(TransformNode.prototype, "right", {
  18787. /**
  18788. * The right direction of that transform in world space.
  18789. */
  18790. get: function () {
  18791. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18792. },
  18793. enumerable: true,
  18794. configurable: true
  18795. });
  18796. /**
  18797. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18798. * Returns the TransformNode.
  18799. */
  18800. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18801. this._poseMatrix.copyFrom(matrix);
  18802. return this;
  18803. };
  18804. /**
  18805. * Returns the mesh Pose matrix.
  18806. * Returned object : Matrix
  18807. */
  18808. TransformNode.prototype.getPoseMatrix = function () {
  18809. return this._poseMatrix;
  18810. };
  18811. /** @hidden */
  18812. TransformNode.prototype._isSynchronized = function () {
  18813. if (this._isDirty) {
  18814. return false;
  18815. }
  18816. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18817. return false;
  18818. if (this._cache.pivotMatrixUpdated) {
  18819. return false;
  18820. }
  18821. if (this.infiniteDistance) {
  18822. return false;
  18823. }
  18824. if (!this._cache.position.equals(this._position))
  18825. return false;
  18826. if (this._rotationQuaternion) {
  18827. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18828. return false;
  18829. }
  18830. if (!this._cache.rotation.equals(this._rotation))
  18831. return false;
  18832. if (!this._cache.scaling.equals(this._scaling))
  18833. return false;
  18834. return true;
  18835. };
  18836. /** @hidden */
  18837. TransformNode.prototype._initCache = function () {
  18838. _super.prototype._initCache.call(this);
  18839. this._cache.localMatrixUpdated = false;
  18840. this._cache.position = BABYLON.Vector3.Zero();
  18841. this._cache.scaling = BABYLON.Vector3.Zero();
  18842. this._cache.rotation = BABYLON.Vector3.Zero();
  18843. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18844. this._cache.billboardMode = -1;
  18845. };
  18846. TransformNode.prototype.markAsDirty = function (property) {
  18847. if (property === "rotation") {
  18848. this.rotationQuaternion = null;
  18849. }
  18850. this._currentRenderId = Number.MAX_VALUE;
  18851. this._isDirty = true;
  18852. return this;
  18853. };
  18854. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18855. /**
  18856. * Returns the current mesh absolute position.
  18857. * Returns a Vector3.
  18858. */
  18859. get: function () {
  18860. return this._absolutePosition;
  18861. },
  18862. enumerable: true,
  18863. configurable: true
  18864. });
  18865. /**
  18866. * Sets a new matrix to apply before all other transformation
  18867. * @param matrix defines the transform matrix
  18868. * @returns the current TransformNode
  18869. */
  18870. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18871. return this.setPivotMatrix(matrix, false);
  18872. };
  18873. /**
  18874. * Sets a new pivot matrix to the current node
  18875. * @param matrix defines the new pivot matrix to use
  18876. * @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
  18877. * @returns the current TransformNode
  18878. */
  18879. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18880. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18881. this._pivotMatrix = matrix.clone();
  18882. this._cache.pivotMatrixUpdated = true;
  18883. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18884. if (this._postMultiplyPivotMatrix) {
  18885. if (!this._pivotMatrixInverse) {
  18886. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18887. }
  18888. else {
  18889. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18890. }
  18891. }
  18892. return this;
  18893. };
  18894. /**
  18895. * Returns the mesh pivot matrix.
  18896. * Default : Identity.
  18897. * A Matrix is returned.
  18898. */
  18899. TransformNode.prototype.getPivotMatrix = function () {
  18900. return this._pivotMatrix;
  18901. };
  18902. /**
  18903. * Prevents the World matrix to be computed any longer.
  18904. * Returns the TransformNode.
  18905. */
  18906. TransformNode.prototype.freezeWorldMatrix = function () {
  18907. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18908. this.computeWorldMatrix(true);
  18909. this._isWorldMatrixFrozen = true;
  18910. return this;
  18911. };
  18912. /**
  18913. * Allows back the World matrix computation.
  18914. * Returns the TransformNode.
  18915. */
  18916. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18917. this._isWorldMatrixFrozen = false;
  18918. this.computeWorldMatrix(true);
  18919. return this;
  18920. };
  18921. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18922. /**
  18923. * True if the World matrix has been frozen.
  18924. * Returns a boolean.
  18925. */
  18926. get: function () {
  18927. return this._isWorldMatrixFrozen;
  18928. },
  18929. enumerable: true,
  18930. configurable: true
  18931. });
  18932. /**
  18933. * Retuns the mesh absolute position in the World.
  18934. * Returns a Vector3.
  18935. */
  18936. TransformNode.prototype.getAbsolutePosition = function () {
  18937. this.computeWorldMatrix();
  18938. return this._absolutePosition;
  18939. };
  18940. /**
  18941. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18942. * Returns the TransformNode.
  18943. */
  18944. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18945. if (!absolutePosition) {
  18946. return this;
  18947. }
  18948. var absolutePositionX;
  18949. var absolutePositionY;
  18950. var absolutePositionZ;
  18951. if (absolutePosition.x === undefined) {
  18952. if (arguments.length < 3) {
  18953. return this;
  18954. }
  18955. absolutePositionX = arguments[0];
  18956. absolutePositionY = arguments[1];
  18957. absolutePositionZ = arguments[2];
  18958. }
  18959. else {
  18960. absolutePositionX = absolutePosition.x;
  18961. absolutePositionY = absolutePosition.y;
  18962. absolutePositionZ = absolutePosition.z;
  18963. }
  18964. if (this.parent) {
  18965. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18966. invertParentWorldMatrix.invert();
  18967. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18968. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18969. }
  18970. else {
  18971. this.position.x = absolutePositionX;
  18972. this.position.y = absolutePositionY;
  18973. this.position.z = absolutePositionZ;
  18974. }
  18975. return this;
  18976. };
  18977. /**
  18978. * Sets the mesh position in its local space.
  18979. * Returns the TransformNode.
  18980. */
  18981. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18982. this.computeWorldMatrix();
  18983. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18984. return this;
  18985. };
  18986. /**
  18987. * Returns the mesh position in the local space from the current World matrix values.
  18988. * Returns a new Vector3.
  18989. */
  18990. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18991. this.computeWorldMatrix();
  18992. var invLocalWorldMatrix = this._localWorld.clone();
  18993. invLocalWorldMatrix.invert();
  18994. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18995. };
  18996. /**
  18997. * Translates the mesh along the passed Vector3 in its local space.
  18998. * Returns the TransformNode.
  18999. */
  19000. TransformNode.prototype.locallyTranslate = function (vector3) {
  19001. this.computeWorldMatrix(true);
  19002. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19003. return this;
  19004. };
  19005. /**
  19006. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19007. * @param targetPoint the position (must be in same space as current mesh) to look at
  19008. * @param yawCor optional yaw (y-axis) correction in radians
  19009. * @param pitchCor optional pitch (x-axis) correction in radians
  19010. * @param rollCor optional roll (z-axis) correction in radians
  19011. * @param space the choosen space of the target
  19012. * @returns the TransformNode.
  19013. */
  19014. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19015. if (yawCor === void 0) { yawCor = 0; }
  19016. if (pitchCor === void 0) { pitchCor = 0; }
  19017. if (rollCor === void 0) { rollCor = 0; }
  19018. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19019. var dv = TransformNode._lookAtVectorCache;
  19020. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19021. targetPoint.subtractToRef(pos, dv);
  19022. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19023. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19024. var pitch = Math.atan2(dv.y, len);
  19025. if (this.rotationQuaternion) {
  19026. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19027. }
  19028. else {
  19029. this.rotation.x = pitch + pitchCor;
  19030. this.rotation.y = yaw + yawCor;
  19031. this.rotation.z = rollCor;
  19032. }
  19033. return this;
  19034. };
  19035. /**
  19036. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19037. * This Vector3 is expressed in the World space.
  19038. */
  19039. TransformNode.prototype.getDirection = function (localAxis) {
  19040. var result = BABYLON.Vector3.Zero();
  19041. this.getDirectionToRef(localAxis, result);
  19042. return result;
  19043. };
  19044. /**
  19045. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19046. * localAxis is expressed in the mesh local space.
  19047. * result is computed in the Wordl space from the mesh World matrix.
  19048. * Returns the TransformNode.
  19049. */
  19050. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19051. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19052. return this;
  19053. };
  19054. /**
  19055. * Sets a new pivot point to the current node
  19056. * @param point defines the new pivot point to use
  19057. * @param space defines if the point is in world or local space (local by default)
  19058. * @returns the current TransformNode
  19059. */
  19060. TransformNode.prototype.setPivotPoint = function (point, space) {
  19061. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19062. if (this.getScene().getRenderId() == 0) {
  19063. this.computeWorldMatrix(true);
  19064. }
  19065. var wm = this.getWorldMatrix();
  19066. if (space == BABYLON.Space.WORLD) {
  19067. var tmat = BABYLON.Tmp.Matrix[0];
  19068. wm.invertToRef(tmat);
  19069. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19070. }
  19071. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19072. };
  19073. /**
  19074. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19075. */
  19076. TransformNode.prototype.getPivotPoint = function () {
  19077. var point = BABYLON.Vector3.Zero();
  19078. this.getPivotPointToRef(point);
  19079. return point;
  19080. };
  19081. /**
  19082. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19083. * Returns the TransformNode.
  19084. */
  19085. TransformNode.prototype.getPivotPointToRef = function (result) {
  19086. result.x = -this._pivotMatrix.m[12];
  19087. result.y = -this._pivotMatrix.m[13];
  19088. result.z = -this._pivotMatrix.m[14];
  19089. return this;
  19090. };
  19091. /**
  19092. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19093. */
  19094. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19095. var point = BABYLON.Vector3.Zero();
  19096. this.getAbsolutePivotPointToRef(point);
  19097. return point;
  19098. };
  19099. /**
  19100. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19101. * Returns the TransformNode.
  19102. */
  19103. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19104. result.x = this._pivotMatrix.m[12];
  19105. result.y = this._pivotMatrix.m[13];
  19106. result.z = this._pivotMatrix.m[14];
  19107. this.getPivotPointToRef(result);
  19108. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19109. return this;
  19110. };
  19111. /**
  19112. * Defines the passed node as the parent of the current node.
  19113. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19114. * Returns the TransformNode.
  19115. */
  19116. TransformNode.prototype.setParent = function (node) {
  19117. if (!node && !this.parent) {
  19118. return this;
  19119. }
  19120. if (!node) {
  19121. var rotation = BABYLON.Tmp.Quaternion[0];
  19122. var position = BABYLON.Tmp.Vector3[0];
  19123. var scale = BABYLON.Tmp.Vector3[1];
  19124. if (this.parent && this.parent.computeWorldMatrix) {
  19125. this.parent.computeWorldMatrix(true);
  19126. }
  19127. this.computeWorldMatrix(true);
  19128. this.getWorldMatrix().decompose(scale, rotation, position);
  19129. if (this.rotationQuaternion) {
  19130. this.rotationQuaternion.copyFrom(rotation);
  19131. }
  19132. else {
  19133. rotation.toEulerAnglesToRef(this.rotation);
  19134. }
  19135. this.scaling.x = scale.x;
  19136. this.scaling.y = scale.y;
  19137. this.scaling.z = scale.z;
  19138. this.position.x = position.x;
  19139. this.position.y = position.y;
  19140. this.position.z = position.z;
  19141. }
  19142. else {
  19143. var rotation = BABYLON.Tmp.Quaternion[0];
  19144. var position = BABYLON.Tmp.Vector3[0];
  19145. var scale = BABYLON.Tmp.Vector3[1];
  19146. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19147. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19148. this.computeWorldMatrix(true);
  19149. node.computeWorldMatrix(true);
  19150. node.getWorldMatrix().invertToRef(invParentMatrix);
  19151. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19152. diffMatrix.decompose(scale, rotation, position);
  19153. if (this.rotationQuaternion) {
  19154. this.rotationQuaternion.copyFrom(rotation);
  19155. }
  19156. else {
  19157. rotation.toEulerAnglesToRef(this.rotation);
  19158. }
  19159. this.position.x = position.x;
  19160. this.position.y = position.y;
  19161. this.position.z = position.z;
  19162. this.scaling.x = scale.x;
  19163. this.scaling.y = scale.y;
  19164. this.scaling.z = scale.z;
  19165. }
  19166. this.parent = node;
  19167. return this;
  19168. };
  19169. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19170. get: function () {
  19171. return this._nonUniformScaling;
  19172. },
  19173. enumerable: true,
  19174. configurable: true
  19175. });
  19176. /** @hidden */
  19177. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19178. if (this._nonUniformScaling === value) {
  19179. return false;
  19180. }
  19181. this._nonUniformScaling = value;
  19182. return true;
  19183. };
  19184. /**
  19185. * Attach the current TransformNode to another TransformNode associated with a bone
  19186. * @param bone Bone affecting the TransformNode
  19187. * @param affectedTransformNode TransformNode associated with the bone
  19188. */
  19189. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19190. this._transformToBoneReferal = affectedTransformNode;
  19191. this.parent = bone;
  19192. if (bone.getWorldMatrix().determinant() < 0) {
  19193. this.scalingDeterminant *= -1;
  19194. }
  19195. return this;
  19196. };
  19197. TransformNode.prototype.detachFromBone = function () {
  19198. if (!this.parent) {
  19199. return this;
  19200. }
  19201. if (this.parent.getWorldMatrix().determinant() < 0) {
  19202. this.scalingDeterminant *= -1;
  19203. }
  19204. this._transformToBoneReferal = null;
  19205. this.parent = null;
  19206. return this;
  19207. };
  19208. /**
  19209. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19210. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19211. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19212. * The passed axis is also normalized.
  19213. * Returns the TransformNode.
  19214. */
  19215. TransformNode.prototype.rotate = function (axis, amount, space) {
  19216. axis.normalize();
  19217. if (!this.rotationQuaternion) {
  19218. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19219. this.rotation = BABYLON.Vector3.Zero();
  19220. }
  19221. var rotationQuaternion;
  19222. if (!space || space === BABYLON.Space.LOCAL) {
  19223. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19224. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19225. }
  19226. else {
  19227. if (this.parent) {
  19228. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19229. invertParentWorldMatrix.invert();
  19230. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19231. }
  19232. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19233. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19234. }
  19235. return this;
  19236. };
  19237. /**
  19238. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19239. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19240. * The passed axis is also normalized.
  19241. * Returns the TransformNode.
  19242. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19243. */
  19244. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19245. axis.normalize();
  19246. if (!this.rotationQuaternion) {
  19247. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19248. this.rotation.copyFromFloats(0, 0, 0);
  19249. }
  19250. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19251. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19252. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19253. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19254. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19255. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19256. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19257. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19258. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19259. return this;
  19260. };
  19261. /**
  19262. * Translates the mesh along the axis vector for the passed distance in the given space.
  19263. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19264. * Returns the TransformNode.
  19265. */
  19266. TransformNode.prototype.translate = function (axis, distance, space) {
  19267. var displacementVector = axis.scale(distance);
  19268. if (!space || space === BABYLON.Space.LOCAL) {
  19269. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19270. this.setPositionWithLocalVector(tempV3);
  19271. }
  19272. else {
  19273. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19274. }
  19275. return this;
  19276. };
  19277. /**
  19278. * Adds a rotation step to the mesh current rotation.
  19279. * x, y, z are Euler angles expressed in radians.
  19280. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19281. * This means this rotation is made in the mesh local space only.
  19282. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19283. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19284. * ```javascript
  19285. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19286. * ```
  19287. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19288. * 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.
  19289. * Returns the TransformNode.
  19290. */
  19291. TransformNode.prototype.addRotation = function (x, y, z) {
  19292. var rotationQuaternion;
  19293. if (this.rotationQuaternion) {
  19294. rotationQuaternion = this.rotationQuaternion;
  19295. }
  19296. else {
  19297. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19298. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19299. }
  19300. var accumulation = BABYLON.Tmp.Quaternion[0];
  19301. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19302. rotationQuaternion.multiplyInPlace(accumulation);
  19303. if (!this.rotationQuaternion) {
  19304. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19305. }
  19306. return this;
  19307. };
  19308. /**
  19309. * Computes the world matrix of the node
  19310. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19311. * @returns the world matrix
  19312. */
  19313. TransformNode.prototype.computeWorldMatrix = function (force) {
  19314. if (this._isWorldMatrixFrozen) {
  19315. return this._worldMatrix;
  19316. }
  19317. if (!force && this.isSynchronized()) {
  19318. this._currentRenderId = this.getScene().getRenderId();
  19319. return this._worldMatrix;
  19320. }
  19321. this._updateCache();
  19322. this._cache.position.copyFrom(this.position);
  19323. this._cache.scaling.copyFrom(this.scaling);
  19324. this._cache.pivotMatrixUpdated = false;
  19325. this._cache.billboardMode = this.billboardMode;
  19326. this._currentRenderId = this.getScene().getRenderId();
  19327. this._childRenderId = this.getScene().getRenderId();
  19328. this._isDirty = false;
  19329. // Scaling
  19330. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19331. // Rotation
  19332. //rotate, if quaternion is set and rotation was used
  19333. if (this.rotationQuaternion) {
  19334. var len = this.rotation.length();
  19335. if (len) {
  19336. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19337. this.rotation.copyFromFloats(0, 0, 0);
  19338. }
  19339. }
  19340. if (this.rotationQuaternion) {
  19341. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19342. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19343. }
  19344. else {
  19345. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19346. this._cache.rotation.copyFrom(this.rotation);
  19347. }
  19348. // Translation
  19349. var camera = this.getScene().activeCamera;
  19350. if (this.infiniteDistance && !this.parent && camera) {
  19351. var cameraWorldMatrix = camera.getWorldMatrix();
  19352. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19353. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19354. }
  19355. else {
  19356. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19357. }
  19358. // Composing transformations
  19359. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19360. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19361. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19362. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19363. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19364. // Need to decompose each rotation here
  19365. var currentPosition = BABYLON.Tmp.Vector3[3];
  19366. if (this.parent && this.parent.getWorldMatrix) {
  19367. if (this._transformToBoneReferal) {
  19368. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19369. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19370. }
  19371. else {
  19372. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19373. }
  19374. }
  19375. else {
  19376. currentPosition.copyFrom(this.position);
  19377. }
  19378. currentPosition.subtractInPlace(camera.globalPosition);
  19379. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19380. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19381. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19382. }
  19383. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19384. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19385. }
  19386. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19387. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19388. }
  19389. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19390. }
  19391. else {
  19392. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19393. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19394. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19395. }
  19396. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19397. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19398. }
  19399. // Post multiply inverse of pivotMatrix
  19400. if (this._postMultiplyPivotMatrix) {
  19401. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19402. }
  19403. // Local world
  19404. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19405. // Parent
  19406. if (this.parent && this.parent.getWorldMatrix) {
  19407. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19408. if (this._transformToBoneReferal) {
  19409. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19410. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19411. }
  19412. else {
  19413. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19414. }
  19415. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19416. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19417. this._worldMatrix.copyFrom(this._localWorld);
  19418. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19419. }
  19420. else {
  19421. if (this._transformToBoneReferal) {
  19422. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19423. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19424. }
  19425. else {
  19426. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19427. }
  19428. }
  19429. this._markSyncedWithParent();
  19430. }
  19431. else {
  19432. this._worldMatrix.copyFrom(this._localWorld);
  19433. }
  19434. // Normal matrix
  19435. if (!this.ignoreNonUniformScaling) {
  19436. if (this.scaling.isNonUniform) {
  19437. this._updateNonUniformScalingState(true);
  19438. }
  19439. else if (this.parent && this.parent._nonUniformScaling) {
  19440. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19441. }
  19442. else {
  19443. this._updateNonUniformScalingState(false);
  19444. }
  19445. }
  19446. else {
  19447. this._updateNonUniformScalingState(false);
  19448. }
  19449. this._afterComputeWorldMatrix();
  19450. // Absolute position
  19451. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19452. // Callbacks
  19453. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19454. if (!this._poseMatrix) {
  19455. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19456. }
  19457. // Cache the determinant
  19458. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19459. return this._worldMatrix;
  19460. };
  19461. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19462. };
  19463. /**
  19464. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19465. * @param func: callback function to add
  19466. *
  19467. * Returns the TransformNode.
  19468. */
  19469. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19470. this.onAfterWorldMatrixUpdateObservable.add(func);
  19471. return this;
  19472. };
  19473. /**
  19474. * Removes a registered callback function.
  19475. * Returns the TransformNode.
  19476. */
  19477. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19478. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19479. return this;
  19480. };
  19481. /**
  19482. * Clone the current transform node
  19483. * Returns the new transform node
  19484. * @param name Name of the new clone
  19485. * @param newParent New parent for the clone
  19486. * @param doNotCloneChildren Do not clone children hierarchy
  19487. */
  19488. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19489. var _this = this;
  19490. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19491. result.name = name;
  19492. result.id = name;
  19493. if (newParent) {
  19494. result.parent = newParent;
  19495. }
  19496. if (!doNotCloneChildren) {
  19497. // Children
  19498. var directDescendants = this.getDescendants(true);
  19499. for (var index = 0; index < directDescendants.length; index++) {
  19500. var child = directDescendants[index];
  19501. if (child.clone) {
  19502. child.clone(name + "." + child.name, result);
  19503. }
  19504. }
  19505. }
  19506. return result;
  19507. };
  19508. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19509. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19510. serializationObject.type = this.getClassName();
  19511. // Parent
  19512. if (this.parent) {
  19513. serializationObject.parentId = this.parent.id;
  19514. }
  19515. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19516. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19517. }
  19518. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19519. serializationObject.isEnabled = this.isEnabled();
  19520. // Parent
  19521. if (this.parent) {
  19522. serializationObject.parentId = this.parent.id;
  19523. }
  19524. return serializationObject;
  19525. };
  19526. // Statics
  19527. /**
  19528. * Returns a new TransformNode object parsed from the source provided.
  19529. * The parameter `parsedMesh` is the source.
  19530. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19531. */
  19532. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19533. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19534. if (BABYLON.Tags) {
  19535. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19536. }
  19537. if (parsedTransformNode.localMatrix) {
  19538. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19539. }
  19540. else if (parsedTransformNode.pivotMatrix) {
  19541. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19542. }
  19543. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19544. // Parent
  19545. if (parsedTransformNode.parentId) {
  19546. transformNode._waitingParentId = parsedTransformNode.parentId;
  19547. }
  19548. return transformNode;
  19549. };
  19550. /**
  19551. * Releases resources associated with this transform node.
  19552. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19553. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19554. */
  19555. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19556. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19557. // Animations
  19558. this.getScene().stopAnimation(this);
  19559. // Remove from scene
  19560. this.getScene().removeTransformNode(this);
  19561. this.onAfterWorldMatrixUpdateObservable.clear();
  19562. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19563. };
  19564. // Statics
  19565. TransformNode.BILLBOARDMODE_NONE = 0;
  19566. TransformNode.BILLBOARDMODE_X = 1;
  19567. TransformNode.BILLBOARDMODE_Y = 2;
  19568. TransformNode.BILLBOARDMODE_Z = 4;
  19569. TransformNode.BILLBOARDMODE_ALL = 7;
  19570. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19571. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19572. __decorate([
  19573. BABYLON.serializeAsVector3("position")
  19574. ], TransformNode.prototype, "_position", void 0);
  19575. __decorate([
  19576. BABYLON.serializeAsVector3("rotation")
  19577. ], TransformNode.prototype, "_rotation", void 0);
  19578. __decorate([
  19579. BABYLON.serializeAsQuaternion("rotationQuaternion")
  19580. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19581. __decorate([
  19582. BABYLON.serializeAsVector3("scaling")
  19583. ], TransformNode.prototype, "_scaling", void 0);
  19584. __decorate([
  19585. BABYLON.serialize()
  19586. ], TransformNode.prototype, "billboardMode", void 0);
  19587. __decorate([
  19588. BABYLON.serialize()
  19589. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19590. __decorate([
  19591. BABYLON.serialize()
  19592. ], TransformNode.prototype, "infiniteDistance", void 0);
  19593. __decorate([
  19594. BABYLON.serialize()
  19595. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19596. return TransformNode;
  19597. }(BABYLON.Node));
  19598. BABYLON.TransformNode = TransformNode;
  19599. })(BABYLON || (BABYLON = {}));
  19600. //# sourceMappingURL=babylon.transformNode.js.map
  19601. var BABYLON;
  19602. (function (BABYLON) {
  19603. /**
  19604. * Class used to store all common mesh properties
  19605. */
  19606. var AbstractMesh = /** @class */ (function (_super) {
  19607. __extends(AbstractMesh, _super);
  19608. // Constructor
  19609. /**
  19610. * Creates a new AbstractMesh
  19611. * @param name defines the name of the mesh
  19612. * @param scene defines the hosting scene
  19613. */
  19614. function AbstractMesh(name, scene) {
  19615. if (scene === void 0) { scene = null; }
  19616. var _this = _super.call(this, name, scene, false) || this;
  19617. _this._facetNb = 0; // facet number
  19618. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19619. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19620. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19621. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19622. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19623. _this._subDiv = {
  19624. max: 1,
  19625. X: 1,
  19626. Y: 1,
  19627. Z: 1
  19628. };
  19629. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19630. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19631. /** Gets ot sets the culling strategy to use to find visible meshes */
  19632. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19633. // Events
  19634. /**
  19635. * An event triggered when this mesh collides with another one
  19636. */
  19637. _this.onCollideObservable = new BABYLON.Observable();
  19638. /**
  19639. * An event triggered when the collision's position changes
  19640. */
  19641. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19642. /**
  19643. * An event triggered when material is changed
  19644. */
  19645. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19646. // Properties
  19647. /**
  19648. * Gets or sets the orientation for POV movement & rotation
  19649. */
  19650. _this.definedFacingForward = true;
  19651. /**
  19652. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19653. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19654. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  19655. * @see http://doc.babylonjs.com/features/occlusionquery
  19656. */
  19657. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19658. /**
  19659. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  19660. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19661. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19662. * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  19663. * @see http://doc.babylonjs.com/features/occlusionquery
  19664. */
  19665. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19666. /**
  19667. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  19668. * The default value is -1 which means don't break the query and wait till the result
  19669. * @see http://doc.babylonjs.com/features/occlusionquery
  19670. */
  19671. _this.occlusionRetryCount = -1;
  19672. /** @hidden */
  19673. _this._occlusionInternalRetryCounter = 0;
  19674. /** @hidden */
  19675. _this._isOccluded = false;
  19676. /** @hidden */
  19677. _this._isOcclusionQueryInProgress = false;
  19678. _this._visibility = 1.0;
  19679. /** Gets or sets the alpha index used to sort transparent meshes
  19680. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19681. */
  19682. _this.alphaIndex = Number.MAX_VALUE;
  19683. /**
  19684. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19685. */
  19686. _this.isVisible = true;
  19687. /**
  19688. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19689. */
  19690. _this.isPickable = true;
  19691. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19692. _this.showSubMeshesBoundingBox = false;
  19693. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19694. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19695. */
  19696. _this.isBlocker = false;
  19697. /**
  19698. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19699. */
  19700. _this.enablePointerMoveEvents = false;
  19701. /**
  19702. * Specifies the rendering group id for this mesh (0 by default)
  19703. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19704. */
  19705. _this.renderingGroupId = 0;
  19706. _this._receiveShadows = false;
  19707. /** Defines color to use when rendering outline */
  19708. _this.outlineColor = BABYLON.Color3.Red();
  19709. /** Define width to use when rendering outline */
  19710. _this.outlineWidth = 0.02;
  19711. /** Defines color to use when rendering overlay */
  19712. _this.overlayColor = BABYLON.Color3.Red();
  19713. /** Defines alpha to use when rendering overlay */
  19714. _this.overlayAlpha = 0.5;
  19715. _this._hasVertexAlpha = false;
  19716. _this._useVertexColors = true;
  19717. _this._computeBonesUsingShaders = true;
  19718. _this._numBoneInfluencers = 4;
  19719. _this._applyFog = true;
  19720. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19721. _this.useOctreeForRenderingSelection = true;
  19722. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19723. _this.useOctreeForPicking = true;
  19724. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19725. _this.useOctreeForCollisions = true;
  19726. _this._layerMask = 0x0FFFFFFF;
  19727. /**
  19728. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19729. */
  19730. _this.alwaysSelectAsActiveMesh = false;
  19731. /**
  19732. * Gets or sets the current action manager
  19733. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19734. */
  19735. _this.actionManager = null;
  19736. /**
  19737. * Gets or sets impostor used for physic simulation
  19738. * @see http://doc.babylonjs.com/features/physics_engine
  19739. */
  19740. _this.physicsImpostor = null;
  19741. // Collisions
  19742. _this._checkCollisions = false;
  19743. _this._collisionMask = -1;
  19744. _this._collisionGroup = -1;
  19745. /**
  19746. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19747. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19748. */
  19749. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19750. /**
  19751. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19752. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19753. */
  19754. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19755. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19756. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19757. // Edges
  19758. /**
  19759. * Defines edge width used when edgesRenderer is enabled
  19760. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19761. */
  19762. _this.edgesWidth = 1;
  19763. /**
  19764. * Defines edge color used when edgesRenderer is enabled
  19765. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19766. */
  19767. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19768. // Cache
  19769. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19770. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19771. /** @hidden */
  19772. _this._renderId = 0;
  19773. /** @hidden */
  19774. _this._intersectionsInProgress = new Array();
  19775. /** @hidden */
  19776. _this._unIndexed = false;
  19777. /** @hidden */
  19778. _this._lightSources = new Array();
  19779. /**
  19780. * An event triggered when the mesh is rebuilt.
  19781. */
  19782. _this.onRebuildObservable = new BABYLON.Observable();
  19783. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19784. if (collidedMesh === void 0) { collidedMesh = null; }
  19785. //TODO move this to the collision coordinator!
  19786. if (_this.getScene().workerCollisions)
  19787. newPosition.multiplyInPlace(_this._collider._radius);
  19788. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19789. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19790. _this.position.addInPlace(_this._diffPositionForCollisions);
  19791. }
  19792. if (collidedMesh) {
  19793. _this.onCollideObservable.notifyObservers(collidedMesh);
  19794. }
  19795. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19796. };
  19797. _this.getScene().addMesh(_this);
  19798. _this._resyncLightSources();
  19799. return _this;
  19800. }
  19801. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19802. /**
  19803. * No billboard
  19804. */
  19805. get: function () {
  19806. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19812. /** Billboard on X axis */
  19813. get: function () {
  19814. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19815. },
  19816. enumerable: true,
  19817. configurable: true
  19818. });
  19819. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19820. /** Billboard on Y axis */
  19821. get: function () {
  19822. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19823. },
  19824. enumerable: true,
  19825. configurable: true
  19826. });
  19827. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19828. /** Billboard on Z axis */
  19829. get: function () {
  19830. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19831. },
  19832. enumerable: true,
  19833. configurable: true
  19834. });
  19835. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19836. /** Billboard on all axes */
  19837. get: function () {
  19838. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19839. },
  19840. enumerable: true,
  19841. configurable: true
  19842. });
  19843. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19844. /**
  19845. * Gets the number of facets in the mesh
  19846. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19847. */
  19848. get: function () {
  19849. return this._facetNb;
  19850. },
  19851. enumerable: true,
  19852. configurable: true
  19853. });
  19854. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19855. /**
  19856. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19857. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19858. */
  19859. get: function () {
  19860. return this._partitioningSubdivisions;
  19861. },
  19862. set: function (nb) {
  19863. this._partitioningSubdivisions = nb;
  19864. },
  19865. enumerable: true,
  19866. configurable: true
  19867. });
  19868. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19869. /**
  19870. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19871. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19872. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19873. */
  19874. get: function () {
  19875. return this._partitioningBBoxRatio;
  19876. },
  19877. set: function (ratio) {
  19878. this._partitioningBBoxRatio = ratio;
  19879. },
  19880. enumerable: true,
  19881. configurable: true
  19882. });
  19883. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19884. /**
  19885. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19886. * Works only for updatable meshes.
  19887. * Doesn't work with multi-materials
  19888. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19889. */
  19890. get: function () {
  19891. return this._facetDepthSort;
  19892. },
  19893. set: function (sort) {
  19894. this._facetDepthSort = sort;
  19895. },
  19896. enumerable: true,
  19897. configurable: true
  19898. });
  19899. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19900. /**
  19901. * The location (Vector3) where the facet depth sort must be computed from.
  19902. * By default, the active camera position.
  19903. * Used only when facet depth sort is enabled
  19904. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19905. */
  19906. get: function () {
  19907. return this._facetDepthSortFrom;
  19908. },
  19909. set: function (location) {
  19910. this._facetDepthSortFrom = location;
  19911. },
  19912. enumerable: true,
  19913. configurable: true
  19914. });
  19915. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19916. /**
  19917. * gets a boolean indicating if facetData is enabled
  19918. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19919. */
  19920. get: function () {
  19921. return this._facetDataEnabled;
  19922. },
  19923. enumerable: true,
  19924. configurable: true
  19925. });
  19926. /** @hidden */
  19927. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19928. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19929. return false;
  19930. }
  19931. this._markSubMeshesAsMiscDirty();
  19932. return true;
  19933. };
  19934. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19935. /** Set a function to call when this mesh collides with another one */
  19936. set: function (callback) {
  19937. if (this._onCollideObserver) {
  19938. this.onCollideObservable.remove(this._onCollideObserver);
  19939. }
  19940. this._onCollideObserver = this.onCollideObservable.add(callback);
  19941. },
  19942. enumerable: true,
  19943. configurable: true
  19944. });
  19945. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19946. /** Set a function to call when the collision's position changes */
  19947. set: function (callback) {
  19948. if (this._onCollisionPositionChangeObserver) {
  19949. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19950. }
  19951. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19952. },
  19953. enumerable: true,
  19954. configurable: true
  19955. });
  19956. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19957. /**
  19958. * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not
  19959. * @see http://doc.babylonjs.com/features/occlusionquery
  19960. */
  19961. get: function () {
  19962. return this._isOccluded;
  19963. },
  19964. set: function (value) {
  19965. this._isOccluded = value;
  19966. },
  19967. enumerable: true,
  19968. configurable: true
  19969. });
  19970. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19971. /**
  19972. * Flag to check the progress status of the query
  19973. * @see http://doc.babylonjs.com/features/occlusionquery
  19974. */
  19975. get: function () {
  19976. return this._isOcclusionQueryInProgress;
  19977. },
  19978. enumerable: true,
  19979. configurable: true
  19980. });
  19981. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19982. /**
  19983. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19984. */
  19985. get: function () {
  19986. return this._visibility;
  19987. },
  19988. /**
  19989. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19990. */
  19991. set: function (value) {
  19992. if (this._visibility === value) {
  19993. return;
  19994. }
  19995. this._visibility = value;
  19996. this._markSubMeshesAsMiscDirty();
  19997. },
  19998. enumerable: true,
  19999. configurable: true
  20000. });
  20001. Object.defineProperty(AbstractMesh.prototype, "material", {
  20002. /** Gets or sets current material */
  20003. get: function () {
  20004. return this._material;
  20005. },
  20006. set: function (value) {
  20007. if (this._material === value) {
  20008. return;
  20009. }
  20010. this._material = value;
  20011. if (this.onMaterialChangedObservable.hasObservers) {
  20012. this.onMaterialChangedObservable.notifyObservers(this);
  20013. }
  20014. if (!this.subMeshes) {
  20015. return;
  20016. }
  20017. this._unBindEffect();
  20018. },
  20019. enumerable: true,
  20020. configurable: true
  20021. });
  20022. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20023. /**
  20024. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20025. * @see http://doc.babylonjs.com/babylon101/shadows
  20026. */
  20027. get: function () {
  20028. return this._receiveShadows;
  20029. },
  20030. set: function (value) {
  20031. if (this._receiveShadows === value) {
  20032. return;
  20033. }
  20034. this._receiveShadows = value;
  20035. this._markSubMeshesAsLightDirty();
  20036. },
  20037. enumerable: true,
  20038. configurable: true
  20039. });
  20040. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20041. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20042. get: function () {
  20043. return this._hasVertexAlpha;
  20044. },
  20045. set: function (value) {
  20046. if (this._hasVertexAlpha === value) {
  20047. return;
  20048. }
  20049. this._hasVertexAlpha = value;
  20050. this._markSubMeshesAsAttributesDirty();
  20051. this._markSubMeshesAsMiscDirty();
  20052. },
  20053. enumerable: true,
  20054. configurable: true
  20055. });
  20056. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20057. /** 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) */
  20058. get: function () {
  20059. return this._useVertexColors;
  20060. },
  20061. set: function (value) {
  20062. if (this._useVertexColors === value) {
  20063. return;
  20064. }
  20065. this._useVertexColors = value;
  20066. this._markSubMeshesAsAttributesDirty();
  20067. },
  20068. enumerable: true,
  20069. configurable: true
  20070. });
  20071. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20072. /**
  20073. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20074. */
  20075. get: function () {
  20076. return this._computeBonesUsingShaders;
  20077. },
  20078. set: function (value) {
  20079. if (this._computeBonesUsingShaders === value) {
  20080. return;
  20081. }
  20082. this._computeBonesUsingShaders = value;
  20083. this._markSubMeshesAsAttributesDirty();
  20084. },
  20085. enumerable: true,
  20086. configurable: true
  20087. });
  20088. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20089. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20090. get: function () {
  20091. return this._numBoneInfluencers;
  20092. },
  20093. set: function (value) {
  20094. if (this._numBoneInfluencers === value) {
  20095. return;
  20096. }
  20097. this._numBoneInfluencers = value;
  20098. this._markSubMeshesAsAttributesDirty();
  20099. },
  20100. enumerable: true,
  20101. configurable: true
  20102. });
  20103. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20104. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20105. get: function () {
  20106. return this._applyFog;
  20107. },
  20108. set: function (value) {
  20109. if (this._applyFog === value) {
  20110. return;
  20111. }
  20112. this._applyFog = value;
  20113. this._markSubMeshesAsMiscDirty();
  20114. },
  20115. enumerable: true,
  20116. configurable: true
  20117. });
  20118. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20119. /**
  20120. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20121. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20122. */
  20123. get: function () {
  20124. return this._layerMask;
  20125. },
  20126. set: function (value) {
  20127. if (value === this._layerMask) {
  20128. return;
  20129. }
  20130. this._layerMask = value;
  20131. this._resyncLightSources();
  20132. },
  20133. enumerable: true,
  20134. configurable: true
  20135. });
  20136. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20137. /**
  20138. * Gets or sets a collision mask used to mask collisions (default is -1).
  20139. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20140. */
  20141. get: function () {
  20142. return this._collisionMask;
  20143. },
  20144. set: function (mask) {
  20145. this._collisionMask = !isNaN(mask) ? mask : -1;
  20146. },
  20147. enumerable: true,
  20148. configurable: true
  20149. });
  20150. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20151. /**
  20152. * Gets or sets the current collision group mask (-1 by default).
  20153. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20154. */
  20155. get: function () {
  20156. return this._collisionGroup;
  20157. },
  20158. set: function (mask) {
  20159. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20160. },
  20161. enumerable: true,
  20162. configurable: true
  20163. });
  20164. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20165. /** @hidden */
  20166. get: function () {
  20167. return null;
  20168. },
  20169. enumerable: true,
  20170. configurable: true
  20171. });
  20172. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20173. get: function () {
  20174. return this._skeleton;
  20175. },
  20176. /**
  20177. * Gets or sets a skeleton to apply skining transformations
  20178. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20179. */
  20180. set: function (value) {
  20181. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20182. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20183. }
  20184. if (value && value.needInitialSkinMatrix) {
  20185. value._registerMeshWithPoseMatrix(this);
  20186. }
  20187. this._skeleton = value;
  20188. if (!this._skeleton) {
  20189. this._bonesTransformMatrices = null;
  20190. }
  20191. this._markSubMeshesAsAttributesDirty();
  20192. },
  20193. enumerable: true,
  20194. configurable: true
  20195. });
  20196. /**
  20197. * Returns the string "AbstractMesh"
  20198. * @returns "AbstractMesh"
  20199. */
  20200. AbstractMesh.prototype.getClassName = function () {
  20201. return "AbstractMesh";
  20202. };
  20203. /**
  20204. * Gets a string representation of the current mesh
  20205. * @param fullDetails defines a boolean indicating if full details must be included
  20206. * @returns a string representation of the current mesh
  20207. */
  20208. AbstractMesh.prototype.toString = function (fullDetails) {
  20209. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20210. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20211. if (this._skeleton) {
  20212. ret += ", skeleton: " + this._skeleton.name;
  20213. }
  20214. if (fullDetails) {
  20215. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20216. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20217. }
  20218. return ret;
  20219. };
  20220. /** @hidden */
  20221. AbstractMesh.prototype._rebuild = function () {
  20222. this.onRebuildObservable.notifyObservers(this);
  20223. if (this._occlusionQuery) {
  20224. this._occlusionQuery = null;
  20225. }
  20226. if (!this.subMeshes) {
  20227. return;
  20228. }
  20229. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20230. var subMesh = _a[_i];
  20231. subMesh._rebuild();
  20232. }
  20233. };
  20234. /** @hidden */
  20235. AbstractMesh.prototype._resyncLightSources = function () {
  20236. this._lightSources.length = 0;
  20237. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20238. var light = _a[_i];
  20239. if (!light.isEnabled()) {
  20240. continue;
  20241. }
  20242. if (light.canAffectMesh(this)) {
  20243. this._lightSources.push(light);
  20244. }
  20245. }
  20246. this._markSubMeshesAsLightDirty();
  20247. };
  20248. /** @hidden */
  20249. AbstractMesh.prototype._resyncLighSource = function (light) {
  20250. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20251. var index = this._lightSources.indexOf(light);
  20252. if (index === -1) {
  20253. if (!isIn) {
  20254. return;
  20255. }
  20256. this._lightSources.push(light);
  20257. }
  20258. else {
  20259. if (isIn) {
  20260. return;
  20261. }
  20262. this._lightSources.splice(index, 1);
  20263. }
  20264. this._markSubMeshesAsLightDirty();
  20265. };
  20266. /** @hidden */
  20267. AbstractMesh.prototype._unBindEffect = function () {
  20268. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20269. var subMesh = _a[_i];
  20270. subMesh.setEffect(null);
  20271. }
  20272. };
  20273. /** @hidden */
  20274. AbstractMesh.prototype._removeLightSource = function (light) {
  20275. var index = this._lightSources.indexOf(light);
  20276. if (index === -1) {
  20277. return;
  20278. }
  20279. this._lightSources.splice(index, 1);
  20280. this._markSubMeshesAsLightDirty();
  20281. };
  20282. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20283. if (!this.subMeshes) {
  20284. return;
  20285. }
  20286. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20287. var subMesh = _a[_i];
  20288. if (subMesh._materialDefines) {
  20289. func(subMesh._materialDefines);
  20290. }
  20291. }
  20292. };
  20293. /** @hidden */
  20294. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20295. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20296. };
  20297. /** @hidden */
  20298. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20299. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20300. };
  20301. /** @hidden */
  20302. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20303. if (!this.subMeshes) {
  20304. return;
  20305. }
  20306. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20307. var subMesh = _a[_i];
  20308. var material = subMesh.getMaterial();
  20309. if (material) {
  20310. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20311. }
  20312. }
  20313. };
  20314. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20315. /**
  20316. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20317. */
  20318. get: function () {
  20319. return this._scaling;
  20320. },
  20321. set: function (newScaling) {
  20322. this._scaling = newScaling;
  20323. if (this.physicsImpostor) {
  20324. this.physicsImpostor.forceUpdate();
  20325. }
  20326. },
  20327. enumerable: true,
  20328. configurable: true
  20329. });
  20330. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20331. // Methods
  20332. /**
  20333. * Returns true if the mesh is blocked. Implemented by child classes
  20334. */
  20335. get: function () {
  20336. return false;
  20337. },
  20338. enumerable: true,
  20339. configurable: true
  20340. });
  20341. /**
  20342. * Returns the mesh itself by default. Implemented by child classes
  20343. * @param camera defines the camera to use to pick the right LOD level
  20344. * @returns the currentAbstractMesh
  20345. */
  20346. AbstractMesh.prototype.getLOD = function (camera) {
  20347. return this;
  20348. };
  20349. /**
  20350. * Returns 0 by default. Implemented by child classes
  20351. * @returns an integer
  20352. */
  20353. AbstractMesh.prototype.getTotalVertices = function () {
  20354. return 0;
  20355. };
  20356. /**
  20357. * Returns null by default. Implemented by child classes
  20358. * @returns null
  20359. */
  20360. AbstractMesh.prototype.getIndices = function () {
  20361. return null;
  20362. };
  20363. /**
  20364. * Returns the array of the requested vertex data kind. Implemented by child classes
  20365. * @param kind defines the vertex data kind to use
  20366. * @returns null
  20367. */
  20368. AbstractMesh.prototype.getVerticesData = function (kind) {
  20369. return null;
  20370. };
  20371. /**
  20372. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20373. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20374. * Note that a new underlying VertexBuffer object is created each call.
  20375. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20376. * @param kind defines vertex data kind:
  20377. * * BABYLON.VertexBuffer.PositionKind
  20378. * * BABYLON.VertexBuffer.UVKind
  20379. * * BABYLON.VertexBuffer.UV2Kind
  20380. * * BABYLON.VertexBuffer.UV3Kind
  20381. * * BABYLON.VertexBuffer.UV4Kind
  20382. * * BABYLON.VertexBuffer.UV5Kind
  20383. * * BABYLON.VertexBuffer.UV6Kind
  20384. * * BABYLON.VertexBuffer.ColorKind
  20385. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20386. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20387. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20388. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20389. * @param data defines the data source
  20390. * @param updatable defines if the data must be flagged as updatable (or static)
  20391. * @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
  20392. * @returns the current mesh
  20393. */
  20394. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20395. return this;
  20396. };
  20397. /**
  20398. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20399. * If the mesh has no geometry, it is simply returned as it is.
  20400. * @param kind defines vertex data kind:
  20401. * * BABYLON.VertexBuffer.PositionKind
  20402. * * BABYLON.VertexBuffer.UVKind
  20403. * * BABYLON.VertexBuffer.UV2Kind
  20404. * * BABYLON.VertexBuffer.UV3Kind
  20405. * * BABYLON.VertexBuffer.UV4Kind
  20406. * * BABYLON.VertexBuffer.UV5Kind
  20407. * * BABYLON.VertexBuffer.UV6Kind
  20408. * * BABYLON.VertexBuffer.ColorKind
  20409. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20410. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20411. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20412. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20413. * @param data defines the data source
  20414. * @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
  20415. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20416. * @returns the current mesh
  20417. */
  20418. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20419. return this;
  20420. };
  20421. /**
  20422. * Sets the mesh indices,
  20423. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20424. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20425. * @param totalVertices Defines the total number of vertices
  20426. * @returns the current mesh
  20427. */
  20428. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20429. return this;
  20430. };
  20431. /**
  20432. * Gets a boolean indicating if specific vertex data is present
  20433. * @param kind defines the vertex data kind to use
  20434. * @returns true is data kind is present
  20435. */
  20436. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20437. return false;
  20438. };
  20439. /**
  20440. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20441. * @returns a BoundingInfo
  20442. */
  20443. AbstractMesh.prototype.getBoundingInfo = function () {
  20444. if (this._masterMesh) {
  20445. return this._masterMesh.getBoundingInfo();
  20446. }
  20447. if (!this._boundingInfo) {
  20448. // this._boundingInfo is being created here
  20449. this._updateBoundingInfo();
  20450. }
  20451. // cannot be null.
  20452. return this._boundingInfo;
  20453. };
  20454. /**
  20455. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20456. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20457. * @returns the current mesh
  20458. */
  20459. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20460. if (includeDescendants === void 0) { includeDescendants = true; }
  20461. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20462. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20463. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20464. if (maxDimension === 0) {
  20465. return this;
  20466. }
  20467. var scale = 1 / maxDimension;
  20468. this.scaling.scaleInPlace(scale);
  20469. return this;
  20470. };
  20471. /**
  20472. * Overwrite the current bounding info
  20473. * @param boundingInfo defines the new bounding info
  20474. * @returns the current mesh
  20475. */
  20476. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20477. this._boundingInfo = boundingInfo;
  20478. return this;
  20479. };
  20480. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20481. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20482. get: function () {
  20483. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20484. },
  20485. enumerable: true,
  20486. configurable: true
  20487. });
  20488. /** @hidden */
  20489. AbstractMesh.prototype._preActivate = function () {
  20490. };
  20491. /** @hidden */
  20492. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20493. };
  20494. /** @hidden */
  20495. AbstractMesh.prototype._activate = function (renderId) {
  20496. this._renderId = renderId;
  20497. };
  20498. /**
  20499. * Gets the current world matrix
  20500. * @returns a Matrix
  20501. */
  20502. AbstractMesh.prototype.getWorldMatrix = function () {
  20503. if (this._masterMesh) {
  20504. return this._masterMesh.getWorldMatrix();
  20505. }
  20506. return _super.prototype.getWorldMatrix.call(this);
  20507. };
  20508. /** @hidden */
  20509. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20510. if (this._masterMesh) {
  20511. return this._masterMesh._getWorldMatrixDeterminant();
  20512. }
  20513. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20514. };
  20515. // ================================== Point of View Movement =================================
  20516. /**
  20517. * Perform relative position change from the point of view of behind the front of the mesh.
  20518. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20519. * Supports definition of mesh facing forward or backward
  20520. * @param amountRight defines the distance on the right axis
  20521. * @param amountUp defines the distance on the up axis
  20522. * @param amountForward defines the distance on the forward axis
  20523. * @returns the current mesh
  20524. */
  20525. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20526. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20527. return this;
  20528. };
  20529. /**
  20530. * Calculate relative position change from the point of view of behind the front of the mesh.
  20531. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20532. * Supports definition of mesh facing forward or backward
  20533. * @param amountRight defines the distance on the right axis
  20534. * @param amountUp defines the distance on the up axis
  20535. * @param amountForward defines the distance on the forward axis
  20536. * @returns the new displacement vector
  20537. */
  20538. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20539. var rotMatrix = new BABYLON.Matrix();
  20540. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20541. rotQuaternion.toRotationMatrix(rotMatrix);
  20542. var translationDelta = BABYLON.Vector3.Zero();
  20543. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20544. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20545. return translationDelta;
  20546. };
  20547. // ================================== Point of View Rotation =================================
  20548. /**
  20549. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20550. * Supports definition of mesh facing forward or backward
  20551. * @param flipBack defines the flip
  20552. * @param twirlClockwise defines the twirl
  20553. * @param tiltRight defines the tilt
  20554. * @returns the current mesh
  20555. */
  20556. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20557. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20558. return this;
  20559. };
  20560. /**
  20561. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20562. * Supports definition of mesh facing forward or backward.
  20563. * @param flipBack defines the flip
  20564. * @param twirlClockwise defines the twirl
  20565. * @param tiltRight defines the tilt
  20566. * @returns the new rotation vector
  20567. */
  20568. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20569. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20570. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20571. };
  20572. /**
  20573. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20574. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20575. * @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
  20576. * @returns the new bounding vectors
  20577. */
  20578. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20579. if (includeDescendants === void 0) { includeDescendants = true; }
  20580. if (predicate === void 0) { predicate = null; }
  20581. // Ensures that all world matrix will be recomputed.
  20582. this.getScene().incrementRenderId();
  20583. this.computeWorldMatrix(true);
  20584. var min;
  20585. var max;
  20586. var boundingInfo = this.getBoundingInfo();
  20587. if (!this.subMeshes) {
  20588. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20589. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20590. }
  20591. else {
  20592. min = boundingInfo.boundingBox.minimumWorld;
  20593. max = boundingInfo.boundingBox.maximumWorld;
  20594. }
  20595. if (includeDescendants) {
  20596. var descendants = this.getDescendants(false);
  20597. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20598. var descendant = descendants_1[_i];
  20599. var childMesh = descendant;
  20600. childMesh.computeWorldMatrix(true);
  20601. // Filters meshes based on custom predicate function.
  20602. if (predicate && !predicate(childMesh)) {
  20603. continue;
  20604. }
  20605. //make sure we have the needed params to get mix and max
  20606. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20607. continue;
  20608. }
  20609. var childBoundingInfo = childMesh.getBoundingInfo();
  20610. var boundingBox = childBoundingInfo.boundingBox;
  20611. var minBox = boundingBox.minimumWorld;
  20612. var maxBox = boundingBox.maximumWorld;
  20613. BABYLON.Tools.CheckExtends(minBox, min, max);
  20614. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20615. }
  20616. }
  20617. return {
  20618. min: min,
  20619. max: max
  20620. };
  20621. };
  20622. /** @hidden */
  20623. AbstractMesh.prototype._updateBoundingInfo = function () {
  20624. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20625. this._boundingInfo.update(this.worldMatrixFromCache);
  20626. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20627. return this;
  20628. };
  20629. /** @hidden */
  20630. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20631. if (!this.subMeshes) {
  20632. return this;
  20633. }
  20634. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20635. var subMesh = this.subMeshes[subIndex];
  20636. if (!subMesh.IsGlobal) {
  20637. subMesh.updateBoundingInfo(matrix);
  20638. }
  20639. }
  20640. return this;
  20641. };
  20642. /** @hidden */
  20643. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20644. // Bounding info
  20645. this._updateBoundingInfo();
  20646. };
  20647. /**
  20648. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20649. * A mesh is in the frustum if its bounding box intersects the frustum
  20650. * @param frustumPlanes defines the frustum to test
  20651. * @returns true if the mesh is in the frustum planes
  20652. */
  20653. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20654. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20655. };
  20656. /**
  20657. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20658. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20659. * @param frustumPlanes defines the frustum to test
  20660. * @returns true if the mesh is completely in the frustum planes
  20661. */
  20662. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20663. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20664. };
  20665. /**
  20666. * True if the mesh intersects another mesh or a SolidParticle object
  20667. * @param mesh defines a target mesh or SolidParticle to test
  20668. * @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)
  20669. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20670. * @returns true if there is an intersection
  20671. */
  20672. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20673. if (precise === void 0) { precise = false; }
  20674. if (!this._boundingInfo || !mesh._boundingInfo) {
  20675. return false;
  20676. }
  20677. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20678. return true;
  20679. }
  20680. if (includeDescendants) {
  20681. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20682. var child = _a[_i];
  20683. if (child.intersectsMesh(mesh, precise, true)) {
  20684. return true;
  20685. }
  20686. }
  20687. }
  20688. return false;
  20689. };
  20690. /**
  20691. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20692. * @param point defines the point to test
  20693. * @returns true if there is an intersection
  20694. */
  20695. AbstractMesh.prototype.intersectsPoint = function (point) {
  20696. if (!this._boundingInfo) {
  20697. return false;
  20698. }
  20699. return this._boundingInfo.intersectsPoint(point);
  20700. };
  20701. /**
  20702. * Gets the current physics impostor
  20703. * @see http://doc.babylonjs.com/features/physics_engine
  20704. * @returns a physics impostor or null
  20705. */
  20706. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20707. return this.physicsImpostor;
  20708. };
  20709. /**
  20710. * Gets the position of the current mesh in camera space
  20711. * @param camera defines the camera to use
  20712. * @returns a position
  20713. */
  20714. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20715. if (camera === void 0) { camera = null; }
  20716. if (!camera) {
  20717. camera = this.getScene().activeCamera;
  20718. }
  20719. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20720. };
  20721. /**
  20722. * Returns the distance from the mesh to the active camera
  20723. * @param camera defines the camera to use
  20724. * @returns the distance
  20725. */
  20726. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20727. if (camera === void 0) { camera = null; }
  20728. if (!camera) {
  20729. camera = this.getScene().activeCamera;
  20730. }
  20731. return this.absolutePosition.subtract(camera.position).length();
  20732. };
  20733. /**
  20734. * Apply a physic impulse to the mesh
  20735. * @param force defines the force to apply
  20736. * @param contactPoint defines where to apply the force
  20737. * @returns the current mesh
  20738. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20739. */
  20740. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20741. if (!this.physicsImpostor) {
  20742. return this;
  20743. }
  20744. this.physicsImpostor.applyImpulse(force, contactPoint);
  20745. return this;
  20746. };
  20747. /**
  20748. * Creates a physic joint between two meshes
  20749. * @param otherMesh defines the other mesh to use
  20750. * @param pivot1 defines the pivot to use on this mesh
  20751. * @param pivot2 defines the pivot to use on the other mesh
  20752. * @param options defines additional options (can be plugin dependent)
  20753. * @returns the current mesh
  20754. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20755. */
  20756. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20757. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20758. return this;
  20759. }
  20760. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20761. mainPivot: pivot1,
  20762. connectedPivot: pivot2,
  20763. nativeParams: options
  20764. });
  20765. return this;
  20766. };
  20767. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20768. // Collisions
  20769. /**
  20770. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20771. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20772. */
  20773. get: function () {
  20774. return this._checkCollisions;
  20775. },
  20776. set: function (collisionEnabled) {
  20777. this._checkCollisions = collisionEnabled;
  20778. if (this.getScene().workerCollisions) {
  20779. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20780. }
  20781. },
  20782. enumerable: true,
  20783. configurable: true
  20784. });
  20785. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20786. /**
  20787. * Gets Collider object used to compute collisions (not physics)
  20788. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20789. */
  20790. get: function () {
  20791. return this._collider;
  20792. },
  20793. enumerable: true,
  20794. configurable: true
  20795. });
  20796. /**
  20797. * Move the mesh using collision engine
  20798. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20799. * @param displacement defines the requested displacement vector
  20800. * @returns the current mesh
  20801. */
  20802. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20803. var globalPosition = this.getAbsolutePosition();
  20804. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20805. if (!this._collider) {
  20806. this._collider = new BABYLON.Collider();
  20807. }
  20808. this._collider._radius = this.ellipsoid;
  20809. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20810. return this;
  20811. };
  20812. // Collisions
  20813. /** @hidden */
  20814. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20815. this._generatePointsArray();
  20816. if (!this._positions) {
  20817. return this;
  20818. }
  20819. // Transformation
  20820. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20821. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20822. subMesh._lastColliderWorldVertices = [];
  20823. subMesh._trianglePlanes = [];
  20824. var start = subMesh.verticesStart;
  20825. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20826. for (var i = start; i < end; i++) {
  20827. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20828. }
  20829. }
  20830. // Collide
  20831. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20832. if (collider.collisionFound) {
  20833. collider.collidedMesh = this;
  20834. }
  20835. return this;
  20836. };
  20837. /** @hidden */
  20838. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20839. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20840. var len = subMeshes.length;
  20841. for (var index = 0; index < len; index++) {
  20842. var subMesh = subMeshes.data[index];
  20843. // Bounding test
  20844. if (len > 1 && !subMesh._checkCollision(collider))
  20845. continue;
  20846. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20847. }
  20848. return this;
  20849. };
  20850. /** @hidden */
  20851. AbstractMesh.prototype._checkCollision = function (collider) {
  20852. // Bounding box test
  20853. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20854. return this;
  20855. // Transformation matrix
  20856. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20857. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20858. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20859. return this;
  20860. };
  20861. // Picking
  20862. /** @hidden */
  20863. AbstractMesh.prototype._generatePointsArray = function () {
  20864. return false;
  20865. };
  20866. /**
  20867. * Checks if the passed Ray intersects with the mesh
  20868. * @param ray defines the ray to use
  20869. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20870. * @returns the picking info
  20871. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20872. */
  20873. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20874. var pickingInfo = new BABYLON.PickingInfo();
  20875. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20876. return pickingInfo;
  20877. }
  20878. if (!this._generatePointsArray()) {
  20879. return pickingInfo;
  20880. }
  20881. var intersectInfo = null;
  20882. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  20883. var len = subMeshes.length;
  20884. for (var index = 0; index < len; index++) {
  20885. var subMesh = subMeshes.data[index];
  20886. // Bounding test
  20887. if (len > 1 && !subMesh.canIntersects(ray))
  20888. continue;
  20889. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20890. if (currentIntersectInfo) {
  20891. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20892. intersectInfo = currentIntersectInfo;
  20893. intersectInfo.subMeshId = index;
  20894. if (fastCheck) {
  20895. break;
  20896. }
  20897. }
  20898. }
  20899. }
  20900. if (intersectInfo) {
  20901. // Get picked point
  20902. var world = this.getWorldMatrix();
  20903. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20904. var direction = ray.direction.clone();
  20905. direction = direction.scale(intersectInfo.distance);
  20906. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20907. var pickedPoint = worldOrigin.add(worldDirection);
  20908. // Return result
  20909. pickingInfo.hit = true;
  20910. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20911. pickingInfo.pickedPoint = pickedPoint;
  20912. pickingInfo.pickedMesh = this;
  20913. pickingInfo.bu = intersectInfo.bu || 0;
  20914. pickingInfo.bv = intersectInfo.bv || 0;
  20915. pickingInfo.faceId = intersectInfo.faceId;
  20916. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20917. return pickingInfo;
  20918. }
  20919. return pickingInfo;
  20920. };
  20921. /**
  20922. * Clones the current mesh
  20923. * @param name defines the mesh name
  20924. * @param newParent defines the new mesh parent
  20925. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20926. * @returns the new mesh
  20927. */
  20928. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20929. return null;
  20930. };
  20931. /**
  20932. * Disposes all the submeshes of the current meshnp
  20933. * @returns the current mesh
  20934. */
  20935. AbstractMesh.prototype.releaseSubMeshes = function () {
  20936. if (this.subMeshes) {
  20937. while (this.subMeshes.length) {
  20938. this.subMeshes[0].dispose();
  20939. }
  20940. }
  20941. else {
  20942. this.subMeshes = new Array();
  20943. }
  20944. return this;
  20945. };
  20946. /**
  20947. * Releases resources associated with this abstract mesh.
  20948. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20949. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20950. */
  20951. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20952. var _this = this;
  20953. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20954. var index;
  20955. // Smart Array Retainers.
  20956. this.getScene().freeActiveMeshes();
  20957. this.getScene().freeRenderingGroups();
  20958. // Action manager
  20959. if (this.actionManager !== undefined && this.actionManager !== null) {
  20960. this.actionManager.dispose();
  20961. this.actionManager = null;
  20962. }
  20963. // Skeleton
  20964. this._skeleton = null;
  20965. // Physics
  20966. if (this.physicsImpostor) {
  20967. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20968. }
  20969. // Intersections in progress
  20970. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20971. var other = this._intersectionsInProgress[index];
  20972. var pos = other._intersectionsInProgress.indexOf(this);
  20973. other._intersectionsInProgress.splice(pos, 1);
  20974. }
  20975. this._intersectionsInProgress = [];
  20976. // Lights
  20977. var lights = this.getScene().lights;
  20978. lights.forEach(function (light) {
  20979. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20980. if (meshIndex !== -1) {
  20981. light.includedOnlyMeshes.splice(meshIndex, 1);
  20982. }
  20983. meshIndex = light.excludedMeshes.indexOf(_this);
  20984. if (meshIndex !== -1) {
  20985. light.excludedMeshes.splice(meshIndex, 1);
  20986. }
  20987. // Shadow generators
  20988. var generator = light.getShadowGenerator();
  20989. if (generator) {
  20990. var shadowMap = generator.getShadowMap();
  20991. if (shadowMap && shadowMap.renderList) {
  20992. meshIndex = shadowMap.renderList.indexOf(_this);
  20993. if (meshIndex !== -1) {
  20994. shadowMap.renderList.splice(meshIndex, 1);
  20995. }
  20996. }
  20997. }
  20998. });
  20999. // SubMeshes
  21000. if (this.getClassName() !== "InstancedMesh") {
  21001. this.releaseSubMeshes();
  21002. }
  21003. // Query
  21004. var engine = this.getScene().getEngine();
  21005. if (this._occlusionQuery) {
  21006. this._isOcclusionQueryInProgress = false;
  21007. engine.deleteQuery(this._occlusionQuery);
  21008. this._occlusionQuery = null;
  21009. }
  21010. // Engine
  21011. engine.wipeCaches();
  21012. // Remove from scene
  21013. this.getScene().removeMesh(this);
  21014. if (disposeMaterialAndTextures) {
  21015. if (this.material) {
  21016. this.material.dispose(false, true);
  21017. }
  21018. }
  21019. if (!doNotRecurse) {
  21020. // Particles
  21021. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21022. if (this.getScene().particleSystems[index].emitter === this) {
  21023. this.getScene().particleSystems[index].dispose();
  21024. index--;
  21025. }
  21026. }
  21027. }
  21028. // facet data
  21029. if (this._facetDataEnabled) {
  21030. this.disableFacetData();
  21031. }
  21032. this.onAfterWorldMatrixUpdateObservable.clear();
  21033. this.onCollideObservable.clear();
  21034. this.onCollisionPositionChangeObservable.clear();
  21035. this.onRebuildObservable.clear();
  21036. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21037. };
  21038. /**
  21039. * Adds the passed mesh as a child to the current mesh
  21040. * @param mesh defines the child mesh
  21041. * @returns the current mesh
  21042. */
  21043. AbstractMesh.prototype.addChild = function (mesh) {
  21044. mesh.setParent(this);
  21045. return this;
  21046. };
  21047. /**
  21048. * Removes the passed mesh from the current mesh children list
  21049. * @param mesh defines the child mesh
  21050. * @returns the current mesh
  21051. */
  21052. AbstractMesh.prototype.removeChild = function (mesh) {
  21053. mesh.setParent(null);
  21054. return this;
  21055. };
  21056. // Facet data
  21057. /** @hidden */
  21058. AbstractMesh.prototype._initFacetData = function () {
  21059. if (!this._facetNormals) {
  21060. this._facetNormals = new Array();
  21061. }
  21062. if (!this._facetPositions) {
  21063. this._facetPositions = new Array();
  21064. }
  21065. if (!this._facetPartitioning) {
  21066. this._facetPartitioning = new Array();
  21067. }
  21068. this._facetNb = (this.getIndices().length / 3) | 0;
  21069. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21070. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21071. for (var f = 0; f < this._facetNb; f++) {
  21072. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21073. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21074. }
  21075. this._facetDataEnabled = true;
  21076. return this;
  21077. };
  21078. /**
  21079. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21080. * This method can be called within the render loop.
  21081. * 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
  21082. * @returns the current mesh
  21083. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21084. */
  21085. AbstractMesh.prototype.updateFacetData = function () {
  21086. if (!this._facetDataEnabled) {
  21087. this._initFacetData();
  21088. }
  21089. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21090. var indices = this.getIndices();
  21091. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21092. var bInfo = this.getBoundingInfo();
  21093. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21094. // init arrays, matrix and sort function on first call
  21095. this._facetDepthSortEnabled = true;
  21096. if (indices instanceof Uint16Array) {
  21097. this._depthSortedIndices = new Uint16Array(indices);
  21098. }
  21099. else if (indices instanceof Uint32Array) {
  21100. this._depthSortedIndices = new Uint32Array(indices);
  21101. }
  21102. else {
  21103. var needs32bits = false;
  21104. for (var i = 0; i < indices.length; i++) {
  21105. if (indices[i] > 65535) {
  21106. needs32bits = true;
  21107. break;
  21108. }
  21109. }
  21110. if (needs32bits) {
  21111. this._depthSortedIndices = new Uint32Array(indices);
  21112. }
  21113. else {
  21114. this._depthSortedIndices = new Uint16Array(indices);
  21115. }
  21116. }
  21117. this._facetDepthSortFunction = function (f1, f2) {
  21118. return (f2.sqDistance - f1.sqDistance);
  21119. };
  21120. if (!this._facetDepthSortFrom) {
  21121. var camera = this.getScene().activeCamera;
  21122. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21123. }
  21124. this._depthSortedFacets = [];
  21125. for (var f = 0; f < this._facetNb; f++) {
  21126. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21127. this._depthSortedFacets.push(depthSortedFacet);
  21128. }
  21129. this._invertedMatrix = BABYLON.Matrix.Identity();
  21130. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21131. }
  21132. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21133. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21134. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21135. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21136. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21137. this._subDiv.max = this._partitioningSubdivisions;
  21138. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21139. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21140. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21141. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21142. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21143. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21144. // set the parameters for ComputeNormals()
  21145. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21146. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21147. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21148. this._facetParameters.bInfo = bInfo;
  21149. this._facetParameters.bbSize = this._bbSize;
  21150. this._facetParameters.subDiv = this._subDiv;
  21151. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21152. this._facetParameters.depthSort = this._facetDepthSort;
  21153. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21154. this.computeWorldMatrix(true);
  21155. this._worldMatrix.invertToRef(this._invertedMatrix);
  21156. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21157. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21158. }
  21159. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21160. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21161. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21162. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21163. var l = (this._depthSortedIndices.length / 3) | 0;
  21164. for (var f = 0; f < l; f++) {
  21165. var sind = this._depthSortedFacets[f].ind;
  21166. this._depthSortedIndices[f * 3] = indices[sind];
  21167. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21168. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21169. }
  21170. this.updateIndices(this._depthSortedIndices);
  21171. }
  21172. return this;
  21173. };
  21174. /**
  21175. * Returns the facetLocalNormals array.
  21176. * The normals are expressed in the mesh local spac
  21177. * @returns an array of Vector3
  21178. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21179. */
  21180. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21181. if (!this._facetNormals) {
  21182. this.updateFacetData();
  21183. }
  21184. return this._facetNormals;
  21185. };
  21186. /**
  21187. * Returns the facetLocalPositions array.
  21188. * The facet positions are expressed in the mesh local space
  21189. * @returns an array of Vector3
  21190. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21191. */
  21192. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21193. if (!this._facetPositions) {
  21194. this.updateFacetData();
  21195. }
  21196. return this._facetPositions;
  21197. };
  21198. /**
  21199. * Returns the facetLocalPartioning array
  21200. * @returns an array of array of numbers
  21201. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21202. */
  21203. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21204. if (!this._facetPartitioning) {
  21205. this.updateFacetData();
  21206. }
  21207. return this._facetPartitioning;
  21208. };
  21209. /**
  21210. * Returns the i-th facet position in the world system.
  21211. * This method allocates a new Vector3 per call
  21212. * @param i defines the facet index
  21213. * @returns a new Vector3
  21214. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21215. */
  21216. AbstractMesh.prototype.getFacetPosition = function (i) {
  21217. var pos = BABYLON.Vector3.Zero();
  21218. this.getFacetPositionToRef(i, pos);
  21219. return pos;
  21220. };
  21221. /**
  21222. * Sets the reference Vector3 with the i-th facet position in the world system
  21223. * @param i defines the facet index
  21224. * @param ref defines the target vector
  21225. * @returns the current mesh
  21226. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21227. */
  21228. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21229. var localPos = (this.getFacetLocalPositions())[i];
  21230. var world = this.getWorldMatrix();
  21231. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21232. return this;
  21233. };
  21234. /**
  21235. * Returns the i-th facet normal in the world system.
  21236. * This method allocates a new Vector3 per call
  21237. * @param i defines the facet index
  21238. * @returns a new Vector3
  21239. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21240. */
  21241. AbstractMesh.prototype.getFacetNormal = function (i) {
  21242. var norm = BABYLON.Vector3.Zero();
  21243. this.getFacetNormalToRef(i, norm);
  21244. return norm;
  21245. };
  21246. /**
  21247. * Sets the reference Vector3 with the i-th facet normal in the world system
  21248. * @param i defines the facet index
  21249. * @param ref defines the target vector
  21250. * @returns the current mesh
  21251. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21252. */
  21253. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21254. var localNorm = (this.getFacetLocalNormals())[i];
  21255. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21256. return this;
  21257. };
  21258. /**
  21259. * 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)
  21260. * @param x defines x coordinate
  21261. * @param y defines y coordinate
  21262. * @param z defines z coordinate
  21263. * @returns the array of facet indexes
  21264. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21265. */
  21266. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21267. var bInfo = this.getBoundingInfo();
  21268. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21269. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21270. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21271. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21272. return null;
  21273. }
  21274. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21275. };
  21276. /**
  21277. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21278. * @param projected sets as the (x,y,z) world projection on the facet
  21279. * @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
  21280. * @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
  21281. * @param x defines x coordinate
  21282. * @param y defines y coordinate
  21283. * @param z defines z coordinate
  21284. * @returns the face index if found (or null instead)
  21285. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21286. */
  21287. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21288. if (checkFace === void 0) { checkFace = false; }
  21289. if (facing === void 0) { facing = true; }
  21290. var world = this.getWorldMatrix();
  21291. var invMat = BABYLON.Tmp.Matrix[5];
  21292. world.invertToRef(invMat);
  21293. var invVect = BABYLON.Tmp.Vector3[8];
  21294. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21295. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21296. if (projected) {
  21297. // tranform the local computed projected vector to world coordinates
  21298. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21299. }
  21300. return closest;
  21301. };
  21302. /**
  21303. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21304. * @param projected sets as the (x,y,z) local projection on the facet
  21305. * @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
  21306. * @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
  21307. * @param x defines x coordinate
  21308. * @param y defines y coordinate
  21309. * @param z defines z coordinate
  21310. * @returns the face index if found (or null instead)
  21311. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21312. */
  21313. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21314. if (checkFace === void 0) { checkFace = false; }
  21315. if (facing === void 0) { facing = true; }
  21316. var closest = null;
  21317. var tmpx = 0.0;
  21318. var tmpy = 0.0;
  21319. var tmpz = 0.0;
  21320. var d = 0.0; // tmp dot facet normal * facet position
  21321. var t0 = 0.0;
  21322. var projx = 0.0;
  21323. var projy = 0.0;
  21324. var projz = 0.0;
  21325. // Get all the facets in the same partitioning block than (x, y, z)
  21326. var facetPositions = this.getFacetLocalPositions();
  21327. var facetNormals = this.getFacetLocalNormals();
  21328. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21329. if (!facetsInBlock) {
  21330. return null;
  21331. }
  21332. // Get the closest facet to (x, y, z)
  21333. var shortest = Number.MAX_VALUE; // init distance vars
  21334. var tmpDistance = shortest;
  21335. var fib; // current facet in the block
  21336. var norm; // current facet normal
  21337. var p0; // current facet barycenter position
  21338. // loop on all the facets in the current partitioning block
  21339. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21340. fib = facetsInBlock[idx];
  21341. norm = facetNormals[fib];
  21342. p0 = facetPositions[fib];
  21343. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21344. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21345. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21346. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21347. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21348. projx = x + norm.x * t0;
  21349. projy = y + norm.y * t0;
  21350. projz = z + norm.z * t0;
  21351. tmpx = projx - x;
  21352. tmpy = projy - y;
  21353. tmpz = projz - z;
  21354. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21355. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21356. shortest = tmpDistance;
  21357. closest = fib;
  21358. if (projected) {
  21359. projected.x = projx;
  21360. projected.y = projy;
  21361. projected.z = projz;
  21362. }
  21363. }
  21364. }
  21365. }
  21366. return closest;
  21367. };
  21368. /**
  21369. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21370. * @returns the parameters
  21371. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21372. */
  21373. AbstractMesh.prototype.getFacetDataParameters = function () {
  21374. return this._facetParameters;
  21375. };
  21376. /**
  21377. * Disables the feature FacetData and frees the related memory
  21378. * @returns the current mesh
  21379. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21380. */
  21381. AbstractMesh.prototype.disableFacetData = function () {
  21382. if (this._facetDataEnabled) {
  21383. this._facetDataEnabled = false;
  21384. this._facetPositions = new Array();
  21385. this._facetNormals = new Array();
  21386. this._facetPartitioning = new Array();
  21387. this._facetParameters = null;
  21388. this._depthSortedIndices = new Uint32Array(0);
  21389. }
  21390. return this;
  21391. };
  21392. /**
  21393. * Updates the AbstractMesh indices array
  21394. * @param indices defines the data source
  21395. * @returns the current mesh
  21396. */
  21397. AbstractMesh.prototype.updateIndices = function (indices) {
  21398. return this;
  21399. };
  21400. /**
  21401. * Creates new normals data for the mesh
  21402. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21403. * @returns the current mesh
  21404. */
  21405. AbstractMesh.prototype.createNormals = function (updatable) {
  21406. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21407. var indices = this.getIndices();
  21408. var normals;
  21409. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21410. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21411. }
  21412. else {
  21413. normals = [];
  21414. }
  21415. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21416. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21417. return this;
  21418. };
  21419. /**
  21420. * Align the mesh with a normal
  21421. * @param normal defines the normal to use
  21422. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21423. * @returns the current mesh
  21424. */
  21425. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21426. if (!upDirection) {
  21427. upDirection = BABYLON.Axis.Y;
  21428. }
  21429. var axisX = BABYLON.Tmp.Vector3[0];
  21430. var axisZ = BABYLON.Tmp.Vector3[1];
  21431. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21432. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21433. if (this.rotationQuaternion) {
  21434. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21435. }
  21436. else {
  21437. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21438. }
  21439. return this;
  21440. };
  21441. /** @hidden */
  21442. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21443. this._isOccluded = false;
  21444. };
  21445. /** No occlusion */
  21446. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21447. /** Occlusion set to optimisitic */
  21448. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21449. /** Occlusion set to strict */
  21450. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21451. /** Use an accurante occlusion algorithm */
  21452. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21453. /** Use a conservative occlusion algorithm */
  21454. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21455. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21456. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21457. /** Culling strategy with bounding sphere only and then frustum culling */
  21458. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21459. return AbstractMesh;
  21460. }(BABYLON.TransformNode));
  21461. BABYLON.AbstractMesh = AbstractMesh;
  21462. })(BABYLON || (BABYLON = {}));
  21463. //# sourceMappingURL=babylon.abstractMesh.js.map
  21464. var BABYLON;
  21465. (function (BABYLON) {
  21466. /**
  21467. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21468. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21469. * 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.
  21470. */
  21471. var Light = /** @class */ (function (_super) {
  21472. __extends(Light, _super);
  21473. /**
  21474. * Creates a Light object in the scene.
  21475. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21476. * @param name The firendly name of the light
  21477. * @param scene The scene the light belongs too
  21478. */
  21479. function Light(name, scene) {
  21480. var _this = _super.call(this, name, scene) || this;
  21481. /**
  21482. * Diffuse gives the basic color to an object.
  21483. */
  21484. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21485. /**
  21486. * Specular produces a highlight color on an object.
  21487. * Note: This is note affecting PBR materials.
  21488. */
  21489. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21490. /**
  21491. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21492. * falling off base on range or angle.
  21493. * This can be set to any values in Light.FALLOFF_x.
  21494. *
  21495. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21496. * other types of materials.
  21497. */
  21498. _this.falloffType = Light.FALLOFF_DEFAULT;
  21499. /**
  21500. * Strength of the light.
  21501. * Note: By default it is define in the framework own unit.
  21502. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21503. */
  21504. _this.intensity = 1.0;
  21505. _this._range = Number.MAX_VALUE;
  21506. _this._inverseSquaredRange = 0;
  21507. /**
  21508. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21509. * of light.
  21510. */
  21511. _this._photometricScale = 1.0;
  21512. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21513. _this._radius = 0.00001;
  21514. /**
  21515. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21516. * exceeding the number allowed of the materials.
  21517. */
  21518. _this.renderPriority = 0;
  21519. _this._shadowEnabled = true;
  21520. _this._excludeWithLayerMask = 0;
  21521. _this._includeOnlyWithLayerMask = 0;
  21522. _this._lightmapMode = 0;
  21523. /**
  21524. * @hidden Internal use only.
  21525. */
  21526. _this._excludedMeshesIds = new Array();
  21527. /**
  21528. * @hidden Internal use only.
  21529. */
  21530. _this._includedOnlyMeshesIds = new Array();
  21531. _this.getScene().addLight(_this);
  21532. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21533. _this._buildUniformLayout();
  21534. _this.includedOnlyMeshes = new Array();
  21535. _this.excludedMeshes = new Array();
  21536. _this._resyncMeshes();
  21537. return _this;
  21538. }
  21539. Object.defineProperty(Light.prototype, "range", {
  21540. /**
  21541. * Defines how far from the source the light is impacting in scene units.
  21542. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21543. */
  21544. get: function () {
  21545. return this._range;
  21546. },
  21547. /**
  21548. * Defines how far from the source the light is impacting in scene units.
  21549. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21550. */
  21551. set: function (value) {
  21552. this._range = value;
  21553. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21554. },
  21555. enumerable: true,
  21556. configurable: true
  21557. });
  21558. Object.defineProperty(Light.prototype, "intensityMode", {
  21559. /**
  21560. * Gets the photometric scale used to interpret the intensity.
  21561. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21562. */
  21563. get: function () {
  21564. return this._intensityMode;
  21565. },
  21566. /**
  21567. * Sets the photometric scale used to interpret the intensity.
  21568. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21569. */
  21570. set: function (value) {
  21571. this._intensityMode = value;
  21572. this._computePhotometricScale();
  21573. },
  21574. enumerable: true,
  21575. configurable: true
  21576. });
  21577. ;
  21578. ;
  21579. Object.defineProperty(Light.prototype, "radius", {
  21580. /**
  21581. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21582. */
  21583. get: function () {
  21584. return this._radius;
  21585. },
  21586. /**
  21587. * sets the light radius used by PBR Materials to simulate soft area lights.
  21588. */
  21589. set: function (value) {
  21590. this._radius = value;
  21591. this._computePhotometricScale();
  21592. },
  21593. enumerable: true,
  21594. configurable: true
  21595. });
  21596. ;
  21597. ;
  21598. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21599. /**
  21600. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21601. * the current shadow generator.
  21602. */
  21603. get: function () {
  21604. return this._shadowEnabled;
  21605. },
  21606. /**
  21607. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21608. * the current shadow generator.
  21609. */
  21610. set: function (value) {
  21611. if (this._shadowEnabled === value) {
  21612. return;
  21613. }
  21614. this._shadowEnabled = value;
  21615. this._markMeshesAsLightDirty();
  21616. },
  21617. enumerable: true,
  21618. configurable: true
  21619. });
  21620. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21621. /**
  21622. * Gets the only meshes impacted by this light.
  21623. */
  21624. get: function () {
  21625. return this._includedOnlyMeshes;
  21626. },
  21627. /**
  21628. * Sets the only meshes impacted by this light.
  21629. */
  21630. set: function (value) {
  21631. this._includedOnlyMeshes = value;
  21632. this._hookArrayForIncludedOnly(value);
  21633. },
  21634. enumerable: true,
  21635. configurable: true
  21636. });
  21637. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21638. /**
  21639. * Gets the meshes not impacted by this light.
  21640. */
  21641. get: function () {
  21642. return this._excludedMeshes;
  21643. },
  21644. /**
  21645. * Sets the meshes not impacted by this light.
  21646. */
  21647. set: function (value) {
  21648. this._excludedMeshes = value;
  21649. this._hookArrayForExcluded(value);
  21650. },
  21651. enumerable: true,
  21652. configurable: true
  21653. });
  21654. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21655. /**
  21656. * Gets the layer id use to find what meshes are not impacted by the light.
  21657. * Inactive if 0
  21658. */
  21659. get: function () {
  21660. return this._excludeWithLayerMask;
  21661. },
  21662. /**
  21663. * Sets the layer id use to find what meshes are not impacted by the light.
  21664. * Inactive if 0
  21665. */
  21666. set: function (value) {
  21667. this._excludeWithLayerMask = value;
  21668. this._resyncMeshes();
  21669. },
  21670. enumerable: true,
  21671. configurable: true
  21672. });
  21673. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21674. /**
  21675. * Gets the layer id use to find what meshes are impacted by the light.
  21676. * Inactive if 0
  21677. */
  21678. get: function () {
  21679. return this._includeOnlyWithLayerMask;
  21680. },
  21681. /**
  21682. * Sets the layer id use to find what meshes are impacted by the light.
  21683. * Inactive if 0
  21684. */
  21685. set: function (value) {
  21686. this._includeOnlyWithLayerMask = value;
  21687. this._resyncMeshes();
  21688. },
  21689. enumerable: true,
  21690. configurable: true
  21691. });
  21692. Object.defineProperty(Light.prototype, "lightmapMode", {
  21693. /**
  21694. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21695. */
  21696. get: function () {
  21697. return this._lightmapMode;
  21698. },
  21699. /**
  21700. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21701. */
  21702. set: function (value) {
  21703. if (this._lightmapMode === value) {
  21704. return;
  21705. }
  21706. this._lightmapMode = value;
  21707. this._markMeshesAsLightDirty();
  21708. },
  21709. enumerable: true,
  21710. configurable: true
  21711. });
  21712. /**
  21713. * Returns the string "Light".
  21714. * @returns the class name
  21715. */
  21716. Light.prototype.getClassName = function () {
  21717. return "Light";
  21718. };
  21719. /**
  21720. * Converts the light information to a readable string for debug purpose.
  21721. * @param fullDetails Supports for multiple levels of logging within scene loading
  21722. * @returns the human readable light info
  21723. */
  21724. Light.prototype.toString = function (fullDetails) {
  21725. var ret = "Name: " + this.name;
  21726. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21727. if (this.animations) {
  21728. for (var i = 0; i < this.animations.length; i++) {
  21729. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21730. }
  21731. }
  21732. if (fullDetails) {
  21733. }
  21734. return ret;
  21735. };
  21736. /**
  21737. * Set the enabled state of this node.
  21738. * @param value - the new enabled state
  21739. */
  21740. Light.prototype.setEnabled = function (value) {
  21741. _super.prototype.setEnabled.call(this, value);
  21742. this._resyncMeshes();
  21743. };
  21744. /**
  21745. * Returns the Light associated shadow generator if any.
  21746. * @return the associated shadow generator.
  21747. */
  21748. Light.prototype.getShadowGenerator = function () {
  21749. return this._shadowGenerator;
  21750. };
  21751. /**
  21752. * Returns a Vector3, the absolute light position in the World.
  21753. * @returns the world space position of the light
  21754. */
  21755. Light.prototype.getAbsolutePosition = function () {
  21756. return BABYLON.Vector3.Zero();
  21757. };
  21758. /**
  21759. * Specifies if the light will affect the passed mesh.
  21760. * @param mesh The mesh to test against the light
  21761. * @return true the mesh is affected otherwise, false.
  21762. */
  21763. Light.prototype.canAffectMesh = function (mesh) {
  21764. if (!mesh) {
  21765. return true;
  21766. }
  21767. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21768. return false;
  21769. }
  21770. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21771. return false;
  21772. }
  21773. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21774. return false;
  21775. }
  21776. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21777. return false;
  21778. }
  21779. return true;
  21780. };
  21781. /**
  21782. * Sort function to order lights for rendering.
  21783. * @param a First Light object to compare to second.
  21784. * @param b Second Light object to compare first.
  21785. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21786. */
  21787. Light.CompareLightsPriority = function (a, b) {
  21788. //shadow-casting lights have priority over non-shadow-casting lights
  21789. //the renderPrioirty is a secondary sort criterion
  21790. if (a.shadowEnabled !== b.shadowEnabled) {
  21791. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21792. }
  21793. return b.renderPriority - a.renderPriority;
  21794. };
  21795. /**
  21796. * Releases resources associated with this node.
  21797. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21798. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21799. */
  21800. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21801. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21802. if (this._shadowGenerator) {
  21803. this._shadowGenerator.dispose();
  21804. this._shadowGenerator = null;
  21805. }
  21806. // Animations
  21807. this.getScene().stopAnimation(this);
  21808. // Remove from meshes
  21809. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21810. var mesh = _a[_i];
  21811. mesh._removeLightSource(this);
  21812. }
  21813. this._uniformBuffer.dispose();
  21814. // Remove from scene
  21815. this.getScene().removeLight(this);
  21816. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21817. };
  21818. /**
  21819. * Returns the light type ID (integer).
  21820. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21821. */
  21822. Light.prototype.getTypeID = function () {
  21823. return 0;
  21824. };
  21825. /**
  21826. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21827. * @returns the scaled intensity in intensity mode unit
  21828. */
  21829. Light.prototype.getScaledIntensity = function () {
  21830. return this._photometricScale * this.intensity;
  21831. };
  21832. /**
  21833. * Returns a new Light object, named "name", from the current one.
  21834. * @param name The name of the cloned light
  21835. * @returns the new created light
  21836. */
  21837. Light.prototype.clone = function (name) {
  21838. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21839. if (!constructor) {
  21840. return null;
  21841. }
  21842. return BABYLON.SerializationHelper.Clone(constructor, this);
  21843. };
  21844. /**
  21845. * Serializes the current light into a Serialization object.
  21846. * @returns the serialized object.
  21847. */
  21848. Light.prototype.serialize = function () {
  21849. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21850. // Type
  21851. serializationObject.type = this.getTypeID();
  21852. // Parent
  21853. if (this.parent) {
  21854. serializationObject.parentId = this.parent.id;
  21855. }
  21856. // Inclusion / exclusions
  21857. if (this.excludedMeshes.length > 0) {
  21858. serializationObject.excludedMeshesIds = [];
  21859. this.excludedMeshes.forEach(function (mesh) {
  21860. serializationObject.excludedMeshesIds.push(mesh.id);
  21861. });
  21862. }
  21863. if (this.includedOnlyMeshes.length > 0) {
  21864. serializationObject.includedOnlyMeshesIds = [];
  21865. this.includedOnlyMeshes.forEach(function (mesh) {
  21866. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21867. });
  21868. }
  21869. // Animations
  21870. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21871. serializationObject.ranges = this.serializeAnimationRanges();
  21872. return serializationObject;
  21873. };
  21874. /**
  21875. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21876. * This new light is named "name" and added to the passed scene.
  21877. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21878. * @param name The friendly name of the light
  21879. * @param scene The scene the new light will belong to
  21880. * @returns the constructor function
  21881. */
  21882. Light.GetConstructorFromName = function (type, name, scene) {
  21883. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21884. if (constructorFunc) {
  21885. return constructorFunc;
  21886. }
  21887. // Default to no light for none present once.
  21888. return null;
  21889. };
  21890. /**
  21891. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21892. * @param parsedLight The JSON representation of the light
  21893. * @param scene The scene to create the parsed light in
  21894. * @returns the created light after parsing
  21895. */
  21896. Light.Parse = function (parsedLight, scene) {
  21897. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21898. if (!constructor) {
  21899. return null;
  21900. }
  21901. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21902. // Inclusion / exclusions
  21903. if (parsedLight.excludedMeshesIds) {
  21904. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21905. }
  21906. if (parsedLight.includedOnlyMeshesIds) {
  21907. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21908. }
  21909. // Parent
  21910. if (parsedLight.parentId) {
  21911. light._waitingParentId = parsedLight.parentId;
  21912. }
  21913. // Animations
  21914. if (parsedLight.animations) {
  21915. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21916. var parsedAnimation = parsedLight.animations[animationIndex];
  21917. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21918. }
  21919. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21920. }
  21921. if (parsedLight.autoAnimate) {
  21922. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21923. }
  21924. return light;
  21925. };
  21926. Light.prototype._hookArrayForExcluded = function (array) {
  21927. var _this = this;
  21928. var oldPush = array.push;
  21929. array.push = function () {
  21930. var items = [];
  21931. for (var _i = 0; _i < arguments.length; _i++) {
  21932. items[_i] = arguments[_i];
  21933. }
  21934. var result = oldPush.apply(array, items);
  21935. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21936. var item = items_1[_a];
  21937. item._resyncLighSource(_this);
  21938. }
  21939. return result;
  21940. };
  21941. var oldSplice = array.splice;
  21942. array.splice = function (index, deleteCount) {
  21943. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21944. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21945. var item = deleted_1[_i];
  21946. item._resyncLighSource(_this);
  21947. }
  21948. return deleted;
  21949. };
  21950. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21951. var item = array_1[_i];
  21952. item._resyncLighSource(this);
  21953. }
  21954. };
  21955. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21956. var _this = this;
  21957. var oldPush = array.push;
  21958. array.push = function () {
  21959. var items = [];
  21960. for (var _i = 0; _i < arguments.length; _i++) {
  21961. items[_i] = arguments[_i];
  21962. }
  21963. var result = oldPush.apply(array, items);
  21964. _this._resyncMeshes();
  21965. return result;
  21966. };
  21967. var oldSplice = array.splice;
  21968. array.splice = function (index, deleteCount) {
  21969. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21970. _this._resyncMeshes();
  21971. return deleted;
  21972. };
  21973. this._resyncMeshes();
  21974. };
  21975. Light.prototype._resyncMeshes = function () {
  21976. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21977. var mesh = _a[_i];
  21978. mesh._resyncLighSource(this);
  21979. }
  21980. };
  21981. /**
  21982. * Forces the meshes to update their light related information in their rendering used effects
  21983. * @hidden Internal Use Only
  21984. */
  21985. Light.prototype._markMeshesAsLightDirty = function () {
  21986. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21987. var mesh = _a[_i];
  21988. if (mesh._lightSources.indexOf(this) !== -1) {
  21989. mesh._markSubMeshesAsLightDirty();
  21990. }
  21991. }
  21992. };
  21993. /**
  21994. * Recomputes the cached photometric scale if needed.
  21995. */
  21996. Light.prototype._computePhotometricScale = function () {
  21997. this._photometricScale = this._getPhotometricScale();
  21998. this.getScene().resetCachedMaterial();
  21999. };
  22000. /**
  22001. * Returns the Photometric Scale according to the light type and intensity mode.
  22002. */
  22003. Light.prototype._getPhotometricScale = function () {
  22004. var photometricScale = 0.0;
  22005. var lightTypeID = this.getTypeID();
  22006. //get photometric mode
  22007. var photometricMode = this.intensityMode;
  22008. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22009. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22010. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22011. }
  22012. else {
  22013. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22014. }
  22015. }
  22016. //compute photometric scale
  22017. switch (lightTypeID) {
  22018. case Light.LIGHTTYPEID_POINTLIGHT:
  22019. case Light.LIGHTTYPEID_SPOTLIGHT:
  22020. switch (photometricMode) {
  22021. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22022. photometricScale = 1.0 / (4.0 * Math.PI);
  22023. break;
  22024. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22025. photometricScale = 1.0;
  22026. break;
  22027. case Light.INTENSITYMODE_LUMINANCE:
  22028. photometricScale = this.radius * this.radius;
  22029. break;
  22030. }
  22031. break;
  22032. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22033. switch (photometricMode) {
  22034. case Light.INTENSITYMODE_ILLUMINANCE:
  22035. photometricScale = 1.0;
  22036. break;
  22037. case Light.INTENSITYMODE_LUMINANCE:
  22038. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22039. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22040. var apexAngleRadians = this.radius;
  22041. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22042. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22043. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22044. photometricScale = solidAngle;
  22045. break;
  22046. }
  22047. break;
  22048. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22049. // No fall off in hemisperic light.
  22050. photometricScale = 1.0;
  22051. break;
  22052. }
  22053. return photometricScale;
  22054. };
  22055. /**
  22056. * Reorder the light in the scene according to their defined priority.
  22057. * @hidden Internal Use Only
  22058. */
  22059. Light.prototype._reorderLightsInScene = function () {
  22060. var scene = this.getScene();
  22061. if (this._renderPriority != 0) {
  22062. scene.requireLightSorting = true;
  22063. }
  22064. this.getScene().sortLightsByPriority();
  22065. };
  22066. /**
  22067. * Falloff Default: light is falling off following the material specification:
  22068. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22069. */
  22070. Light.FALLOFF_DEFAULT = 0;
  22071. /**
  22072. * Falloff Physical: light is falling off following the inverse squared distance law.
  22073. */
  22074. Light.FALLOFF_PHYSICAL = 1;
  22075. /**
  22076. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22077. * to enhance interoperability with other engines.
  22078. */
  22079. Light.FALLOFF_GLTF = 2;
  22080. /**
  22081. * Falloff Standard: light is falling off like in the standard material
  22082. * to enhance interoperability with other materials.
  22083. */
  22084. Light.FALLOFF_STANDARD = 3;
  22085. //lightmapMode Consts
  22086. /**
  22087. * If every light affecting the material is in this lightmapMode,
  22088. * material.lightmapTexture adds or multiplies
  22089. * (depends on material.useLightmapAsShadowmap)
  22090. * after every other light calculations.
  22091. */
  22092. Light.LIGHTMAP_DEFAULT = 0;
  22093. /**
  22094. * material.lightmapTexture as only diffuse lighting from this light
  22095. * adds only specular lighting from this light
  22096. * adds dynamic shadows
  22097. */
  22098. Light.LIGHTMAP_SPECULAR = 1;
  22099. /**
  22100. * material.lightmapTexture as only lighting
  22101. * no light calculation from this light
  22102. * only adds dynamic shadows from this light
  22103. */
  22104. Light.LIGHTMAP_SHADOWSONLY = 2;
  22105. // Intensity Mode Consts
  22106. /**
  22107. * Each light type uses the default quantity according to its type:
  22108. * point/spot lights use luminous intensity
  22109. * directional lights use illuminance
  22110. */
  22111. Light.INTENSITYMODE_AUTOMATIC = 0;
  22112. /**
  22113. * lumen (lm)
  22114. */
  22115. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22116. /**
  22117. * candela (lm/sr)
  22118. */
  22119. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22120. /**
  22121. * lux (lm/m^2)
  22122. */
  22123. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22124. /**
  22125. * nit (cd/m^2)
  22126. */
  22127. Light.INTENSITYMODE_LUMINANCE = 4;
  22128. // Light types ids const.
  22129. /**
  22130. * Light type const id of the point light.
  22131. */
  22132. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22133. /**
  22134. * Light type const id of the directional light.
  22135. */
  22136. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22137. /**
  22138. * Light type const id of the spot light.
  22139. */
  22140. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22141. /**
  22142. * Light type const id of the hemispheric light.
  22143. */
  22144. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22145. __decorate([
  22146. BABYLON.serializeAsColor3()
  22147. ], Light.prototype, "diffuse", void 0);
  22148. __decorate([
  22149. BABYLON.serializeAsColor3()
  22150. ], Light.prototype, "specular", void 0);
  22151. __decorate([
  22152. BABYLON.serialize()
  22153. ], Light.prototype, "falloffType", void 0);
  22154. __decorate([
  22155. BABYLON.serialize()
  22156. ], Light.prototype, "intensity", void 0);
  22157. __decorate([
  22158. BABYLON.serialize()
  22159. ], Light.prototype, "range", null);
  22160. __decorate([
  22161. BABYLON.serialize()
  22162. ], Light.prototype, "intensityMode", null);
  22163. __decorate([
  22164. BABYLON.serialize()
  22165. ], Light.prototype, "radius", null);
  22166. __decorate([
  22167. BABYLON.serialize()
  22168. ], Light.prototype, "_renderPriority", void 0);
  22169. __decorate([
  22170. BABYLON.expandToProperty("_reorderLightsInScene")
  22171. ], Light.prototype, "renderPriority", void 0);
  22172. __decorate([
  22173. BABYLON.serialize("shadowEnabled")
  22174. ], Light.prototype, "_shadowEnabled", void 0);
  22175. __decorate([
  22176. BABYLON.serialize("excludeWithLayerMask")
  22177. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22178. __decorate([
  22179. BABYLON.serialize("includeOnlyWithLayerMask")
  22180. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22181. __decorate([
  22182. BABYLON.serialize("lightmapMode")
  22183. ], Light.prototype, "_lightmapMode", void 0);
  22184. return Light;
  22185. }(BABYLON.Node));
  22186. BABYLON.Light = Light;
  22187. })(BABYLON || (BABYLON = {}));
  22188. //# sourceMappingURL=babylon.light.js.map
  22189. var BABYLON;
  22190. (function (BABYLON) {
  22191. var Camera = /** @class */ (function (_super) {
  22192. __extends(Camera, _super);
  22193. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22194. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22195. var _this = _super.call(this, name, scene) || this;
  22196. /**
  22197. * The vector the camera should consider as up.
  22198. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22199. */
  22200. _this.upVector = BABYLON.Vector3.Up();
  22201. _this.orthoLeft = null;
  22202. _this.orthoRight = null;
  22203. _this.orthoBottom = null;
  22204. _this.orthoTop = null;
  22205. /**
  22206. * FOV is set in Radians. (default is 0.8)
  22207. */
  22208. _this.fov = 0.8;
  22209. _this.minZ = 1;
  22210. _this.maxZ = 10000.0;
  22211. _this.inertia = 0.9;
  22212. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22213. _this.isIntermediate = false;
  22214. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22215. /**
  22216. * Restricts the camera to viewing objects with the same layerMask.
  22217. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22218. */
  22219. _this.layerMask = 0x0FFFFFFF;
  22220. /**
  22221. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22222. */
  22223. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22224. // Camera rig members
  22225. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22226. /** @hidden */
  22227. _this._rigCameras = new Array();
  22228. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22229. /** @hidden */
  22230. _this._skipRendering = false;
  22231. _this.customRenderTargets = new Array();
  22232. // Observables
  22233. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22234. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22235. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22236. _this.onRestoreStateObservable = new BABYLON.Observable();
  22237. // Cache
  22238. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22239. _this._projectionMatrix = new BABYLON.Matrix();
  22240. _this._doNotComputeProjectionMatrix = false;
  22241. _this._postProcesses = new Array();
  22242. _this._transformMatrix = BABYLON.Matrix.Zero();
  22243. _this._activeMeshes = new BABYLON.SmartArray(256);
  22244. _this._globalPosition = BABYLON.Vector3.Zero();
  22245. _this._refreshFrustumPlanes = true;
  22246. _this.getScene().addCamera(_this);
  22247. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22248. _this.getScene().activeCamera = _this;
  22249. }
  22250. _this.position = position;
  22251. return _this;
  22252. }
  22253. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22254. get: function () {
  22255. return Camera._PERSPECTIVE_CAMERA;
  22256. },
  22257. enumerable: true,
  22258. configurable: true
  22259. });
  22260. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22261. get: function () {
  22262. return Camera._ORTHOGRAPHIC_CAMERA;
  22263. },
  22264. enumerable: true,
  22265. configurable: true
  22266. });
  22267. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22268. /**
  22269. * This is the default FOV mode for perspective cameras.
  22270. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22271. *
  22272. */
  22273. get: function () {
  22274. return Camera._FOVMODE_VERTICAL_FIXED;
  22275. },
  22276. enumerable: true,
  22277. configurable: true
  22278. });
  22279. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22280. /**
  22281. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22282. *
  22283. */
  22284. get: function () {
  22285. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22286. },
  22287. enumerable: true,
  22288. configurable: true
  22289. });
  22290. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22291. get: function () {
  22292. return Camera._RIG_MODE_NONE;
  22293. },
  22294. enumerable: true,
  22295. configurable: true
  22296. });
  22297. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22298. get: function () {
  22299. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22300. },
  22301. enumerable: true,
  22302. configurable: true
  22303. });
  22304. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22305. get: function () {
  22306. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22307. },
  22308. enumerable: true,
  22309. configurable: true
  22310. });
  22311. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22312. get: function () {
  22313. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22314. },
  22315. enumerable: true,
  22316. configurable: true
  22317. });
  22318. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22319. get: function () {
  22320. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22321. },
  22322. enumerable: true,
  22323. configurable: true
  22324. });
  22325. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22326. get: function () {
  22327. return Camera._RIG_MODE_VR;
  22328. },
  22329. enumerable: true,
  22330. configurable: true
  22331. });
  22332. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22333. get: function () {
  22334. return Camera._RIG_MODE_WEBVR;
  22335. },
  22336. enumerable: true,
  22337. configurable: true
  22338. });
  22339. /**
  22340. * Store current camera state (fov, position, etc..)
  22341. */
  22342. Camera.prototype.storeState = function () {
  22343. this._stateStored = true;
  22344. this._storedFov = this.fov;
  22345. return this;
  22346. };
  22347. /**
  22348. * Restores the camera state values if it has been stored. You must call storeState() first
  22349. */
  22350. Camera.prototype._restoreStateValues = function () {
  22351. if (!this._stateStored) {
  22352. return false;
  22353. }
  22354. this.fov = this._storedFov;
  22355. return true;
  22356. };
  22357. /**
  22358. * Restored camera state. You must call storeState() first
  22359. */
  22360. Camera.prototype.restoreState = function () {
  22361. if (this._restoreStateValues()) {
  22362. this.onRestoreStateObservable.notifyObservers(this);
  22363. return true;
  22364. }
  22365. return false;
  22366. };
  22367. Camera.prototype.getClassName = function () {
  22368. return "Camera";
  22369. };
  22370. /**
  22371. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22372. */
  22373. Camera.prototype.toString = function (fullDetails) {
  22374. var ret = "Name: " + this.name;
  22375. ret += ", type: " + this.getClassName();
  22376. if (this.animations) {
  22377. for (var i = 0; i < this.animations.length; i++) {
  22378. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22379. }
  22380. }
  22381. if (fullDetails) {
  22382. }
  22383. return ret;
  22384. };
  22385. Object.defineProperty(Camera.prototype, "globalPosition", {
  22386. get: function () {
  22387. return this._globalPosition;
  22388. },
  22389. enumerable: true,
  22390. configurable: true
  22391. });
  22392. Camera.prototype.getActiveMeshes = function () {
  22393. return this._activeMeshes;
  22394. };
  22395. Camera.prototype.isActiveMesh = function (mesh) {
  22396. return (this._activeMeshes.indexOf(mesh) !== -1);
  22397. };
  22398. /**
  22399. * Is this camera ready to be used/rendered
  22400. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22401. * @return true if the camera is ready
  22402. */
  22403. Camera.prototype.isReady = function (completeCheck) {
  22404. if (completeCheck === void 0) { completeCheck = false; }
  22405. if (completeCheck) {
  22406. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22407. var pp = _a[_i];
  22408. if (pp && !pp.isReady()) {
  22409. return false;
  22410. }
  22411. }
  22412. }
  22413. return _super.prototype.isReady.call(this, completeCheck);
  22414. };
  22415. //Cache
  22416. /** @hidden */
  22417. Camera.prototype._initCache = function () {
  22418. _super.prototype._initCache.call(this);
  22419. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22420. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22421. this._cache.mode = undefined;
  22422. this._cache.minZ = undefined;
  22423. this._cache.maxZ = undefined;
  22424. this._cache.fov = undefined;
  22425. this._cache.fovMode = undefined;
  22426. this._cache.aspectRatio = undefined;
  22427. this._cache.orthoLeft = undefined;
  22428. this._cache.orthoRight = undefined;
  22429. this._cache.orthoBottom = undefined;
  22430. this._cache.orthoTop = undefined;
  22431. this._cache.renderWidth = undefined;
  22432. this._cache.renderHeight = undefined;
  22433. };
  22434. /** @hidden */
  22435. Camera.prototype._updateCache = function (ignoreParentClass) {
  22436. if (!ignoreParentClass) {
  22437. _super.prototype._updateCache.call(this);
  22438. }
  22439. this._cache.position.copyFrom(this.position);
  22440. this._cache.upVector.copyFrom(this.upVector);
  22441. };
  22442. // Synchronized
  22443. /** @hidden */
  22444. Camera.prototype._isSynchronized = function () {
  22445. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22446. };
  22447. /** @hidden */
  22448. Camera.prototype._isSynchronizedViewMatrix = function () {
  22449. if (!_super.prototype._isSynchronized.call(this))
  22450. return false;
  22451. return this._cache.position.equals(this.position)
  22452. && this._cache.upVector.equals(this.upVector)
  22453. && this.isSynchronizedWithParent();
  22454. };
  22455. /** @hidden */
  22456. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22457. var check = this._cache.mode === this.mode
  22458. && this._cache.minZ === this.minZ
  22459. && this._cache.maxZ === this.maxZ;
  22460. if (!check) {
  22461. return false;
  22462. }
  22463. var engine = this.getEngine();
  22464. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22465. check = this._cache.fov === this.fov
  22466. && this._cache.fovMode === this.fovMode
  22467. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22468. }
  22469. else {
  22470. check = this._cache.orthoLeft === this.orthoLeft
  22471. && this._cache.orthoRight === this.orthoRight
  22472. && this._cache.orthoBottom === this.orthoBottom
  22473. && this._cache.orthoTop === this.orthoTop
  22474. && this._cache.renderWidth === engine.getRenderWidth()
  22475. && this._cache.renderHeight === engine.getRenderHeight();
  22476. }
  22477. return check;
  22478. };
  22479. // Controls
  22480. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22481. };
  22482. Camera.prototype.detachControl = function (element) {
  22483. };
  22484. Camera.prototype.update = function () {
  22485. this._checkInputs();
  22486. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22487. this._updateRigCameras();
  22488. }
  22489. };
  22490. /** @hidden */
  22491. Camera.prototype._checkInputs = function () {
  22492. this.onAfterCheckInputsObservable.notifyObservers(this);
  22493. };
  22494. Object.defineProperty(Camera.prototype, "rigCameras", {
  22495. get: function () {
  22496. return this._rigCameras;
  22497. },
  22498. enumerable: true,
  22499. configurable: true
  22500. });
  22501. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22502. get: function () {
  22503. return this._rigPostProcess;
  22504. },
  22505. enumerable: true,
  22506. configurable: true
  22507. });
  22508. /**
  22509. * Internal, gets the first post proces.
  22510. * @returns the first post process to be run on this camera.
  22511. */
  22512. Camera.prototype._getFirstPostProcess = function () {
  22513. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22514. if (this._postProcesses[ppIndex] !== null) {
  22515. return this._postProcesses[ppIndex];
  22516. }
  22517. }
  22518. return null;
  22519. };
  22520. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22521. // invalidate framebuffer
  22522. var firstPostProcess = this._getFirstPostProcess();
  22523. if (firstPostProcess) {
  22524. firstPostProcess.markTextureDirty();
  22525. }
  22526. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22527. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22528. var cam = this._rigCameras[i];
  22529. var rigPostProcess = cam._rigPostProcess;
  22530. // for VR rig, there does not have to be a post process
  22531. if (rigPostProcess) {
  22532. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22533. if (isPass) {
  22534. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22535. cam.isIntermediate = this._postProcesses.length === 0;
  22536. }
  22537. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22538. rigPostProcess.markTextureDirty();
  22539. }
  22540. else {
  22541. cam._postProcesses = this._postProcesses.slice(0);
  22542. }
  22543. }
  22544. };
  22545. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22546. if (insertAt === void 0) { insertAt = null; }
  22547. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22548. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22549. return 0;
  22550. }
  22551. if (insertAt == null || insertAt < 0) {
  22552. this._postProcesses.push(postProcess);
  22553. }
  22554. else if (this._postProcesses[insertAt] === null) {
  22555. this._postProcesses[insertAt] = postProcess;
  22556. }
  22557. else {
  22558. this._postProcesses.splice(insertAt, 0, postProcess);
  22559. }
  22560. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22561. return this._postProcesses.indexOf(postProcess);
  22562. };
  22563. Camera.prototype.detachPostProcess = function (postProcess) {
  22564. var idx = this._postProcesses.indexOf(postProcess);
  22565. if (idx !== -1) {
  22566. this._postProcesses[idx] = null;
  22567. }
  22568. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22569. };
  22570. Camera.prototype.getWorldMatrix = function () {
  22571. if (this._isSynchronizedViewMatrix()) {
  22572. return this._worldMatrix;
  22573. }
  22574. // Getting the the view matrix will also compute the world matrix.
  22575. this.getViewMatrix();
  22576. return this._worldMatrix;
  22577. };
  22578. /** @hidden */
  22579. Camera.prototype._getViewMatrix = function () {
  22580. return BABYLON.Matrix.Identity();
  22581. };
  22582. Camera.prototype.getViewMatrix = function (force) {
  22583. if (!force && this._isSynchronizedViewMatrix()) {
  22584. return this._computedViewMatrix;
  22585. }
  22586. this.updateCache();
  22587. this._computedViewMatrix = this._getViewMatrix();
  22588. this._currentRenderId = this.getScene().getRenderId();
  22589. this._childRenderId = this._currentRenderId;
  22590. this._refreshFrustumPlanes = true;
  22591. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22592. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22593. }
  22594. this.onViewMatrixChangedObservable.notifyObservers(this);
  22595. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22596. return this._computedViewMatrix;
  22597. };
  22598. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22599. this._doNotComputeProjectionMatrix = true;
  22600. if (projection !== undefined) {
  22601. this._projectionMatrix = projection;
  22602. }
  22603. };
  22604. ;
  22605. Camera.prototype.unfreezeProjectionMatrix = function () {
  22606. this._doNotComputeProjectionMatrix = false;
  22607. };
  22608. ;
  22609. Camera.prototype.getProjectionMatrix = function (force) {
  22610. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22611. return this._projectionMatrix;
  22612. }
  22613. // Cache
  22614. this._cache.mode = this.mode;
  22615. this._cache.minZ = this.minZ;
  22616. this._cache.maxZ = this.maxZ;
  22617. // Matrix
  22618. this._refreshFrustumPlanes = true;
  22619. var engine = this.getEngine();
  22620. var scene = this.getScene();
  22621. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22622. this._cache.fov = this.fov;
  22623. this._cache.fovMode = this.fovMode;
  22624. this._cache.aspectRatio = engine.getAspectRatio(this);
  22625. if (this.minZ <= 0) {
  22626. this.minZ = 0.1;
  22627. }
  22628. if (scene.useRightHandedSystem) {
  22629. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22630. }
  22631. else {
  22632. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22633. }
  22634. }
  22635. else {
  22636. var halfWidth = engine.getRenderWidth() / 2.0;
  22637. var halfHeight = engine.getRenderHeight() / 2.0;
  22638. if (scene.useRightHandedSystem) {
  22639. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22640. }
  22641. else {
  22642. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22643. }
  22644. this._cache.orthoLeft = this.orthoLeft;
  22645. this._cache.orthoRight = this.orthoRight;
  22646. this._cache.orthoBottom = this.orthoBottom;
  22647. this._cache.orthoTop = this.orthoTop;
  22648. this._cache.renderWidth = engine.getRenderWidth();
  22649. this._cache.renderHeight = engine.getRenderHeight();
  22650. }
  22651. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22652. return this._projectionMatrix;
  22653. };
  22654. /**
  22655. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22656. * @returns a Matrix
  22657. */
  22658. Camera.prototype.getTransformationMatrix = function () {
  22659. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22660. return this._transformMatrix;
  22661. };
  22662. Camera.prototype.updateFrustumPlanes = function () {
  22663. if (!this._refreshFrustumPlanes) {
  22664. return;
  22665. }
  22666. this.getTransformationMatrix();
  22667. if (!this._frustumPlanes) {
  22668. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22669. }
  22670. else {
  22671. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22672. }
  22673. this._refreshFrustumPlanes = false;
  22674. };
  22675. Camera.prototype.isInFrustum = function (target) {
  22676. this.updateFrustumPlanes();
  22677. return target.isInFrustum(this._frustumPlanes);
  22678. };
  22679. Camera.prototype.isCompletelyInFrustum = function (target) {
  22680. this.updateFrustumPlanes();
  22681. return target.isCompletelyInFrustum(this._frustumPlanes);
  22682. };
  22683. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22684. if (length === void 0) { length = 100; }
  22685. if (!transform) {
  22686. transform = this.getWorldMatrix();
  22687. }
  22688. if (!origin) {
  22689. origin = this.position;
  22690. }
  22691. var forward = new BABYLON.Vector3(0, 0, 1);
  22692. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22693. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22694. return new BABYLON.Ray(origin, direction, length);
  22695. };
  22696. /**
  22697. * Releases resources associated with this node.
  22698. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22699. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22700. */
  22701. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22702. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22703. // Observables
  22704. this.onViewMatrixChangedObservable.clear();
  22705. this.onProjectionMatrixChangedObservable.clear();
  22706. this.onAfterCheckInputsObservable.clear();
  22707. this.onRestoreStateObservable.clear();
  22708. // Inputs
  22709. if (this.inputs) {
  22710. this.inputs.clear();
  22711. }
  22712. // Animations
  22713. this.getScene().stopAnimation(this);
  22714. // Remove from scene
  22715. this.getScene().removeCamera(this);
  22716. while (this._rigCameras.length > 0) {
  22717. var camera = this._rigCameras.pop();
  22718. if (camera) {
  22719. camera.dispose();
  22720. }
  22721. }
  22722. // Postprocesses
  22723. if (this._rigPostProcess) {
  22724. this._rigPostProcess.dispose(this);
  22725. this._rigPostProcess = null;
  22726. this._postProcesses = [];
  22727. }
  22728. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22729. this._rigPostProcess = null;
  22730. this._postProcesses = [];
  22731. }
  22732. else {
  22733. var i = this._postProcesses.length;
  22734. while (--i >= 0) {
  22735. var postProcess = this._postProcesses[i];
  22736. if (postProcess) {
  22737. postProcess.dispose(this);
  22738. }
  22739. }
  22740. }
  22741. // Render targets
  22742. var i = this.customRenderTargets.length;
  22743. while (--i >= 0) {
  22744. this.customRenderTargets[i].dispose();
  22745. }
  22746. this.customRenderTargets = [];
  22747. // Active Meshes
  22748. this._activeMeshes.dispose();
  22749. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22750. };
  22751. Object.defineProperty(Camera.prototype, "leftCamera", {
  22752. // ---- Camera rigs section ----
  22753. get: function () {
  22754. if (this._rigCameras.length < 1) {
  22755. return null;
  22756. }
  22757. return this._rigCameras[0];
  22758. },
  22759. enumerable: true,
  22760. configurable: true
  22761. });
  22762. Object.defineProperty(Camera.prototype, "rightCamera", {
  22763. get: function () {
  22764. if (this._rigCameras.length < 2) {
  22765. return null;
  22766. }
  22767. return this._rigCameras[1];
  22768. },
  22769. enumerable: true,
  22770. configurable: true
  22771. });
  22772. Camera.prototype.getLeftTarget = function () {
  22773. if (this._rigCameras.length < 1) {
  22774. return null;
  22775. }
  22776. return this._rigCameras[0].getTarget();
  22777. };
  22778. Camera.prototype.getRightTarget = function () {
  22779. if (this._rigCameras.length < 2) {
  22780. return null;
  22781. }
  22782. return this._rigCameras[1].getTarget();
  22783. };
  22784. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22785. if (this.cameraRigMode === mode) {
  22786. return;
  22787. }
  22788. while (this._rigCameras.length > 0) {
  22789. var camera = this._rigCameras.pop();
  22790. if (camera) {
  22791. camera.dispose();
  22792. }
  22793. }
  22794. this.cameraRigMode = mode;
  22795. this._cameraRigParams = {};
  22796. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22797. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22798. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22799. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22800. // create the rig cameras, unless none
  22801. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22802. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22803. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22804. if (leftCamera && rightCamera) {
  22805. this._rigCameras.push(leftCamera);
  22806. this._rigCameras.push(rightCamera);
  22807. }
  22808. }
  22809. switch (this.cameraRigMode) {
  22810. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22811. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22812. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22813. break;
  22814. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22815. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22816. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22817. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22818. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22819. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22820. break;
  22821. case Camera.RIG_MODE_VR:
  22822. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22823. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22824. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22825. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22826. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22827. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22828. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22829. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22830. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22831. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22832. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22833. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22834. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22835. if (metrics.compensateDistortion) {
  22836. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22837. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22838. }
  22839. break;
  22840. case Camera.RIG_MODE_WEBVR:
  22841. if (rigParams.vrDisplay) {
  22842. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22843. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22844. //Left eye
  22845. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22846. this._rigCameras[0].setCameraRigParameter("left", true);
  22847. //leaving this for future reference
  22848. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22849. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22850. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22851. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22852. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22853. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22854. this._rigCameras[0].parent = this;
  22855. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22856. //Right eye
  22857. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22858. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22859. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22860. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22861. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22862. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22863. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22864. this._rigCameras[1].parent = this;
  22865. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22866. if (Camera.UseAlternateWebVRRendering) {
  22867. this._rigCameras[1]._skipRendering = true;
  22868. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22869. }
  22870. }
  22871. break;
  22872. }
  22873. this._cascadePostProcessesToRigCams();
  22874. this.update();
  22875. };
  22876. Camera.prototype._getVRProjectionMatrix = function () {
  22877. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22878. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22879. return this._projectionMatrix;
  22880. };
  22881. Camera.prototype._updateCameraRotationMatrix = function () {
  22882. //Here for WebVR
  22883. };
  22884. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22885. //Here for WebVR
  22886. };
  22887. /**
  22888. * This function MUST be overwritten by the different WebVR cameras available.
  22889. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22890. */
  22891. Camera.prototype._getWebVRProjectionMatrix = function () {
  22892. return BABYLON.Matrix.Identity();
  22893. };
  22894. /**
  22895. * This function MUST be overwritten by the different WebVR cameras available.
  22896. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22897. */
  22898. Camera.prototype._getWebVRViewMatrix = function () {
  22899. return BABYLON.Matrix.Identity();
  22900. };
  22901. Camera.prototype.setCameraRigParameter = function (name, value) {
  22902. if (!this._cameraRigParams) {
  22903. this._cameraRigParams = {};
  22904. }
  22905. this._cameraRigParams[name] = value;
  22906. //provisionnally:
  22907. if (name === "interaxialDistance") {
  22908. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22909. }
  22910. };
  22911. /**
  22912. * needs to be overridden by children so sub has required properties to be copied
  22913. */
  22914. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22915. return null;
  22916. };
  22917. /**
  22918. * May need to be overridden by children
  22919. * @hidden
  22920. */
  22921. Camera.prototype._updateRigCameras = function () {
  22922. for (var i = 0; i < this._rigCameras.length; i++) {
  22923. this._rigCameras[i].minZ = this.minZ;
  22924. this._rigCameras[i].maxZ = this.maxZ;
  22925. this._rigCameras[i].fov = this.fov;
  22926. }
  22927. // only update viewport when ANAGLYPH
  22928. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22929. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22930. }
  22931. };
  22932. /** @hidden */
  22933. Camera.prototype._setupInputs = function () {
  22934. };
  22935. Camera.prototype.serialize = function () {
  22936. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22937. // Type
  22938. serializationObject.type = this.getClassName();
  22939. // Parent
  22940. if (this.parent) {
  22941. serializationObject.parentId = this.parent.id;
  22942. }
  22943. if (this.inputs) {
  22944. this.inputs.serialize(serializationObject);
  22945. }
  22946. // Animations
  22947. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22948. serializationObject.ranges = this.serializeAnimationRanges();
  22949. return serializationObject;
  22950. };
  22951. Camera.prototype.clone = function (name) {
  22952. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22953. };
  22954. Camera.prototype.getDirection = function (localAxis) {
  22955. var result = BABYLON.Vector3.Zero();
  22956. this.getDirectionToRef(localAxis, result);
  22957. return result;
  22958. };
  22959. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22960. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22961. };
  22962. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22963. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22964. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22965. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22966. interaxial_distance: interaxial_distance,
  22967. isStereoscopicSideBySide: isStereoscopicSideBySide
  22968. });
  22969. if (constructorFunc) {
  22970. return constructorFunc;
  22971. }
  22972. // Default to universal camera
  22973. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22974. };
  22975. Camera.prototype.computeWorldMatrix = function () {
  22976. return this.getWorldMatrix();
  22977. };
  22978. Camera.Parse = function (parsedCamera, scene) {
  22979. var type = parsedCamera.type;
  22980. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22981. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22982. // Parent
  22983. if (parsedCamera.parentId) {
  22984. camera._waitingParentId = parsedCamera.parentId;
  22985. }
  22986. //If camera has an input manager, let it parse inputs settings
  22987. if (camera.inputs) {
  22988. camera.inputs.parse(parsedCamera);
  22989. camera._setupInputs();
  22990. }
  22991. if (camera.setPosition) { // need to force position
  22992. camera.position.copyFromFloats(0, 0, 0);
  22993. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22994. }
  22995. // Target
  22996. if (parsedCamera.target) {
  22997. if (camera.setTarget) {
  22998. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22999. }
  23000. }
  23001. // Apply 3d rig, when found
  23002. if (parsedCamera.cameraRigMode) {
  23003. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23004. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23005. }
  23006. // Animations
  23007. if (parsedCamera.animations) {
  23008. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23009. var parsedAnimation = parsedCamera.animations[animationIndex];
  23010. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23011. }
  23012. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23013. }
  23014. if (parsedCamera.autoAnimate) {
  23015. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23016. }
  23017. return camera;
  23018. };
  23019. // Statics
  23020. Camera._PERSPECTIVE_CAMERA = 0;
  23021. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23022. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23023. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23024. Camera._RIG_MODE_NONE = 0;
  23025. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23026. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23027. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23028. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23029. Camera._RIG_MODE_VR = 20;
  23030. Camera._RIG_MODE_WEBVR = 21;
  23031. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23032. Camera.UseAlternateWebVRRendering = false;
  23033. __decorate([
  23034. BABYLON.serializeAsVector3()
  23035. ], Camera.prototype, "position", void 0);
  23036. __decorate([
  23037. BABYLON.serializeAsVector3()
  23038. ], Camera.prototype, "upVector", void 0);
  23039. __decorate([
  23040. BABYLON.serialize()
  23041. ], Camera.prototype, "orthoLeft", void 0);
  23042. __decorate([
  23043. BABYLON.serialize()
  23044. ], Camera.prototype, "orthoRight", void 0);
  23045. __decorate([
  23046. BABYLON.serialize()
  23047. ], Camera.prototype, "orthoBottom", void 0);
  23048. __decorate([
  23049. BABYLON.serialize()
  23050. ], Camera.prototype, "orthoTop", void 0);
  23051. __decorate([
  23052. BABYLON.serialize()
  23053. ], Camera.prototype, "fov", void 0);
  23054. __decorate([
  23055. BABYLON.serialize()
  23056. ], Camera.prototype, "minZ", void 0);
  23057. __decorate([
  23058. BABYLON.serialize()
  23059. ], Camera.prototype, "maxZ", void 0);
  23060. __decorate([
  23061. BABYLON.serialize()
  23062. ], Camera.prototype, "inertia", void 0);
  23063. __decorate([
  23064. BABYLON.serialize()
  23065. ], Camera.prototype, "mode", void 0);
  23066. __decorate([
  23067. BABYLON.serialize()
  23068. ], Camera.prototype, "layerMask", void 0);
  23069. __decorate([
  23070. BABYLON.serialize()
  23071. ], Camera.prototype, "fovMode", void 0);
  23072. __decorate([
  23073. BABYLON.serialize()
  23074. ], Camera.prototype, "cameraRigMode", void 0);
  23075. __decorate([
  23076. BABYLON.serialize()
  23077. ], Camera.prototype, "interaxialDistance", void 0);
  23078. __decorate([
  23079. BABYLON.serialize()
  23080. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23081. return Camera;
  23082. }(BABYLON.Node));
  23083. BABYLON.Camera = Camera;
  23084. })(BABYLON || (BABYLON = {}));
  23085. //# sourceMappingURL=babylon.camera.js.map
  23086. var BABYLON;
  23087. (function (BABYLON) {
  23088. var RenderingManager = /** @class */ (function () {
  23089. function RenderingManager(scene) {
  23090. /**
  23091. * @hidden
  23092. */
  23093. this._useSceneAutoClearSetup = false;
  23094. this._renderingGroups = new Array();
  23095. this._autoClearDepthStencil = {};
  23096. this._customOpaqueSortCompareFn = {};
  23097. this._customAlphaTestSortCompareFn = {};
  23098. this._customTransparentSortCompareFn = {};
  23099. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23100. this._scene = scene;
  23101. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23102. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23103. }
  23104. }
  23105. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23106. if (depth === void 0) { depth = true; }
  23107. if (stencil === void 0) { stencil = true; }
  23108. if (this._depthStencilBufferAlreadyCleaned) {
  23109. return;
  23110. }
  23111. this._scene.getEngine().clear(null, false, depth, stencil);
  23112. this._depthStencilBufferAlreadyCleaned = true;
  23113. };
  23114. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23115. // Update the observable context (not null as it only goes away on dispose)
  23116. var info = this._renderingGroupInfo;
  23117. info.scene = this._scene;
  23118. info.camera = this._scene.activeCamera;
  23119. // Dispatch sprites
  23120. if (this._scene.spriteManagers && renderSprites) {
  23121. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23122. var manager = this._scene.spriteManagers[index];
  23123. this.dispatchSprites(manager);
  23124. }
  23125. }
  23126. // Render
  23127. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23128. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23129. var renderingGroup = this._renderingGroups[index];
  23130. if (!renderingGroup)
  23131. continue;
  23132. var renderingGroupMask = Math.pow(2, index);
  23133. info.renderingGroupId = index;
  23134. // Before Observable
  23135. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23136. // Clear depth/stencil if needed
  23137. if (RenderingManager.AUTOCLEAR) {
  23138. var autoClear = this._useSceneAutoClearSetup ?
  23139. this._scene.getAutoClearDepthStencilSetup(index) :
  23140. this._autoClearDepthStencil[index];
  23141. if (autoClear && autoClear.autoClear) {
  23142. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23143. }
  23144. }
  23145. // Render
  23146. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23147. var step = _a[_i];
  23148. step.action(index);
  23149. }
  23150. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23151. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23152. var step = _c[_b];
  23153. step.action(index);
  23154. }
  23155. // After Observable
  23156. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23157. }
  23158. };
  23159. RenderingManager.prototype.reset = function () {
  23160. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23161. var renderingGroup = this._renderingGroups[index];
  23162. if (renderingGroup) {
  23163. renderingGroup.prepare();
  23164. }
  23165. }
  23166. };
  23167. RenderingManager.prototype.dispose = function () {
  23168. this.freeRenderingGroups();
  23169. this._renderingGroups.length = 0;
  23170. this._renderingGroupInfo = null;
  23171. };
  23172. /**
  23173. * Clear the info related to rendering groups preventing retention points during dispose.
  23174. */
  23175. RenderingManager.prototype.freeRenderingGroups = function () {
  23176. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23177. var renderingGroup = this._renderingGroups[index];
  23178. if (renderingGroup) {
  23179. renderingGroup.dispose();
  23180. }
  23181. }
  23182. };
  23183. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23184. if (this._renderingGroups[renderingGroupId] === undefined) {
  23185. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23186. }
  23187. };
  23188. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23189. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23190. this._prepareRenderingGroup(renderingGroupId);
  23191. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23192. };
  23193. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23194. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23195. this._prepareRenderingGroup(renderingGroupId);
  23196. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23197. };
  23198. /**
  23199. * @param subMesh The submesh to dispatch
  23200. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23201. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23202. */
  23203. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23204. if (mesh === undefined) {
  23205. mesh = subMesh.getMesh();
  23206. }
  23207. var renderingGroupId = mesh.renderingGroupId || 0;
  23208. this._prepareRenderingGroup(renderingGroupId);
  23209. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23210. };
  23211. /**
  23212. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23213. * This allowed control for front to back rendering or reversly depending of the special needs.
  23214. *
  23215. * @param renderingGroupId The rendering group id corresponding to its index
  23216. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23217. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23218. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23219. */
  23220. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23221. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23222. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23223. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23224. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23225. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23226. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23227. if (this._renderingGroups[renderingGroupId]) {
  23228. var group = this._renderingGroups[renderingGroupId];
  23229. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23230. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23231. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23232. }
  23233. };
  23234. /**
  23235. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23236. *
  23237. * @param renderingGroupId The rendering group id corresponding to its index
  23238. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23239. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23240. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23241. */
  23242. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23243. if (depth === void 0) { depth = true; }
  23244. if (stencil === void 0) { stencil = true; }
  23245. this._autoClearDepthStencil[renderingGroupId] = {
  23246. autoClear: autoClearDepthStencil,
  23247. depth: depth,
  23248. stencil: stencil
  23249. };
  23250. };
  23251. /**
  23252. * Gets the current auto clear configuration for one rendering group of the rendering
  23253. * manager.
  23254. * @param index the rendering group index to get the information for
  23255. * @returns The auto clear setup for the requested rendering group
  23256. */
  23257. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23258. return this._autoClearDepthStencil[index];
  23259. };
  23260. /**
  23261. * The max id used for rendering groups (not included)
  23262. */
  23263. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23264. /**
  23265. * The min id used for rendering groups (included)
  23266. */
  23267. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23268. /**
  23269. * Used to globally prevent autoclearing scenes.
  23270. */
  23271. RenderingManager.AUTOCLEAR = true;
  23272. return RenderingManager;
  23273. }());
  23274. BABYLON.RenderingManager = RenderingManager;
  23275. })(BABYLON || (BABYLON = {}));
  23276. //# sourceMappingURL=babylon.renderingManager.js.map
  23277. var BABYLON;
  23278. (function (BABYLON) {
  23279. var RenderingGroup = /** @class */ (function () {
  23280. /**
  23281. * Creates a new rendering group.
  23282. * @param index The rendering group index
  23283. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23284. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23285. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23286. */
  23287. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23288. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23289. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23290. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23291. this.index = index;
  23292. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23293. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23294. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23295. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23296. this._particleSystems = new BABYLON.SmartArray(256);
  23297. this._spriteManagers = new BABYLON.SmartArray(256);
  23298. this._edgesRenderers = new BABYLON.SmartArray(16);
  23299. this._scene = scene;
  23300. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23301. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23302. this.transparentSortCompareFn = transparentSortCompareFn;
  23303. }
  23304. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23305. /**
  23306. * Set the opaque sort comparison function.
  23307. * If null the sub meshes will be render in the order they were created
  23308. */
  23309. set: function (value) {
  23310. this._opaqueSortCompareFn = value;
  23311. if (value) {
  23312. this._renderOpaque = this.renderOpaqueSorted;
  23313. }
  23314. else {
  23315. this._renderOpaque = RenderingGroup.renderUnsorted;
  23316. }
  23317. },
  23318. enumerable: true,
  23319. configurable: true
  23320. });
  23321. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23322. /**
  23323. * Set the alpha test sort comparison function.
  23324. * If null the sub meshes will be render in the order they were created
  23325. */
  23326. set: function (value) {
  23327. this._alphaTestSortCompareFn = value;
  23328. if (value) {
  23329. this._renderAlphaTest = this.renderAlphaTestSorted;
  23330. }
  23331. else {
  23332. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23333. }
  23334. },
  23335. enumerable: true,
  23336. configurable: true
  23337. });
  23338. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23339. /**
  23340. * Set the transparent sort comparison function.
  23341. * If null the sub meshes will be render in the order they were created
  23342. */
  23343. set: function (value) {
  23344. if (value) {
  23345. this._transparentSortCompareFn = value;
  23346. }
  23347. else {
  23348. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23349. }
  23350. this._renderTransparent = this.renderTransparentSorted;
  23351. },
  23352. enumerable: true,
  23353. configurable: true
  23354. });
  23355. /**
  23356. * Render all the sub meshes contained in the group.
  23357. * @param customRenderFunction Used to override the default render behaviour of the group.
  23358. * @returns true if rendered some submeshes.
  23359. */
  23360. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23361. if (customRenderFunction) {
  23362. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23363. return;
  23364. }
  23365. var engine = this._scene.getEngine();
  23366. // Depth only
  23367. if (this._depthOnlySubMeshes.length !== 0) {
  23368. engine.setColorWrite(false);
  23369. this._renderAlphaTest(this._depthOnlySubMeshes);
  23370. engine.setColorWrite(true);
  23371. }
  23372. // Opaque
  23373. if (this._opaqueSubMeshes.length !== 0) {
  23374. this._renderOpaque(this._opaqueSubMeshes);
  23375. }
  23376. // Alpha test
  23377. if (this._alphaTestSubMeshes.length !== 0) {
  23378. this._renderAlphaTest(this._alphaTestSubMeshes);
  23379. }
  23380. var stencilState = engine.getStencilBuffer();
  23381. engine.setStencilBuffer(false);
  23382. // Sprites
  23383. if (renderSprites) {
  23384. this._renderSprites();
  23385. }
  23386. // Particles
  23387. if (renderParticles) {
  23388. this._renderParticles(activeMeshes);
  23389. }
  23390. if (this.onBeforeTransparentRendering) {
  23391. this.onBeforeTransparentRendering();
  23392. }
  23393. // Transparent
  23394. if (this._transparentSubMeshes.length !== 0) {
  23395. this._renderTransparent(this._transparentSubMeshes);
  23396. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23397. }
  23398. // Set back stencil to false in case it changes before the edge renderer.
  23399. engine.setStencilBuffer(false);
  23400. // Edges
  23401. if (this._edgesRenderers.length) {
  23402. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23403. this._edgesRenderers.data[edgesRendererIndex].render();
  23404. }
  23405. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23406. }
  23407. // Restore Stencil state.
  23408. engine.setStencilBuffer(stencilState);
  23409. };
  23410. /**
  23411. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23412. * @param subMeshes The submeshes to render
  23413. */
  23414. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23415. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23416. };
  23417. /**
  23418. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23419. * @param subMeshes The submeshes to render
  23420. */
  23421. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23422. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23423. };
  23424. /**
  23425. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23426. * @param subMeshes The submeshes to render
  23427. */
  23428. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23429. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23430. };
  23431. /**
  23432. * Renders the submeshes in a specified order.
  23433. * @param subMeshes The submeshes to sort before render
  23434. * @param sortCompareFn The comparison function use to sort
  23435. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23436. * @param transparent Specifies to activate blending if true
  23437. */
  23438. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23439. var subIndex = 0;
  23440. var subMesh;
  23441. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23442. for (; subIndex < subMeshes.length; subIndex++) {
  23443. subMesh = subMeshes.data[subIndex];
  23444. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23445. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23446. }
  23447. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23448. if (sortCompareFn) {
  23449. sortedArray.sort(sortCompareFn);
  23450. }
  23451. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23452. subMesh = sortedArray[subIndex];
  23453. if (transparent) {
  23454. var material = subMesh.getMaterial();
  23455. if (material && material.needDepthPrePass) {
  23456. var engine = material.getScene().getEngine();
  23457. engine.setColorWrite(false);
  23458. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23459. subMesh.render(false);
  23460. engine.setColorWrite(true);
  23461. }
  23462. }
  23463. subMesh.render(transparent);
  23464. }
  23465. };
  23466. /**
  23467. * Renders the submeshes in the order they were dispatched (no sort applied).
  23468. * @param subMeshes The submeshes to render
  23469. */
  23470. RenderingGroup.renderUnsorted = function (subMeshes) {
  23471. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23472. var submesh = subMeshes.data[subIndex];
  23473. submesh.render(false);
  23474. }
  23475. };
  23476. /**
  23477. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23478. * are rendered back to front if in the same alpha index.
  23479. *
  23480. * @param a The first submesh
  23481. * @param b The second submesh
  23482. * @returns The result of the comparison
  23483. */
  23484. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23485. // Alpha index first
  23486. if (a._alphaIndex > b._alphaIndex) {
  23487. return 1;
  23488. }
  23489. if (a._alphaIndex < b._alphaIndex) {
  23490. return -1;
  23491. }
  23492. // Then distance to camera
  23493. return RenderingGroup.backToFrontSortCompare(a, b);
  23494. };
  23495. /**
  23496. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23497. * are rendered back to front.
  23498. *
  23499. * @param a The first submesh
  23500. * @param b The second submesh
  23501. * @returns The result of the comparison
  23502. */
  23503. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23504. // Then distance to camera
  23505. if (a._distanceToCamera < b._distanceToCamera) {
  23506. return 1;
  23507. }
  23508. if (a._distanceToCamera > b._distanceToCamera) {
  23509. return -1;
  23510. }
  23511. return 0;
  23512. };
  23513. /**
  23514. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23515. * are rendered front to back (prevent overdraw).
  23516. *
  23517. * @param a The first submesh
  23518. * @param b The second submesh
  23519. * @returns The result of the comparison
  23520. */
  23521. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23522. // Then distance to camera
  23523. if (a._distanceToCamera < b._distanceToCamera) {
  23524. return -1;
  23525. }
  23526. if (a._distanceToCamera > b._distanceToCamera) {
  23527. return 1;
  23528. }
  23529. return 0;
  23530. };
  23531. /**
  23532. * Resets the different lists of submeshes to prepare a new frame.
  23533. */
  23534. RenderingGroup.prototype.prepare = function () {
  23535. this._opaqueSubMeshes.reset();
  23536. this._transparentSubMeshes.reset();
  23537. this._alphaTestSubMeshes.reset();
  23538. this._depthOnlySubMeshes.reset();
  23539. this._particleSystems.reset();
  23540. this._spriteManagers.reset();
  23541. this._edgesRenderers.reset();
  23542. };
  23543. RenderingGroup.prototype.dispose = function () {
  23544. this._opaqueSubMeshes.dispose();
  23545. this._transparentSubMeshes.dispose();
  23546. this._alphaTestSubMeshes.dispose();
  23547. this._depthOnlySubMeshes.dispose();
  23548. this._particleSystems.dispose();
  23549. this._spriteManagers.dispose();
  23550. this._edgesRenderers.dispose();
  23551. };
  23552. /**
  23553. * Inserts the submesh in its correct queue depending on its material.
  23554. * @param subMesh The submesh to dispatch
  23555. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23556. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23557. */
  23558. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23559. // Get mesh and materials if not provided
  23560. if (mesh === undefined) {
  23561. mesh = subMesh.getMesh();
  23562. }
  23563. if (material === undefined) {
  23564. material = subMesh.getMaterial();
  23565. }
  23566. if (material === null || material === undefined) {
  23567. return;
  23568. }
  23569. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23570. this._transparentSubMeshes.push(subMesh);
  23571. }
  23572. else if (material.needAlphaTesting()) { // Alpha test
  23573. if (material.needDepthPrePass) {
  23574. this._depthOnlySubMeshes.push(subMesh);
  23575. }
  23576. this._alphaTestSubMeshes.push(subMesh);
  23577. }
  23578. else {
  23579. if (material.needDepthPrePass) {
  23580. this._depthOnlySubMeshes.push(subMesh);
  23581. }
  23582. this._opaqueSubMeshes.push(subMesh); // Opaque
  23583. }
  23584. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23585. this._edgesRenderers.push(mesh._edgesRenderer);
  23586. }
  23587. };
  23588. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23589. this._spriteManagers.push(spriteManager);
  23590. };
  23591. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23592. this._particleSystems.push(particleSystem);
  23593. };
  23594. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23595. if (this._particleSystems.length === 0) {
  23596. return;
  23597. }
  23598. // Particles
  23599. var activeCamera = this._scene.activeCamera;
  23600. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23601. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23602. var particleSystem = this._particleSystems.data[particleIndex];
  23603. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23604. continue;
  23605. }
  23606. var emitter = particleSystem.emitter;
  23607. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23608. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23609. }
  23610. }
  23611. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23612. };
  23613. RenderingGroup.prototype._renderSprites = function () {
  23614. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23615. return;
  23616. }
  23617. // Sprites
  23618. var activeCamera = this._scene.activeCamera;
  23619. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23620. for (var id = 0; id < this._spriteManagers.length; id++) {
  23621. var spriteManager = this._spriteManagers.data[id];
  23622. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23623. spriteManager.render();
  23624. }
  23625. }
  23626. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23627. };
  23628. return RenderingGroup;
  23629. }());
  23630. BABYLON.RenderingGroup = RenderingGroup;
  23631. })(BABYLON || (BABYLON = {}));
  23632. //# sourceMappingURL=babylon.renderingGroup.js.map
  23633. var BABYLON;
  23634. (function (BABYLON) {
  23635. /**
  23636. * Groups all the scene component constants in one place to ease maintenance.
  23637. * @hidden
  23638. */
  23639. var SceneComponentConstants = /** @class */ (function () {
  23640. function SceneComponentConstants() {
  23641. }
  23642. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23643. SceneComponentConstants.NAME_LAYER = "Layer";
  23644. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23645. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23646. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23647. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23648. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23649. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23650. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23651. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23652. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23653. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23654. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23655. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23656. SceneComponentConstants.NAME_OCTREE = "Octree";
  23657. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23658. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23659. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23660. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23661. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23662. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23663. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23664. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  23665. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23666. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23667. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23668. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23669. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23670. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23671. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23672. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23673. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23674. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23675. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  23676. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  23677. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  23678. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  23679. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  23680. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  23681. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  23682. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  23683. return SceneComponentConstants;
  23684. }());
  23685. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23686. /**
  23687. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23688. * @hidden
  23689. */
  23690. var Stage = /** @class */ (function (_super) {
  23691. __extends(Stage, _super);
  23692. /**
  23693. * Hide ctor from the rest of the world.
  23694. * @param items The items to add.
  23695. */
  23696. function Stage(items) {
  23697. return _super.apply(this, items) || this;
  23698. }
  23699. /**
  23700. * Creates a new Stage.
  23701. * @returns A new instance of a Stage
  23702. */
  23703. Stage.Create = function () {
  23704. return Object.create(Stage.prototype);
  23705. };
  23706. /**
  23707. * Registers a step in an ordered way in the targeted stage.
  23708. * @param index Defines the position to register the step in
  23709. * @param component Defines the component attached to the step
  23710. * @param action Defines the action to launch during the step
  23711. */
  23712. Stage.prototype.registerStep = function (index, component, action) {
  23713. var i = 0;
  23714. var maxIndex = Number.MAX_VALUE;
  23715. for (; i < this.length && i < maxIndex; i++) {
  23716. var step = this[i];
  23717. maxIndex = step.index;
  23718. }
  23719. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23720. };
  23721. /**
  23722. * Clears all the steps from the stage.
  23723. */
  23724. Stage.prototype.clear = function () {
  23725. this.length = 0;
  23726. };
  23727. return Stage;
  23728. }(Array));
  23729. BABYLON.Stage = Stage;
  23730. })(BABYLON || (BABYLON = {}));
  23731. //# sourceMappingURL=babylon.sceneComponent.js.map
  23732. var BABYLON;
  23733. (function (BABYLON) {
  23734. /**
  23735. * Base class of the scene acting as a container for the different elements composing a scene.
  23736. * This class is dynamically extended by the different components of the scene increasing
  23737. * flexibility and reducing coupling
  23738. */
  23739. var AbstractScene = /** @class */ (function () {
  23740. function AbstractScene() {
  23741. /**
  23742. * Gets the list of root nodes (ie. nodes with no parent)
  23743. */
  23744. this.rootNodes = new Array();
  23745. /** All of the cameras added to this scene
  23746. * @see http://doc.babylonjs.com/babylon101/cameras
  23747. */
  23748. this.cameras = new Array();
  23749. /**
  23750. * All of the lights added to this scene
  23751. * @see http://doc.babylonjs.com/babylon101/lights
  23752. */
  23753. this.lights = new Array();
  23754. /**
  23755. * All of the (abstract) meshes added to this scene
  23756. */
  23757. this.meshes = new Array();
  23758. /**
  23759. * The list of skeletons added to the scene
  23760. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23761. */
  23762. this.skeletons = new Array();
  23763. /**
  23764. * All of the particle systems added to this scene
  23765. * @see http://doc.babylonjs.com/babylon101/particles
  23766. */
  23767. this.particleSystems = new Array();
  23768. /**
  23769. * Gets a list of Animations associated with the scene
  23770. */
  23771. this.animations = [];
  23772. /**
  23773. * All of the animation groups added to this scene
  23774. * @see http://doc.babylonjs.com/how_to/group
  23775. */
  23776. this.animationGroups = new Array();
  23777. /**
  23778. * All of the multi-materials added to this scene
  23779. * @see http://doc.babylonjs.com/how_to/multi_materials
  23780. */
  23781. this.multiMaterials = new Array();
  23782. /**
  23783. * All of the materials added to this scene
  23784. * @see http://doc.babylonjs.com/babylon101/materials
  23785. */
  23786. this.materials = new Array();
  23787. /**
  23788. * The list of morph target managers added to the scene
  23789. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23790. */
  23791. this.morphTargetManagers = new Array();
  23792. /**
  23793. * The list of geometries used in the scene.
  23794. */
  23795. this.geometries = new Array();
  23796. /**
  23797. * All of the tranform nodes added to this scene
  23798. * @see http://doc.babylonjs.com/how_to/transformnode
  23799. */
  23800. this.transformNodes = new Array();
  23801. /**
  23802. * ActionManagers available on the scene.
  23803. */
  23804. this.actionManagers = new Array();
  23805. /**
  23806. * Sounds to keep.
  23807. */
  23808. this.sounds = new Array();
  23809. /**
  23810. * Textures to keep.
  23811. */
  23812. this.textures = new Array();
  23813. }
  23814. /**
  23815. * Adds a parser in the list of available ones
  23816. * @param name Defines the name of the parser
  23817. * @param parser Defines the parser to add
  23818. */
  23819. AbstractScene.AddParser = function (name, parser) {
  23820. this._BabylonFileParsers[name] = parser;
  23821. };
  23822. /**
  23823. * Gets a general parser from the list of avaialble ones
  23824. * @param name Defines the name of the parser
  23825. * @returns the requested parser or null
  23826. */
  23827. AbstractScene.GetParser = function (name) {
  23828. if (this._BabylonFileParsers[name]) {
  23829. return this._BabylonFileParsers[name];
  23830. }
  23831. return null;
  23832. };
  23833. /**
  23834. * Adds n individual parser in the list of available ones
  23835. * @param name Defines the name of the parser
  23836. * @param parser Defines the parser to add
  23837. */
  23838. AbstractScene.AddIndividualParser = function (name, parser) {
  23839. this._IndividualBabylonFileParsers[name] = parser;
  23840. };
  23841. /**
  23842. * Gets an individual parser from the list of avaialble ones
  23843. * @param name Defines the name of the parser
  23844. * @returns the requested parser or null
  23845. */
  23846. AbstractScene.GetIndividualParser = function (name) {
  23847. if (this._IndividualBabylonFileParsers[name]) {
  23848. return this._IndividualBabylonFileParsers[name];
  23849. }
  23850. return null;
  23851. };
  23852. /**
  23853. * Parser json data and populate both a scene and its associated container object
  23854. * @param jsonData Defines the data to parse
  23855. * @param scene Defines the scene to parse the data for
  23856. * @param container Defines the container attached to the parsing sequence
  23857. * @param rootUrl Defines the root url of the data
  23858. */
  23859. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23860. for (var parserName in this._BabylonFileParsers) {
  23861. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23862. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23863. }
  23864. }
  23865. };
  23866. /**
  23867. * Stores the list of available parsers in the application.
  23868. */
  23869. AbstractScene._BabylonFileParsers = {};
  23870. /**
  23871. * Stores the list of available individual parsers in the application.
  23872. */
  23873. AbstractScene._IndividualBabylonFileParsers = {};
  23874. return AbstractScene;
  23875. }());
  23876. BABYLON.AbstractScene = AbstractScene;
  23877. })(BABYLON || (BABYLON = {}));
  23878. //# sourceMappingURL=babylon.abstractScene.js.map
  23879. var BABYLON;
  23880. (function (BABYLON) {
  23881. /** @hidden */
  23882. var ClickInfo = /** @class */ (function () {
  23883. function ClickInfo() {
  23884. this._singleClick = false;
  23885. this._doubleClick = false;
  23886. this._hasSwiped = false;
  23887. this._ignore = false;
  23888. }
  23889. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23890. get: function () {
  23891. return this._singleClick;
  23892. },
  23893. set: function (b) {
  23894. this._singleClick = b;
  23895. },
  23896. enumerable: true,
  23897. configurable: true
  23898. });
  23899. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23900. get: function () {
  23901. return this._doubleClick;
  23902. },
  23903. set: function (b) {
  23904. this._doubleClick = b;
  23905. },
  23906. enumerable: true,
  23907. configurable: true
  23908. });
  23909. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23910. get: function () {
  23911. return this._hasSwiped;
  23912. },
  23913. set: function (b) {
  23914. this._hasSwiped = b;
  23915. },
  23916. enumerable: true,
  23917. configurable: true
  23918. });
  23919. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23920. get: function () {
  23921. return this._ignore;
  23922. },
  23923. set: function (b) {
  23924. this._ignore = b;
  23925. },
  23926. enumerable: true,
  23927. configurable: true
  23928. });
  23929. return ClickInfo;
  23930. }());
  23931. /**
  23932. * This class is used by the onRenderingGroupObservable
  23933. */
  23934. var RenderingGroupInfo = /** @class */ (function () {
  23935. function RenderingGroupInfo() {
  23936. }
  23937. return RenderingGroupInfo;
  23938. }());
  23939. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23940. /**
  23941. * Represents a scene to be rendered by the engine.
  23942. * @see http://doc.babylonjs.com/features/scene
  23943. */
  23944. var Scene = /** @class */ (function (_super) {
  23945. __extends(Scene, _super);
  23946. /**
  23947. * Creates a new Scene
  23948. * @param engine defines the engine to use to render this scene
  23949. */
  23950. function Scene(engine) {
  23951. var _this = _super.call(this) || this;
  23952. // Members
  23953. /**
  23954. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23955. */
  23956. _this.autoClear = true;
  23957. /**
  23958. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23959. */
  23960. _this.autoClearDepthAndStencil = true;
  23961. /**
  23962. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23963. */
  23964. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23965. /**
  23966. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23967. */
  23968. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23969. _this._forceWireframe = false;
  23970. _this._forcePointsCloud = false;
  23971. /**
  23972. * Gets or sets a boolean indicating if animations are enabled
  23973. */
  23974. _this.animationsEnabled = true;
  23975. _this._animationPropertiesOverride = null;
  23976. /**
  23977. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23978. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23979. */
  23980. _this.useConstantAnimationDeltaTime = false;
  23981. /**
  23982. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23983. * Please note that it requires to run a ray cast through the scene on every frame
  23984. */
  23985. _this.constantlyUpdateMeshUnderPointer = false;
  23986. /**
  23987. * Defines the HTML cursor to use when hovering over interactive elements
  23988. */
  23989. _this.hoverCursor = "pointer";
  23990. /**
  23991. * Defines the HTML default cursor to use (empty by default)
  23992. */
  23993. _this.defaultCursor = "";
  23994. /**
  23995. * This is used to call preventDefault() on pointer down
  23996. * in order to block unwanted artifacts like system double clicks
  23997. */
  23998. _this.preventDefaultOnPointerDown = true;
  23999. // Metadata
  24000. /**
  24001. * Gets or sets user defined metadata
  24002. */
  24003. _this.metadata = null;
  24004. /**
  24005. * Use this array to add regular expressions used to disable offline support for specific urls
  24006. */
  24007. _this.disableOfflineSupportExceptionRules = new Array();
  24008. /**
  24009. * An event triggered when the scene is disposed.
  24010. */
  24011. _this.onDisposeObservable = new BABYLON.Observable();
  24012. _this._onDisposeObserver = null;
  24013. /**
  24014. * An event triggered before rendering the scene (right after animations and physics)
  24015. */
  24016. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24017. _this._onBeforeRenderObserver = null;
  24018. /**
  24019. * An event triggered after rendering the scene
  24020. */
  24021. _this.onAfterRenderObservable = new BABYLON.Observable();
  24022. _this._onAfterRenderObserver = null;
  24023. /**
  24024. * An event triggered before animating the scene
  24025. */
  24026. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24027. /**
  24028. * An event triggered after animations processing
  24029. */
  24030. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24031. /**
  24032. * An event triggered before draw calls are ready to be sent
  24033. */
  24034. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24035. /**
  24036. * An event triggered after draw calls have been sent
  24037. */
  24038. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24039. /**
  24040. * An event triggered when physic simulation is about to be run
  24041. */
  24042. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  24043. /**
  24044. * An event triggered when physic simulation has been done
  24045. */
  24046. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24047. /**
  24048. * An event triggered when the scene is ready
  24049. */
  24050. _this.onReadyObservable = new BABYLON.Observable();
  24051. /**
  24052. * An event triggered before rendering a camera
  24053. */
  24054. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24055. _this._onBeforeCameraRenderObserver = null;
  24056. /**
  24057. * An event triggered after rendering a camera
  24058. */
  24059. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24060. _this._onAfterCameraRenderObserver = null;
  24061. /**
  24062. * An event triggered when active meshes evaluation is about to start
  24063. */
  24064. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24065. /**
  24066. * An event triggered when active meshes evaluation is done
  24067. */
  24068. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24069. /**
  24070. * An event triggered when particles rendering is about to start
  24071. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24072. */
  24073. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24074. /**
  24075. * An event triggered when particles rendering is done
  24076. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24077. */
  24078. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24079. /**
  24080. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24081. */
  24082. _this.onDataLoadedObservable = new BABYLON.Observable();
  24083. /**
  24084. * An event triggered when a camera is created
  24085. */
  24086. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24087. /**
  24088. * An event triggered when a camera is removed
  24089. */
  24090. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24091. /**
  24092. * An event triggered when a light is created
  24093. */
  24094. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24095. /**
  24096. * An event triggered when a light is removed
  24097. */
  24098. _this.onLightRemovedObservable = new BABYLON.Observable();
  24099. /**
  24100. * An event triggered when a geometry is created
  24101. */
  24102. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24103. /**
  24104. * An event triggered when a geometry is removed
  24105. */
  24106. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24107. /**
  24108. * An event triggered when a transform node is created
  24109. */
  24110. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24111. /**
  24112. * An event triggered when a transform node is removed
  24113. */
  24114. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24115. /**
  24116. * An event triggered when a mesh is created
  24117. */
  24118. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24119. /**
  24120. * An event triggered when a mesh is removed
  24121. */
  24122. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24123. /**
  24124. * An event triggered when render targets are about to be rendered
  24125. * Can happen multiple times per frame.
  24126. */
  24127. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24128. /**
  24129. * An event triggered when render targets were rendered.
  24130. * Can happen multiple times per frame.
  24131. */
  24132. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24133. /**
  24134. * An event triggered before calculating deterministic simulation step
  24135. */
  24136. _this.onBeforeStepObservable = new BABYLON.Observable();
  24137. /**
  24138. * An event triggered after calculating deterministic simulation step
  24139. */
  24140. _this.onAfterStepObservable = new BABYLON.Observable();
  24141. /**
  24142. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24143. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24144. * 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)
  24145. */
  24146. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24147. /**
  24148. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24149. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24150. * 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)
  24151. */
  24152. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24153. /**
  24154. * This Observable will when a mesh has been imported into the scene.
  24155. */
  24156. _this.onMeshImportedObservable = new BABYLON.Observable();
  24157. // Animations
  24158. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24159. /**
  24160. * 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).
  24161. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24162. */
  24163. _this.onPrePointerObservable = new BABYLON.Observable();
  24164. /**
  24165. * Observable event triggered each time an input event is received from the rendering canvas
  24166. */
  24167. _this.onPointerObservable = new BABYLON.Observable();
  24168. _this._meshPickProceed = false;
  24169. _this._currentPickResult = null;
  24170. _this._previousPickResult = null;
  24171. _this._totalPointersPressed = 0;
  24172. _this._doubleClickOccured = false;
  24173. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24174. _this.cameraToUseForPointers = null;
  24175. _this._pointerX = 0;
  24176. _this._pointerY = 0;
  24177. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24178. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24179. _this._startingPointerTime = 0;
  24180. _this._previousStartingPointerTime = 0;
  24181. _this._pointerCaptures = {};
  24182. // Deterministic lockstep
  24183. _this._timeAccumulator = 0;
  24184. _this._currentStepId = 0;
  24185. _this._currentInternalStep = 0;
  24186. // Keyboard
  24187. /**
  24188. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24189. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24190. */
  24191. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24192. /**
  24193. * Observable event triggered each time an keyboard event is received from the hosting window
  24194. */
  24195. _this.onKeyboardObservable = new BABYLON.Observable();
  24196. // Coordinates system
  24197. _this._useRightHandedSystem = false;
  24198. // Fog
  24199. _this._fogEnabled = true;
  24200. _this._fogMode = Scene.FOGMODE_NONE;
  24201. /**
  24202. * Gets or sets the fog color to use
  24203. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24204. */
  24205. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24206. /**
  24207. * Gets or sets the fog density to use
  24208. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24209. */
  24210. _this.fogDensity = 0.1;
  24211. /**
  24212. * Gets or sets the fog start distance to use
  24213. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24214. */
  24215. _this.fogStart = 0;
  24216. /**
  24217. * Gets or sets the fog end distance to use
  24218. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24219. */
  24220. _this.fogEnd = 1000.0;
  24221. // Lights
  24222. _this._shadowsEnabled = true;
  24223. _this._lightsEnabled = true;
  24224. /** All of the active cameras added to this scene. */
  24225. _this.activeCameras = new Array();
  24226. // Textures
  24227. _this._texturesEnabled = true;
  24228. // Particles
  24229. /**
  24230. * Gets or sets a boolean indicating if particles are enabled on this scene
  24231. */
  24232. _this.particlesEnabled = true;
  24233. // Sprites
  24234. /**
  24235. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24236. */
  24237. _this.spritesEnabled = true;
  24238. // Skeletons
  24239. _this._skeletonsEnabled = true;
  24240. // Lens flares
  24241. /**
  24242. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24243. */
  24244. _this.lensFlaresEnabled = true;
  24245. // Collisions
  24246. /**
  24247. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24248. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24249. */
  24250. _this.collisionsEnabled = true;
  24251. /**
  24252. * Defines the gravity applied to this scene (used only for collisions)
  24253. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24254. */
  24255. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24256. // Postprocesses
  24257. /**
  24258. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24259. */
  24260. _this.postProcessesEnabled = true;
  24261. /**
  24262. * The list of postprocesses added to the scene
  24263. */
  24264. _this.postProcesses = new Array();
  24265. // Customs render targets
  24266. /**
  24267. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24268. */
  24269. _this.renderTargetsEnabled = true;
  24270. /**
  24271. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24272. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24273. */
  24274. _this.dumpNextRenderTargets = false;
  24275. /**
  24276. * The list of user defined render targets added to the scene
  24277. */
  24278. _this.customRenderTargets = new Array();
  24279. /**
  24280. * Gets the list of meshes imported to the scene through SceneLoader
  24281. */
  24282. _this.importedMeshesFiles = new Array();
  24283. // Probes
  24284. /**
  24285. * Gets or sets a boolean indicating if probes are enabled on this scene
  24286. */
  24287. _this.probesEnabled = true;
  24288. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24289. // Procedural textures
  24290. /**
  24291. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24292. */
  24293. _this.proceduralTexturesEnabled = true;
  24294. /**
  24295. * The list of sound tracks added to the scene
  24296. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24297. */
  24298. _this.soundTracks = new Array();
  24299. _this._audioEnabled = true;
  24300. _this._headphone = false;
  24301. // Performance counters
  24302. _this._totalVertices = new BABYLON.PerfCounter();
  24303. /** @hidden */
  24304. _this._activeIndices = new BABYLON.PerfCounter();
  24305. /** @hidden */
  24306. _this._activeParticles = new BABYLON.PerfCounter();
  24307. /** @hidden */
  24308. _this._activeBones = new BABYLON.PerfCounter();
  24309. _this._animationTime = 0;
  24310. /**
  24311. * Gets or sets a general scale for animation speed
  24312. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24313. */
  24314. _this.animationTimeScale = 1;
  24315. _this._renderId = 0;
  24316. _this._frameId = 0;
  24317. _this._executeWhenReadyTimeoutId = -1;
  24318. _this._intermediateRendering = false;
  24319. _this._viewUpdateFlag = -1;
  24320. _this._projectionUpdateFlag = -1;
  24321. _this._alternateViewUpdateFlag = -1;
  24322. _this._alternateProjectionUpdateFlag = -1;
  24323. /** @hidden */
  24324. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24325. _this._activeRequests = new Array();
  24326. _this._pendingData = new Array();
  24327. _this._isDisposed = false;
  24328. /**
  24329. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24330. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24331. */
  24332. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24333. _this._activeMeshes = new BABYLON.SmartArray(256);
  24334. _this._processedMaterials = new BABYLON.SmartArray(256);
  24335. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24336. /** @hidden */
  24337. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24338. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24339. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24340. /** @hidden */
  24341. _this._activeAnimatables = new Array();
  24342. _this._transformMatrix = BABYLON.Matrix.Zero();
  24343. _this._useAlternateCameraConfiguration = false;
  24344. _this._alternateRendering = false;
  24345. /**
  24346. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24347. * This is useful if there are more lights that the maximum simulteanous authorized
  24348. */
  24349. _this.requireLightSorting = false;
  24350. /**
  24351. * @hidden
  24352. * Backing store of defined scene components.
  24353. */
  24354. _this._components = [];
  24355. /**
  24356. * @hidden
  24357. * Backing store of defined scene components.
  24358. */
  24359. _this._serializableComponents = [];
  24360. /**
  24361. * List of components to register on the next registration step.
  24362. */
  24363. _this._transientComponents = [];
  24364. /**
  24365. * @hidden
  24366. * Defines the actions happening before camera updates.
  24367. */
  24368. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24369. /**
  24370. * @hidden
  24371. * Defines the actions happening before clear the canvas.
  24372. */
  24373. _this._beforeClearStage = BABYLON.Stage.Create();
  24374. /**
  24375. * @hidden
  24376. * Defines the actions when collecting render targets for the frame.
  24377. */
  24378. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24379. /**
  24380. * @hidden
  24381. * Defines the actions happening for one camera in the frame.
  24382. */
  24383. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24384. /**
  24385. * @hidden
  24386. * Defines the actions happening during the per mesh ready checks.
  24387. */
  24388. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24389. /**
  24390. * @hidden
  24391. * Defines the actions happening before evaluate active mesh checks.
  24392. */
  24393. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24394. /**
  24395. * @hidden
  24396. * Defines the actions happening during the evaluate sub mesh checks.
  24397. */
  24398. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24399. /**
  24400. * @hidden
  24401. * Defines the actions happening during the active mesh stage.
  24402. */
  24403. _this._activeMeshStage = BABYLON.Stage.Create();
  24404. /**
  24405. * @hidden
  24406. * Defines the actions happening during the per camera render target step.
  24407. */
  24408. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24409. /**
  24410. * @hidden
  24411. * Defines the actions happening just before the active camera is drawing.
  24412. */
  24413. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24414. /**
  24415. * @hidden
  24416. * Defines the actions happening just before a rendering group is drawing.
  24417. */
  24418. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24419. /**
  24420. * @hidden
  24421. * Defines the actions happening just before a mesh is drawing.
  24422. */
  24423. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24424. /**
  24425. * @hidden
  24426. * Defines the actions happening just after a mesh has been drawn.
  24427. */
  24428. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24429. /**
  24430. * @hidden
  24431. * Defines the actions happening just after a rendering group has been drawn.
  24432. */
  24433. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24434. /**
  24435. * @hidden
  24436. * Defines the actions happening just after the active camera has been drawn.
  24437. */
  24438. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24439. /**
  24440. * @hidden
  24441. * Defines the actions happening when a pointer move event happens.
  24442. */
  24443. _this._pointerMoveStage = BABYLON.Stage.Create();
  24444. /**
  24445. * @hidden
  24446. * Defines the actions happening when a pointer down event happens.
  24447. */
  24448. _this._pointerDownStage = BABYLON.Stage.Create();
  24449. /**
  24450. * @hidden
  24451. * Defines the actions happening when a pointer up event happens.
  24452. */
  24453. _this._pointerUpStage = BABYLON.Stage.Create();
  24454. _this._defaultMeshCandidates = {
  24455. data: [],
  24456. length: 0
  24457. };
  24458. _this._defaultSubMeshCandidates = {
  24459. data: [],
  24460. length: 0
  24461. };
  24462. _this._activeMeshesFrozen = false;
  24463. /** @hidden */
  24464. _this._allowPostProcessClearColor = true;
  24465. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24466. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24467. _this.blockMaterialDirtyMechanism = false;
  24468. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24469. _this._engine.scenes.push(_this);
  24470. _this._uid = null;
  24471. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24472. if (BABYLON.PostProcessManager) {
  24473. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24474. }
  24475. if (BABYLON.Tools.IsWindowObjectExist()) {
  24476. _this.attachControl();
  24477. }
  24478. //collision coordinator initialization. For now legacy per default.
  24479. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24480. // Uniform Buffer
  24481. _this._createUbo();
  24482. // Default Image processing definition
  24483. if (BABYLON.ImageProcessingConfiguration) {
  24484. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24485. }
  24486. _this.setDefaultCandidateProviders();
  24487. return _this;
  24488. }
  24489. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24490. /**
  24491. * Texture used in all pbr material as the reflection texture.
  24492. * As in the majority of the scene they are the same (exception for multi room and so on),
  24493. * this is easier to reference from here than from all the materials.
  24494. */
  24495. get: function () {
  24496. return this._environmentTexture;
  24497. },
  24498. /**
  24499. * Texture used in all pbr material as the reflection texture.
  24500. * As in the majority of the scene they are the same (exception for multi room and so on),
  24501. * this is easier to set here than in all the materials.
  24502. */
  24503. set: function (value) {
  24504. if (this._environmentTexture === value) {
  24505. return;
  24506. }
  24507. this._environmentTexture = value;
  24508. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24509. },
  24510. enumerable: true,
  24511. configurable: true
  24512. });
  24513. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24514. /**
  24515. * Default image processing configuration used either in the rendering
  24516. * Forward main pass or through the imageProcessingPostProcess if present.
  24517. * As in the majority of the scene they are the same (exception for multi camera),
  24518. * this is easier to reference from here than from all the materials and post process.
  24519. *
  24520. * No setter as we it is a shared configuration, you can set the values instead.
  24521. */
  24522. get: function () {
  24523. return this._imageProcessingConfiguration;
  24524. },
  24525. enumerable: true,
  24526. configurable: true
  24527. });
  24528. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24529. get: function () {
  24530. return this._forceWireframe;
  24531. },
  24532. /**
  24533. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24534. */
  24535. set: function (value) {
  24536. if (this._forceWireframe === value) {
  24537. return;
  24538. }
  24539. this._forceWireframe = value;
  24540. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24541. },
  24542. enumerable: true,
  24543. configurable: true
  24544. });
  24545. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24546. get: function () {
  24547. return this._forcePointsCloud;
  24548. },
  24549. /**
  24550. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24551. */
  24552. set: function (value) {
  24553. if (this._forcePointsCloud === value) {
  24554. return;
  24555. }
  24556. this._forcePointsCloud = value;
  24557. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24558. },
  24559. enumerable: true,
  24560. configurable: true
  24561. });
  24562. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24563. /**
  24564. * Gets or sets the animation properties override
  24565. */
  24566. get: function () {
  24567. return this._animationPropertiesOverride;
  24568. },
  24569. set: function (value) {
  24570. this._animationPropertiesOverride = value;
  24571. },
  24572. enumerable: true,
  24573. configurable: true
  24574. });
  24575. Object.defineProperty(Scene.prototype, "onDispose", {
  24576. /** Sets a function to be executed when this scene is disposed. */
  24577. set: function (callback) {
  24578. if (this._onDisposeObserver) {
  24579. this.onDisposeObservable.remove(this._onDisposeObserver);
  24580. }
  24581. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24582. },
  24583. enumerable: true,
  24584. configurable: true
  24585. });
  24586. Object.defineProperty(Scene.prototype, "beforeRender", {
  24587. /** Sets a function to be executed before rendering this scene */
  24588. set: function (callback) {
  24589. if (this._onBeforeRenderObserver) {
  24590. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24591. }
  24592. if (callback) {
  24593. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24594. }
  24595. },
  24596. enumerable: true,
  24597. configurable: true
  24598. });
  24599. Object.defineProperty(Scene.prototype, "afterRender", {
  24600. /** Sets a function to be executed after rendering this scene */
  24601. set: function (callback) {
  24602. if (this._onAfterRenderObserver) {
  24603. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24604. }
  24605. if (callback) {
  24606. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24607. }
  24608. },
  24609. enumerable: true,
  24610. configurable: true
  24611. });
  24612. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24613. /** Sets a function to be executed before rendering a camera*/
  24614. set: function (callback) {
  24615. if (this._onBeforeCameraRenderObserver) {
  24616. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24617. }
  24618. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24619. },
  24620. enumerable: true,
  24621. configurable: true
  24622. });
  24623. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24624. /** Sets a function to be executed after rendering a camera*/
  24625. set: function (callback) {
  24626. if (this._onAfterCameraRenderObserver) {
  24627. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24628. }
  24629. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24630. },
  24631. enumerable: true,
  24632. configurable: true
  24633. });
  24634. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24635. /**
  24636. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24637. */
  24638. get: function () {
  24639. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24640. },
  24641. enumerable: true,
  24642. configurable: true
  24643. });
  24644. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24645. get: function () {
  24646. return this._useRightHandedSystem;
  24647. },
  24648. /**
  24649. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24650. */
  24651. set: function (value) {
  24652. if (this._useRightHandedSystem === value) {
  24653. return;
  24654. }
  24655. this._useRightHandedSystem = value;
  24656. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24657. },
  24658. enumerable: true,
  24659. configurable: true
  24660. });
  24661. /**
  24662. * Sets the step Id used by deterministic lock step
  24663. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24664. * @param newStepId defines the step Id
  24665. */
  24666. Scene.prototype.setStepId = function (newStepId) {
  24667. this._currentStepId = newStepId;
  24668. };
  24669. ;
  24670. /**
  24671. * Gets the step Id used by deterministic lock step
  24672. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24673. * @returns the step Id
  24674. */
  24675. Scene.prototype.getStepId = function () {
  24676. return this._currentStepId;
  24677. };
  24678. ;
  24679. /**
  24680. * Gets the internal step used by deterministic lock step
  24681. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24682. * @returns the internal step
  24683. */
  24684. Scene.prototype.getInternalStep = function () {
  24685. return this._currentInternalStep;
  24686. };
  24687. ;
  24688. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24689. get: function () {
  24690. return this._fogEnabled;
  24691. },
  24692. /**
  24693. * Gets or sets a boolean indicating if fog is enabled on this scene
  24694. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24695. */
  24696. set: function (value) {
  24697. if (this._fogEnabled === value) {
  24698. return;
  24699. }
  24700. this._fogEnabled = value;
  24701. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24702. },
  24703. enumerable: true,
  24704. configurable: true
  24705. });
  24706. Object.defineProperty(Scene.prototype, "fogMode", {
  24707. get: function () {
  24708. return this._fogMode;
  24709. },
  24710. /**
  24711. * Gets or sets the fog mode to use
  24712. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24713. */
  24714. set: function (value) {
  24715. if (this._fogMode === value) {
  24716. return;
  24717. }
  24718. this._fogMode = value;
  24719. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24720. },
  24721. enumerable: true,
  24722. configurable: true
  24723. });
  24724. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24725. get: function () {
  24726. return this._shadowsEnabled;
  24727. },
  24728. /**
  24729. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24730. */
  24731. set: function (value) {
  24732. if (this._shadowsEnabled === value) {
  24733. return;
  24734. }
  24735. this._shadowsEnabled = value;
  24736. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24737. },
  24738. enumerable: true,
  24739. configurable: true
  24740. });
  24741. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24742. get: function () {
  24743. return this._lightsEnabled;
  24744. },
  24745. /**
  24746. * Gets or sets a boolean indicating if lights are enabled on this scene
  24747. */
  24748. set: function (value) {
  24749. if (this._lightsEnabled === value) {
  24750. return;
  24751. }
  24752. this._lightsEnabled = value;
  24753. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24754. },
  24755. enumerable: true,
  24756. configurable: true
  24757. });
  24758. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24759. /** The default material used on meshes when no material is affected */
  24760. get: function () {
  24761. if (!this._defaultMaterial) {
  24762. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24763. }
  24764. return this._defaultMaterial;
  24765. },
  24766. /** The default material used on meshes when no material is affected */
  24767. set: function (value) {
  24768. this._defaultMaterial = value;
  24769. },
  24770. enumerable: true,
  24771. configurable: true
  24772. });
  24773. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24774. get: function () {
  24775. return this._texturesEnabled;
  24776. },
  24777. /**
  24778. * Gets or sets a boolean indicating if textures are enabled on this scene
  24779. */
  24780. set: function (value) {
  24781. if (this._texturesEnabled === value) {
  24782. return;
  24783. }
  24784. this._texturesEnabled = value;
  24785. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24786. },
  24787. enumerable: true,
  24788. configurable: true
  24789. });
  24790. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24791. get: function () {
  24792. return this._skeletonsEnabled;
  24793. },
  24794. /**
  24795. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24796. */
  24797. set: function (value) {
  24798. if (this._skeletonsEnabled === value) {
  24799. return;
  24800. }
  24801. this._skeletonsEnabled = value;
  24802. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24803. },
  24804. enumerable: true,
  24805. configurable: true
  24806. });
  24807. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24808. /**
  24809. * Gets the main soundtrack associated with the scene
  24810. */
  24811. get: function () {
  24812. if (!this._mainSoundTrack) {
  24813. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24814. }
  24815. return this._mainSoundTrack;
  24816. },
  24817. enumerable: true,
  24818. configurable: true
  24819. });
  24820. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24821. /** @hidden */
  24822. get: function () {
  24823. return this._alternateRendering;
  24824. },
  24825. enumerable: true,
  24826. configurable: true
  24827. });
  24828. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24829. /**
  24830. * Gets the list of frustum planes (built from the active camera)
  24831. */
  24832. get: function () {
  24833. return this._frustumPlanes;
  24834. },
  24835. enumerable: true,
  24836. configurable: true
  24837. });
  24838. /**
  24839. * Registers the transient components if needed.
  24840. */
  24841. Scene.prototype._registerTransientComponents = function () {
  24842. // Register components that have been associated lately to the scene.
  24843. if (this._transientComponents.length > 0) {
  24844. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24845. var component = _a[_i];
  24846. component.register();
  24847. }
  24848. this._transientComponents = [];
  24849. }
  24850. };
  24851. /**
  24852. * @hidden
  24853. * Add a component to the scene.
  24854. * Note that the ccomponent could be registered on th next frame if this is called after
  24855. * the register component stage.
  24856. * @param component Defines the component to add to the scene
  24857. */
  24858. Scene.prototype._addComponent = function (component) {
  24859. this._components.push(component);
  24860. this._transientComponents.push(component);
  24861. var serializableComponent = component;
  24862. if (serializableComponent.addFromContainer) {
  24863. this._serializableComponents.push(serializableComponent);
  24864. }
  24865. };
  24866. /**
  24867. * @hidden
  24868. * Gets a component from the scene.
  24869. * @param name defines the name of the component to retrieve
  24870. * @returns the component or null if not present
  24871. */
  24872. Scene.prototype._getComponent = function (name) {
  24873. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24874. var component = _a[_i];
  24875. if (component.name === name) {
  24876. return component;
  24877. }
  24878. }
  24879. return null;
  24880. };
  24881. /**
  24882. * @hidden
  24883. */
  24884. Scene.prototype._getDefaultMeshCandidates = function () {
  24885. this._defaultMeshCandidates.data = this.meshes;
  24886. this._defaultMeshCandidates.length = this.meshes.length;
  24887. return this._defaultMeshCandidates;
  24888. };
  24889. /**
  24890. * @hidden
  24891. */
  24892. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  24893. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  24894. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  24895. return this._defaultSubMeshCandidates;
  24896. };
  24897. /**
  24898. * Sets the default candidate providers for the scene.
  24899. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  24900. * and getCollidingSubMeshCandidates to their default function
  24901. */
  24902. Scene.prototype.setDefaultCandidateProviders = function () {
  24903. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  24904. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24905. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24906. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24907. };
  24908. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24909. /**
  24910. * Gets a boolean indicating if collisions are processed on a web worker
  24911. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24912. */
  24913. get: function () {
  24914. return this._workerCollisions;
  24915. },
  24916. set: function (enabled) {
  24917. if (!BABYLON.CollisionCoordinatorLegacy) {
  24918. return;
  24919. }
  24920. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24921. this._workerCollisions = enabled;
  24922. if (this.collisionCoordinator) {
  24923. this.collisionCoordinator.destroy();
  24924. }
  24925. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24926. this.collisionCoordinator.init(this);
  24927. },
  24928. enumerable: true,
  24929. configurable: true
  24930. });
  24931. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24932. /**
  24933. * Gets the mesh that is currently under the pointer
  24934. */
  24935. get: function () {
  24936. return this._pointerOverMesh;
  24937. },
  24938. enumerable: true,
  24939. configurable: true
  24940. });
  24941. Object.defineProperty(Scene.prototype, "pointerX", {
  24942. /**
  24943. * Gets the current on-screen X position of the pointer
  24944. */
  24945. get: function () {
  24946. return this._pointerX;
  24947. },
  24948. enumerable: true,
  24949. configurable: true
  24950. });
  24951. Object.defineProperty(Scene.prototype, "pointerY", {
  24952. /**
  24953. * Gets the current on-screen Y position of the pointer
  24954. */
  24955. get: function () {
  24956. return this._pointerY;
  24957. },
  24958. enumerable: true,
  24959. configurable: true
  24960. });
  24961. /**
  24962. * Gets the cached material (ie. the latest rendered one)
  24963. * @returns the cached material
  24964. */
  24965. Scene.prototype.getCachedMaterial = function () {
  24966. return this._cachedMaterial;
  24967. };
  24968. /**
  24969. * Gets the cached effect (ie. the latest rendered one)
  24970. * @returns the cached effect
  24971. */
  24972. Scene.prototype.getCachedEffect = function () {
  24973. return this._cachedEffect;
  24974. };
  24975. /**
  24976. * Gets the cached visibility state (ie. the latest rendered one)
  24977. * @returns the cached visibility state
  24978. */
  24979. Scene.prototype.getCachedVisibility = function () {
  24980. return this._cachedVisibility;
  24981. };
  24982. /**
  24983. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24984. * @param material defines the current material
  24985. * @param effect defines the current effect
  24986. * @param visibility defines the current visibility state
  24987. * @returns true if one parameter is not cached
  24988. */
  24989. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24990. if (visibility === void 0) { visibility = 1; }
  24991. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24992. };
  24993. /**
  24994. * Gets the engine associated with the scene
  24995. * @returns an Engine
  24996. */
  24997. Scene.prototype.getEngine = function () {
  24998. return this._engine;
  24999. };
  25000. /**
  25001. * Gets the total number of vertices rendered per frame
  25002. * @returns the total number of vertices rendered per frame
  25003. */
  25004. Scene.prototype.getTotalVertices = function () {
  25005. return this._totalVertices.current;
  25006. };
  25007. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25008. /**
  25009. * Gets the performance counter for total vertices
  25010. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25011. */
  25012. get: function () {
  25013. return this._totalVertices;
  25014. },
  25015. enumerable: true,
  25016. configurable: true
  25017. });
  25018. /**
  25019. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25020. * @returns the total number of active indices rendered per frame
  25021. */
  25022. Scene.prototype.getActiveIndices = function () {
  25023. return this._activeIndices.current;
  25024. };
  25025. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25026. /**
  25027. * Gets the performance counter for active indices
  25028. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25029. */
  25030. get: function () {
  25031. return this._activeIndices;
  25032. },
  25033. enumerable: true,
  25034. configurable: true
  25035. });
  25036. /**
  25037. * Gets the total number of active particles rendered per frame
  25038. * @returns the total number of active particles rendered per frame
  25039. */
  25040. Scene.prototype.getActiveParticles = function () {
  25041. return this._activeParticles.current;
  25042. };
  25043. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25044. /**
  25045. * Gets the performance counter for active particles
  25046. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25047. */
  25048. get: function () {
  25049. return this._activeParticles;
  25050. },
  25051. enumerable: true,
  25052. configurable: true
  25053. });
  25054. /**
  25055. * Gets the total number of active bones rendered per frame
  25056. * @returns the total number of active bones rendered per frame
  25057. */
  25058. Scene.prototype.getActiveBones = function () {
  25059. return this._activeBones.current;
  25060. };
  25061. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25062. /**
  25063. * Gets the performance counter for active bones
  25064. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25065. */
  25066. get: function () {
  25067. return this._activeBones;
  25068. },
  25069. enumerable: true,
  25070. configurable: true
  25071. });
  25072. /** @hidden */
  25073. Scene.prototype.getInterFramePerfCounter = function () {
  25074. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25075. return 0;
  25076. };
  25077. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25078. /** @hidden */
  25079. get: function () {
  25080. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25081. return null;
  25082. },
  25083. enumerable: true,
  25084. configurable: true
  25085. });
  25086. /** @hidden */
  25087. Scene.prototype.getLastFrameDuration = function () {
  25088. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25089. return 0;
  25090. };
  25091. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25092. /** @hidden */
  25093. get: function () {
  25094. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25095. return null;
  25096. },
  25097. enumerable: true,
  25098. configurable: true
  25099. });
  25100. /** @hidden */
  25101. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25102. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25103. return 0;
  25104. };
  25105. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25106. /** @hidden */
  25107. get: function () {
  25108. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25109. return null;
  25110. },
  25111. enumerable: true,
  25112. configurable: true
  25113. });
  25114. /**
  25115. * Gets the array of active meshes
  25116. * @returns an array of AbstractMesh
  25117. */
  25118. Scene.prototype.getActiveMeshes = function () {
  25119. return this._activeMeshes;
  25120. };
  25121. /** @hidden */
  25122. Scene.prototype.getRenderTargetsDuration = function () {
  25123. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25124. return 0;
  25125. };
  25126. /** @hidden */
  25127. Scene.prototype.getRenderDuration = function () {
  25128. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25129. return 0;
  25130. };
  25131. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25132. /** @hidden */
  25133. get: function () {
  25134. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25135. return null;
  25136. },
  25137. enumerable: true,
  25138. configurable: true
  25139. });
  25140. /** @hidden */
  25141. Scene.prototype.getParticlesDuration = function () {
  25142. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25143. return 0;
  25144. };
  25145. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25146. /** @hidden */
  25147. get: function () {
  25148. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25149. return null;
  25150. },
  25151. enumerable: true,
  25152. configurable: true
  25153. });
  25154. /** @hidden */
  25155. Scene.prototype.getSpritesDuration = function () {
  25156. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25157. return 0;
  25158. };
  25159. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25160. /** @hidden */
  25161. get: function () {
  25162. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25163. return null;
  25164. },
  25165. enumerable: true,
  25166. configurable: true
  25167. });
  25168. /**
  25169. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25170. * @returns a number
  25171. */
  25172. Scene.prototype.getAnimationRatio = function () {
  25173. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25174. };
  25175. /**
  25176. * Gets an unique Id for the current render phase
  25177. * @returns a number
  25178. */
  25179. Scene.prototype.getRenderId = function () {
  25180. return this._renderId;
  25181. };
  25182. /**
  25183. * Gets an unique Id for the current frame
  25184. * @returns a number
  25185. */
  25186. Scene.prototype.getFrameId = function () {
  25187. return this._frameId;
  25188. };
  25189. /** Call this function if you want to manually increment the render Id*/
  25190. Scene.prototype.incrementRenderId = function () {
  25191. this._renderId++;
  25192. };
  25193. Scene.prototype._updatePointerPosition = function (evt) {
  25194. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25195. if (!canvasRect) {
  25196. return;
  25197. }
  25198. this._pointerX = evt.clientX - canvasRect.left;
  25199. this._pointerY = evt.clientY - canvasRect.top;
  25200. this._unTranslatedPointerX = this._pointerX;
  25201. this._unTranslatedPointerY = this._pointerY;
  25202. };
  25203. Scene.prototype._createUbo = function () {
  25204. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25205. this._sceneUbo.addUniform("viewProjection", 16);
  25206. this._sceneUbo.addUniform("view", 16);
  25207. };
  25208. Scene.prototype._createAlternateUbo = function () {
  25209. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25210. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25211. this._alternateSceneUbo.addUniform("view", 16);
  25212. };
  25213. // Pointers handling
  25214. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25215. if (pointerInfo.pickInfo) {
  25216. if (!pointerInfo.pickInfo.ray) {
  25217. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25218. }
  25219. }
  25220. };
  25221. /**
  25222. * Use this method to simulate a pointer move on a mesh
  25223. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25224. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25225. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25226. * @returns the current scene
  25227. */
  25228. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25229. var evt = new PointerEvent("pointermove", pointerEventInit);
  25230. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25231. return this;
  25232. }
  25233. return this._processPointerMove(pickResult, evt);
  25234. };
  25235. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25236. var canvas = this._engine.getRenderingCanvas();
  25237. if (!canvas) {
  25238. return this;
  25239. }
  25240. // Restore pointer
  25241. canvas.style.cursor = this.defaultCursor;
  25242. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25243. if (isMeshPicked) {
  25244. this.setPointerOverMesh(pickResult.pickedMesh);
  25245. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25246. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25247. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25248. }
  25249. else {
  25250. canvas.style.cursor = this.hoverCursor;
  25251. }
  25252. }
  25253. }
  25254. else {
  25255. this.setPointerOverMesh(null);
  25256. }
  25257. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25258. var step = _a[_i];
  25259. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25260. }
  25261. if (pickResult) {
  25262. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25263. if (this.onPointerMove) {
  25264. this.onPointerMove(evt, pickResult, type);
  25265. }
  25266. if (this.onPointerObservable.hasObservers()) {
  25267. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25268. this._setRayOnPointerInfo(pi);
  25269. this.onPointerObservable.notifyObservers(pi, type);
  25270. }
  25271. }
  25272. return this;
  25273. };
  25274. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25275. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25276. if (pickResult) {
  25277. pi.ray = pickResult.ray;
  25278. }
  25279. this.onPrePointerObservable.notifyObservers(pi, type);
  25280. if (pi.skipOnPointerObservable) {
  25281. return true;
  25282. }
  25283. else {
  25284. return false;
  25285. }
  25286. };
  25287. /**
  25288. * Use this method to simulate a pointer down on a mesh
  25289. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25290. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25291. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25292. * @returns the current scene
  25293. */
  25294. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25295. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25296. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25297. return this;
  25298. }
  25299. return this._processPointerDown(pickResult, evt);
  25300. };
  25301. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25302. var _this = this;
  25303. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25304. this._pickedDownMesh = pickResult.pickedMesh;
  25305. var actionManager = pickResult.pickedMesh.actionManager;
  25306. if (actionManager) {
  25307. if (actionManager.hasPickTriggers) {
  25308. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25309. switch (evt.button) {
  25310. case 0:
  25311. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25312. break;
  25313. case 1:
  25314. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25315. break;
  25316. case 2:
  25317. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25318. break;
  25319. }
  25320. }
  25321. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25322. window.setTimeout(function () {
  25323. 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);
  25324. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25325. if (_this._totalPointersPressed !== 0 &&
  25326. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25327. !_this._isPointerSwiping()) {
  25328. _this._startingPointerTime = 0;
  25329. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25330. }
  25331. }
  25332. }, Scene.LongPressDelay);
  25333. }
  25334. }
  25335. }
  25336. else {
  25337. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25338. var step = _a[_i];
  25339. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25340. }
  25341. }
  25342. if (pickResult) {
  25343. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25344. if (this.onPointerDown) {
  25345. this.onPointerDown(evt, pickResult, type);
  25346. }
  25347. if (this.onPointerObservable.hasObservers()) {
  25348. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25349. this._setRayOnPointerInfo(pi);
  25350. this.onPointerObservable.notifyObservers(pi, type);
  25351. }
  25352. }
  25353. return this;
  25354. };
  25355. /**
  25356. * Use this method to simulate a pointer up on a mesh
  25357. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25358. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25359. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25360. * @returns the current scene
  25361. */
  25362. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25363. var evt = new PointerEvent("pointerup", pointerEventInit);
  25364. var clickInfo = new ClickInfo();
  25365. clickInfo.singleClick = true;
  25366. clickInfo.ignore = true;
  25367. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25368. return this;
  25369. }
  25370. return this._processPointerUp(pickResult, evt, clickInfo);
  25371. };
  25372. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25373. if (pickResult && pickResult && pickResult.pickedMesh) {
  25374. this._pickedUpMesh = pickResult.pickedMesh;
  25375. if (this._pickedDownMesh === this._pickedUpMesh) {
  25376. if (this.onPointerPick) {
  25377. this.onPointerPick(evt, pickResult);
  25378. }
  25379. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25380. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25381. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25382. this._setRayOnPointerInfo(pi);
  25383. this.onPointerObservable.notifyObservers(pi, type_1);
  25384. }
  25385. }
  25386. if (pickResult.pickedMesh.actionManager) {
  25387. if (clickInfo.ignore) {
  25388. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25389. }
  25390. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25391. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25392. }
  25393. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25394. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25395. }
  25396. }
  25397. }
  25398. else {
  25399. if (!clickInfo.ignore) {
  25400. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25401. var step = _a[_i];
  25402. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25403. }
  25404. }
  25405. }
  25406. if (this._pickedDownMesh &&
  25407. this._pickedDownMesh.actionManager &&
  25408. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25409. this._pickedDownMesh !== this._pickedUpMesh) {
  25410. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25411. }
  25412. var type = BABYLON.PointerEventTypes.POINTERUP;
  25413. if (this.onPointerObservable.hasObservers()) {
  25414. if (!clickInfo.ignore) {
  25415. if (!clickInfo.hasSwiped) {
  25416. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25417. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25418. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25419. this._setRayOnPointerInfo(pi);
  25420. this.onPointerObservable.notifyObservers(pi, type_2);
  25421. }
  25422. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25423. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25424. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25425. this._setRayOnPointerInfo(pi);
  25426. this.onPointerObservable.notifyObservers(pi, type_3);
  25427. }
  25428. }
  25429. }
  25430. else {
  25431. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25432. this._setRayOnPointerInfo(pi);
  25433. this.onPointerObservable.notifyObservers(pi, type);
  25434. }
  25435. }
  25436. if (this.onPointerUp) {
  25437. this.onPointerUp(evt, pickResult, type);
  25438. }
  25439. return this;
  25440. };
  25441. /**
  25442. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25443. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25444. * @returns true if the pointer was captured
  25445. */
  25446. Scene.prototype.isPointerCaptured = function (pointerId) {
  25447. if (pointerId === void 0) { pointerId = 0; }
  25448. return this._pointerCaptures[pointerId];
  25449. };
  25450. /** @hidden */
  25451. Scene.prototype._isPointerSwiping = function () {
  25452. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25453. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25454. };
  25455. /**
  25456. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25457. * @param attachUp defines if you want to attach events to pointerup
  25458. * @param attachDown defines if you want to attach events to pointerdown
  25459. * @param attachMove defines if you want to attach events to pointermove
  25460. */
  25461. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25462. var _this = this;
  25463. if (attachUp === void 0) { attachUp = true; }
  25464. if (attachDown === void 0) { attachDown = true; }
  25465. if (attachMove === void 0) { attachMove = true; }
  25466. this._initActionManager = function (act, clickInfo) {
  25467. if (!_this._meshPickProceed) {
  25468. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25469. _this._currentPickResult = pickResult;
  25470. if (pickResult) {
  25471. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25472. }
  25473. _this._meshPickProceed = true;
  25474. }
  25475. return act;
  25476. };
  25477. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25478. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25479. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25480. btn !== _this._previousButtonPressed) {
  25481. _this._doubleClickOccured = false;
  25482. clickInfo.singleClick = true;
  25483. clickInfo.ignore = false;
  25484. cb(clickInfo, _this._currentPickResult);
  25485. }
  25486. };
  25487. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25488. var clickInfo = new ClickInfo();
  25489. _this._currentPickResult = null;
  25490. var act = null;
  25491. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25492. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25493. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25494. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25495. act = _this._initActionManager(act, clickInfo);
  25496. if (act)
  25497. checkPicking = act.hasPickTriggers;
  25498. }
  25499. if (checkPicking) {
  25500. var btn = evt.button;
  25501. clickInfo.hasSwiped = _this._isPointerSwiping();
  25502. if (!clickInfo.hasSwiped) {
  25503. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25504. if (!checkSingleClickImmediately) {
  25505. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25506. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25507. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25508. act = _this._initActionManager(act, clickInfo);
  25509. if (act)
  25510. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25511. }
  25512. }
  25513. if (checkSingleClickImmediately) {
  25514. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25515. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25516. btn !== _this._previousButtonPressed) {
  25517. clickInfo.singleClick = true;
  25518. cb(clickInfo, _this._currentPickResult);
  25519. }
  25520. }
  25521. // at least one double click is required to be check and exclusive double click is enabled
  25522. else {
  25523. // wait that no double click has been raised during the double click delay
  25524. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25525. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25526. }
  25527. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25528. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25529. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25530. act = _this._initActionManager(act, clickInfo);
  25531. if (act)
  25532. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25533. }
  25534. if (checkDoubleClick) {
  25535. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25536. if (btn === _this._previousButtonPressed &&
  25537. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25538. !_this._doubleClickOccured) {
  25539. // pointer has not moved for 2 clicks, it's a double click
  25540. if (!clickInfo.hasSwiped &&
  25541. !_this._isPointerSwiping()) {
  25542. _this._previousStartingPointerTime = 0;
  25543. _this._doubleClickOccured = true;
  25544. clickInfo.doubleClick = true;
  25545. clickInfo.ignore = false;
  25546. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25547. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25548. }
  25549. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25550. cb(clickInfo, _this._currentPickResult);
  25551. }
  25552. // if the two successive clicks are too far, it's just two simple clicks
  25553. else {
  25554. _this._doubleClickOccured = false;
  25555. _this._previousStartingPointerTime = _this._startingPointerTime;
  25556. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25557. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25558. _this._previousButtonPressed = btn;
  25559. if (Scene.ExclusiveDoubleClickMode) {
  25560. if (_this._previousDelayedSimpleClickTimeout) {
  25561. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25562. }
  25563. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25564. cb(clickInfo, _this._previousPickResult);
  25565. }
  25566. else {
  25567. cb(clickInfo, _this._currentPickResult);
  25568. }
  25569. }
  25570. }
  25571. // just the first click of the double has been raised
  25572. else {
  25573. _this._doubleClickOccured = false;
  25574. _this._previousStartingPointerTime = _this._startingPointerTime;
  25575. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25576. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25577. _this._previousButtonPressed = btn;
  25578. }
  25579. }
  25580. }
  25581. }
  25582. clickInfo.ignore = true;
  25583. cb(clickInfo, _this._currentPickResult);
  25584. };
  25585. this._onPointerMove = function (evt) {
  25586. _this._updatePointerPosition(evt);
  25587. // PreObservable support
  25588. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25589. return;
  25590. }
  25591. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25592. return;
  25593. }
  25594. if (!_this.pointerMovePredicate) {
  25595. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25596. }
  25597. // Meshes
  25598. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25599. _this._processPointerMove(pickResult, evt);
  25600. };
  25601. this._onPointerDown = function (evt) {
  25602. _this._totalPointersPressed++;
  25603. _this._pickedDownMesh = null;
  25604. _this._meshPickProceed = false;
  25605. _this._updatePointerPosition(evt);
  25606. if (_this.preventDefaultOnPointerDown && canvas) {
  25607. evt.preventDefault();
  25608. canvas.focus();
  25609. }
  25610. // PreObservable support
  25611. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25612. return;
  25613. }
  25614. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25615. return;
  25616. }
  25617. _this._pointerCaptures[evt.pointerId] = true;
  25618. _this._startingPointerPosition.x = _this._pointerX;
  25619. _this._startingPointerPosition.y = _this._pointerY;
  25620. _this._startingPointerTime = Date.now();
  25621. if (!_this.pointerDownPredicate) {
  25622. _this.pointerDownPredicate = function (mesh) {
  25623. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25624. };
  25625. }
  25626. // Meshes
  25627. _this._pickedDownMesh = null;
  25628. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25629. _this._processPointerDown(pickResult, evt);
  25630. };
  25631. this._onPointerUp = function (evt) {
  25632. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25633. return; // So we need to test it the pointer down was pressed before.
  25634. }
  25635. _this._totalPointersPressed--;
  25636. _this._pickedUpMesh = null;
  25637. _this._meshPickProceed = false;
  25638. _this._updatePointerPosition(evt);
  25639. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25640. // PreObservable support
  25641. if (_this.onPrePointerObservable.hasObservers()) {
  25642. if (!clickInfo.ignore) {
  25643. if (!clickInfo.hasSwiped) {
  25644. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25645. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25646. return;
  25647. }
  25648. }
  25649. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25650. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25651. return;
  25652. }
  25653. }
  25654. }
  25655. }
  25656. else {
  25657. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25658. return;
  25659. }
  25660. }
  25661. }
  25662. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25663. return;
  25664. }
  25665. _this._pointerCaptures[evt.pointerId] = false;
  25666. if (!_this.pointerUpPredicate) {
  25667. _this.pointerUpPredicate = function (mesh) {
  25668. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25669. };
  25670. }
  25671. // Meshes
  25672. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25673. _this._initActionManager(null, clickInfo);
  25674. }
  25675. if (!pickResult) {
  25676. pickResult = _this._currentPickResult;
  25677. }
  25678. _this._processPointerUp(pickResult, evt, clickInfo);
  25679. _this._previousPickResult = _this._currentPickResult;
  25680. });
  25681. };
  25682. this._onKeyDown = function (evt) {
  25683. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25684. if (_this.onPreKeyboardObservable.hasObservers()) {
  25685. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25686. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25687. if (pi.skipOnPointerObservable) {
  25688. return;
  25689. }
  25690. }
  25691. if (_this.onKeyboardObservable.hasObservers()) {
  25692. var pi = new BABYLON.KeyboardInfo(type, evt);
  25693. _this.onKeyboardObservable.notifyObservers(pi, type);
  25694. }
  25695. if (_this.actionManager) {
  25696. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25697. }
  25698. };
  25699. this._onKeyUp = function (evt) {
  25700. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25701. if (_this.onPreKeyboardObservable.hasObservers()) {
  25702. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25703. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25704. if (pi.skipOnPointerObservable) {
  25705. return;
  25706. }
  25707. }
  25708. if (_this.onKeyboardObservable.hasObservers()) {
  25709. var pi = new BABYLON.KeyboardInfo(type, evt);
  25710. _this.onKeyboardObservable.notifyObservers(pi, type);
  25711. }
  25712. if (_this.actionManager) {
  25713. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25714. }
  25715. };
  25716. var engine = this.getEngine();
  25717. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25718. if (!canvas) {
  25719. return;
  25720. }
  25721. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25722. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25723. });
  25724. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25725. if (!canvas) {
  25726. return;
  25727. }
  25728. canvas.removeEventListener("keydown", _this._onKeyDown);
  25729. canvas.removeEventListener("keyup", _this._onKeyUp);
  25730. });
  25731. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25732. var canvas = this._engine.getRenderingCanvas();
  25733. if (!canvas) {
  25734. return;
  25735. }
  25736. if (attachMove) {
  25737. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25738. // Wheel
  25739. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25740. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25741. }
  25742. if (attachDown) {
  25743. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25744. }
  25745. if (attachUp) {
  25746. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25747. }
  25748. canvas.tabIndex = 1;
  25749. };
  25750. /** Detaches all event handlers*/
  25751. Scene.prototype.detachControl = function () {
  25752. var engine = this.getEngine();
  25753. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25754. var canvas = engine.getRenderingCanvas();
  25755. if (!canvas) {
  25756. return;
  25757. }
  25758. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25759. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25760. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25761. if (this._onCanvasBlurObserver) {
  25762. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25763. }
  25764. if (this._onCanvasFocusObserver) {
  25765. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25766. }
  25767. // Wheel
  25768. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25769. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25770. // Keyboard
  25771. canvas.removeEventListener("keydown", this._onKeyDown);
  25772. canvas.removeEventListener("keyup", this._onKeyUp);
  25773. // Observables
  25774. this.onKeyboardObservable.clear();
  25775. this.onPreKeyboardObservable.clear();
  25776. this.onPointerObservable.clear();
  25777. this.onPrePointerObservable.clear();
  25778. };
  25779. /**
  25780. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25781. * Delay loaded resources are not taking in account
  25782. * @return true if all required resources are ready
  25783. */
  25784. Scene.prototype.isReady = function () {
  25785. if (this._isDisposed) {
  25786. return false;
  25787. }
  25788. if (this._pendingData.length > 0) {
  25789. return false;
  25790. }
  25791. var index;
  25792. var engine = this.getEngine();
  25793. // Geometries
  25794. for (index = 0; index < this.geometries.length; index++) {
  25795. var geometry = this.geometries[index];
  25796. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25797. return false;
  25798. }
  25799. }
  25800. // Meshes
  25801. for (index = 0; index < this.meshes.length; index++) {
  25802. var mesh = this.meshes[index];
  25803. if (!mesh.isEnabled()) {
  25804. continue;
  25805. }
  25806. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25807. continue;
  25808. }
  25809. if (!mesh.isReady(true)) {
  25810. return false;
  25811. }
  25812. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25813. // Is Ready For Mesh
  25814. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25815. var step = _a[_i];
  25816. if (!step.action(mesh, hardwareInstancedRendering)) {
  25817. return false;
  25818. }
  25819. }
  25820. }
  25821. // Post-processes
  25822. if (this.activeCameras && this.activeCameras.length > 0) {
  25823. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25824. var camera = _c[_b];
  25825. if (!camera.isReady(true)) {
  25826. return false;
  25827. }
  25828. }
  25829. }
  25830. else if (this.activeCamera) {
  25831. if (!this.activeCamera.isReady(true)) {
  25832. return false;
  25833. }
  25834. }
  25835. // Particles
  25836. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25837. var particleSystem = _e[_d];
  25838. if (!particleSystem.isReady()) {
  25839. return false;
  25840. }
  25841. }
  25842. return true;
  25843. };
  25844. /** Resets all cached information relative to material (including effect and visibility) */
  25845. Scene.prototype.resetCachedMaterial = function () {
  25846. this._cachedMaterial = null;
  25847. this._cachedEffect = null;
  25848. this._cachedVisibility = null;
  25849. };
  25850. /**
  25851. * Registers a function to be called before every frame render
  25852. * @param func defines the function to register
  25853. */
  25854. Scene.prototype.registerBeforeRender = function (func) {
  25855. this.onBeforeRenderObservable.add(func);
  25856. };
  25857. /**
  25858. * Unregisters a function called before every frame render
  25859. * @param func defines the function to unregister
  25860. */
  25861. Scene.prototype.unregisterBeforeRender = function (func) {
  25862. this.onBeforeRenderObservable.removeCallback(func);
  25863. };
  25864. /**
  25865. * Registers a function to be called after every frame render
  25866. * @param func defines the function to register
  25867. */
  25868. Scene.prototype.registerAfterRender = function (func) {
  25869. this.onAfterRenderObservable.add(func);
  25870. };
  25871. /**
  25872. * Unregisters a function called after every frame render
  25873. * @param func defines the function to unregister
  25874. */
  25875. Scene.prototype.unregisterAfterRender = function (func) {
  25876. this.onAfterRenderObservable.removeCallback(func);
  25877. };
  25878. Scene.prototype._executeOnceBeforeRender = function (func) {
  25879. var _this = this;
  25880. var execFunc = function () {
  25881. func();
  25882. setTimeout(function () {
  25883. _this.unregisterBeforeRender(execFunc);
  25884. });
  25885. };
  25886. this.registerBeforeRender(execFunc);
  25887. };
  25888. /**
  25889. * The provided function will run before render once and will be disposed afterwards.
  25890. * A timeout delay can be provided so that the function will be executed in N ms.
  25891. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25892. * @param func The function to be executed.
  25893. * @param timeout optional delay in ms
  25894. */
  25895. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25896. var _this = this;
  25897. if (timeout !== undefined) {
  25898. setTimeout(function () {
  25899. _this._executeOnceBeforeRender(func);
  25900. }, timeout);
  25901. }
  25902. else {
  25903. this._executeOnceBeforeRender(func);
  25904. }
  25905. };
  25906. /** @hidden */
  25907. Scene.prototype._addPendingData = function (data) {
  25908. this._pendingData.push(data);
  25909. };
  25910. /** @hidden */
  25911. Scene.prototype._removePendingData = function (data) {
  25912. var wasLoading = this.isLoading;
  25913. var index = this._pendingData.indexOf(data);
  25914. if (index !== -1) {
  25915. this._pendingData.splice(index, 1);
  25916. }
  25917. if (wasLoading && !this.isLoading) {
  25918. this.onDataLoadedObservable.notifyObservers(this);
  25919. }
  25920. };
  25921. /**
  25922. * Returns the number of items waiting to be loaded
  25923. * @returns the number of items waiting to be loaded
  25924. */
  25925. Scene.prototype.getWaitingItemsCount = function () {
  25926. return this._pendingData.length;
  25927. };
  25928. Object.defineProperty(Scene.prototype, "isLoading", {
  25929. /**
  25930. * Returns a boolean indicating if the scene is still loading data
  25931. */
  25932. get: function () {
  25933. return this._pendingData.length > 0;
  25934. },
  25935. enumerable: true,
  25936. configurable: true
  25937. });
  25938. /**
  25939. * Registers a function to be executed when the scene is ready
  25940. * @param {Function} func - the function to be executed
  25941. */
  25942. Scene.prototype.executeWhenReady = function (func) {
  25943. var _this = this;
  25944. this.onReadyObservable.add(func);
  25945. if (this._executeWhenReadyTimeoutId !== -1) {
  25946. return;
  25947. }
  25948. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25949. _this._checkIsReady();
  25950. }, 150);
  25951. };
  25952. /**
  25953. * Returns a promise that resolves when the scene is ready
  25954. * @returns A promise that resolves when the scene is ready
  25955. */
  25956. Scene.prototype.whenReadyAsync = function () {
  25957. var _this = this;
  25958. return new Promise(function (resolve) {
  25959. _this.executeWhenReady(function () {
  25960. resolve();
  25961. });
  25962. });
  25963. };
  25964. /** @hidden */
  25965. Scene.prototype._checkIsReady = function () {
  25966. var _this = this;
  25967. this._registerTransientComponents();
  25968. if (this.isReady()) {
  25969. this.onReadyObservable.notifyObservers(this);
  25970. this.onReadyObservable.clear();
  25971. this._executeWhenReadyTimeoutId = -1;
  25972. return;
  25973. }
  25974. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25975. _this._checkIsReady();
  25976. }, 150);
  25977. };
  25978. // Animations
  25979. /**
  25980. * Will start the animation sequence of a given target
  25981. * @param target defines the target
  25982. * @param from defines from which frame should animation start
  25983. * @param to defines until which frame should animation run.
  25984. * @param weight defines the weight to apply to the animation (1.0 by default)
  25985. * @param loop defines if the animation loops
  25986. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25987. * @param onAnimationEnd defines the function to be executed when the animation ends
  25988. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25989. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25990. * @returns the animatable object created for this animation
  25991. */
  25992. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25993. if (weight === void 0) { weight = 1.0; }
  25994. if (speedRatio === void 0) { speedRatio = 1.0; }
  25995. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25996. returnedAnimatable.weight = weight;
  25997. return returnedAnimatable;
  25998. };
  25999. /**
  26000. * Will start the animation sequence of a given target
  26001. * @param target defines the target
  26002. * @param from defines from which frame should animation start
  26003. * @param to defines until which frame should animation run.
  26004. * @param loop defines if the animation loops
  26005. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26006. * @param onAnimationEnd defines the function to be executed when the animation ends
  26007. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26008. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26009. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26010. * @returns the animatable object created for this animation
  26011. */
  26012. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26013. if (speedRatio === void 0) { speedRatio = 1.0; }
  26014. if (stopCurrent === void 0) { stopCurrent = true; }
  26015. if (from > to && speedRatio > 0) {
  26016. speedRatio *= -1;
  26017. }
  26018. if (stopCurrent) {
  26019. this.stopAnimation(target, undefined, targetMask);
  26020. }
  26021. if (!animatable) {
  26022. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26023. }
  26024. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26025. // Local animations
  26026. if (target.animations && shouldRunTargetAnimations) {
  26027. animatable.appendAnimations(target, target.animations);
  26028. }
  26029. // Children animations
  26030. if (target.getAnimatables) {
  26031. var animatables = target.getAnimatables();
  26032. for (var index = 0; index < animatables.length; index++) {
  26033. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26034. }
  26035. }
  26036. animatable.reset();
  26037. return animatable;
  26038. };
  26039. /**
  26040. * Begin a new animation on a given node
  26041. * @param target defines the target where the animation will take place
  26042. * @param animations defines the list of animations to start
  26043. * @param from defines the initial value
  26044. * @param to defines the final value
  26045. * @param loop defines if you want animation to loop (off by default)
  26046. * @param speedRatio defines the speed ratio to apply to all animations
  26047. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26048. * @returns the list of created animatables
  26049. */
  26050. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26051. if (speedRatio === undefined) {
  26052. speedRatio = 1.0;
  26053. }
  26054. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26055. return animatable;
  26056. };
  26057. /**
  26058. * Begin a new animation on a given node and its hierarchy
  26059. * @param target defines the root node where the animation will take place
  26060. * @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.
  26061. * @param animations defines the list of animations to start
  26062. * @param from defines the initial value
  26063. * @param to defines the final value
  26064. * @param loop defines if you want animation to loop (off by default)
  26065. * @param speedRatio defines the speed ratio to apply to all animations
  26066. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26067. * @returns the list of animatables created for all nodes
  26068. */
  26069. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26070. var children = target.getDescendants(directDescendantsOnly);
  26071. var result = [];
  26072. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26073. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26074. var child = children_1[_i];
  26075. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26076. }
  26077. return result;
  26078. };
  26079. /**
  26080. * Gets the animatable associated with a specific target
  26081. * @param target defines the target of the animatable
  26082. * @returns the required animatable if found
  26083. */
  26084. Scene.prototype.getAnimatableByTarget = function (target) {
  26085. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26086. if (this._activeAnimatables[index].target === target) {
  26087. return this._activeAnimatables[index];
  26088. }
  26089. }
  26090. return null;
  26091. };
  26092. /**
  26093. * Gets all animatables associated with a given target
  26094. * @param target defines the target to look animatables for
  26095. * @returns an array of Animatables
  26096. */
  26097. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26098. var result = [];
  26099. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26100. if (this._activeAnimatables[index].target === target) {
  26101. result.push(this._activeAnimatables[index]);
  26102. }
  26103. }
  26104. return result;
  26105. };
  26106. Object.defineProperty(Scene.prototype, "animatables", {
  26107. /**
  26108. * Gets all animatable attached to the scene
  26109. */
  26110. get: function () {
  26111. return this._activeAnimatables;
  26112. },
  26113. enumerable: true,
  26114. configurable: true
  26115. });
  26116. /**
  26117. * Will stop the animation of the given target
  26118. * @param target - the target
  26119. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26120. * @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)
  26121. */
  26122. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26123. var animatables = this.getAllAnimatablesByTarget(target);
  26124. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26125. var animatable = animatables_1[_i];
  26126. animatable.stop(animationName, targetMask);
  26127. }
  26128. };
  26129. /**
  26130. * Stops and removes all animations that have been applied to the scene
  26131. */
  26132. Scene.prototype.stopAllAnimations = function () {
  26133. if (this._activeAnimatables) {
  26134. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26135. this._activeAnimatables[i].stop();
  26136. }
  26137. this._activeAnimatables = [];
  26138. }
  26139. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26140. var group = _a[_i];
  26141. group.stop();
  26142. }
  26143. };
  26144. Scene.prototype._animate = function () {
  26145. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26146. return;
  26147. }
  26148. // Getting time
  26149. var now = BABYLON.Tools.Now;
  26150. if (!this._animationTimeLast) {
  26151. if (this._pendingData.length > 0) {
  26152. return;
  26153. }
  26154. this._animationTimeLast = now;
  26155. }
  26156. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26157. this._animationTime += deltaTime;
  26158. this._animationTimeLast = now;
  26159. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26160. this._activeAnimatables[index]._animate(this._animationTime);
  26161. }
  26162. // Late animation bindings
  26163. this._processLateAnimationBindings();
  26164. };
  26165. /** @hidden */
  26166. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26167. var target = runtimeAnimation.target;
  26168. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26169. if (!target._lateAnimationHolders) {
  26170. target._lateAnimationHolders = {};
  26171. }
  26172. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26173. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26174. totalWeight: 0,
  26175. animations: [],
  26176. originalValue: originalValue
  26177. };
  26178. }
  26179. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26180. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26181. };
  26182. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26183. var normalizer = 1.0;
  26184. var finalPosition = BABYLON.Tmp.Vector3[0];
  26185. var finalScaling = BABYLON.Tmp.Vector3[1];
  26186. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26187. var startIndex = 0;
  26188. var originalAnimation = holder.animations[0];
  26189. var originalValue = holder.originalValue;
  26190. var scale = 1;
  26191. if (holder.totalWeight < 1.0) {
  26192. // We need to mix the original value in
  26193. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26194. scale = 1.0 - holder.totalWeight;
  26195. }
  26196. else {
  26197. startIndex = 1;
  26198. // We need to normalize the weights
  26199. normalizer = holder.totalWeight;
  26200. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26201. scale = originalAnimation.weight / normalizer;
  26202. if (scale == 1) {
  26203. return originalAnimation.currentValue;
  26204. }
  26205. }
  26206. finalScaling.scaleInPlace(scale);
  26207. finalPosition.scaleInPlace(scale);
  26208. finalQuaternion.scaleInPlace(scale);
  26209. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26210. var runtimeAnimation = holder.animations[animIndex];
  26211. var scale = runtimeAnimation.weight / normalizer;
  26212. var currentPosition = BABYLON.Tmp.Vector3[2];
  26213. var currentScaling = BABYLON.Tmp.Vector3[3];
  26214. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26215. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26216. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26217. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26218. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26219. }
  26220. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26221. return originalAnimation._workValue;
  26222. };
  26223. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26224. var originalAnimation = holder.animations[0];
  26225. var originalValue = holder.originalValue;
  26226. if (holder.animations.length === 1) {
  26227. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26228. return refQuaternion;
  26229. }
  26230. var normalizer = 1.0;
  26231. var quaternions;
  26232. var weights;
  26233. if (holder.totalWeight < 1.0) {
  26234. var scale = 1.0 - holder.totalWeight;
  26235. quaternions = [];
  26236. weights = [];
  26237. quaternions.push(originalValue);
  26238. weights.push(scale);
  26239. }
  26240. else {
  26241. if (holder.animations.length === 2) { // Slerp as soon as we can
  26242. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26243. return refQuaternion;
  26244. }
  26245. quaternions = [];
  26246. weights = [];
  26247. normalizer = holder.totalWeight;
  26248. }
  26249. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26250. var runtimeAnimation = holder.animations[animIndex];
  26251. quaternions.push(runtimeAnimation.currentValue);
  26252. weights.push(runtimeAnimation.weight / normalizer);
  26253. }
  26254. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26255. var cumulativeAmount = 0;
  26256. var cumulativeQuaternion = null;
  26257. for (var index = 0; index < quaternions.length;) {
  26258. if (!cumulativeQuaternion) {
  26259. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26260. cumulativeQuaternion = refQuaternion;
  26261. cumulativeAmount = weights[index] + weights[index + 1];
  26262. index += 2;
  26263. continue;
  26264. }
  26265. cumulativeAmount += weights[index];
  26266. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26267. index++;
  26268. }
  26269. return cumulativeQuaternion;
  26270. };
  26271. Scene.prototype._processLateAnimationBindings = function () {
  26272. if (!this._registeredForLateAnimationBindings.length) {
  26273. return;
  26274. }
  26275. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26276. var target = this._registeredForLateAnimationBindings.data[index];
  26277. for (var path in target._lateAnimationHolders) {
  26278. var holder = target._lateAnimationHolders[path];
  26279. var originalAnimation = holder.animations[0];
  26280. var originalValue = holder.originalValue;
  26281. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26282. var finalValue = target[path];
  26283. if (matrixDecomposeMode) {
  26284. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26285. }
  26286. else {
  26287. var quaternionMode = originalValue.w !== undefined;
  26288. if (quaternionMode) {
  26289. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26290. }
  26291. else {
  26292. var startIndex = 0;
  26293. var normalizer = 1.0;
  26294. if (holder.totalWeight < 1.0) {
  26295. // We need to mix the original value in
  26296. if (originalValue.scale) {
  26297. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26298. }
  26299. else {
  26300. finalValue = originalValue * (1.0 - holder.totalWeight);
  26301. }
  26302. }
  26303. else {
  26304. // We need to normalize the weights
  26305. normalizer = holder.totalWeight;
  26306. var scale_1 = originalAnimation.weight / normalizer;
  26307. if (scale_1 !== 1) {
  26308. if (originalAnimation.currentValue.scale) {
  26309. finalValue = originalAnimation.currentValue.scale(scale_1);
  26310. }
  26311. else {
  26312. finalValue = originalAnimation.currentValue * scale_1;
  26313. }
  26314. }
  26315. else {
  26316. finalValue = originalAnimation.currentValue;
  26317. }
  26318. startIndex = 1;
  26319. }
  26320. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26321. var runtimeAnimation = holder.animations[animIndex];
  26322. var scale = runtimeAnimation.weight / normalizer;
  26323. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26324. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26325. }
  26326. else {
  26327. finalValue += runtimeAnimation.currentValue * scale;
  26328. }
  26329. }
  26330. }
  26331. }
  26332. target[path] = finalValue;
  26333. }
  26334. target._lateAnimationHolders = {};
  26335. }
  26336. this._registeredForLateAnimationBindings.reset();
  26337. };
  26338. // Matrix
  26339. /** @hidden */
  26340. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26341. this._useAlternateCameraConfiguration = active;
  26342. };
  26343. /**
  26344. * Gets the current view matrix
  26345. * @returns a Matrix
  26346. */
  26347. Scene.prototype.getViewMatrix = function () {
  26348. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26349. };
  26350. /**
  26351. * Gets the current projection matrix
  26352. * @returns a Matrix
  26353. */
  26354. Scene.prototype.getProjectionMatrix = function () {
  26355. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26356. };
  26357. /**
  26358. * Gets the current transform matrix
  26359. * @returns a Matrix made of View * Projection
  26360. */
  26361. Scene.prototype.getTransformMatrix = function () {
  26362. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26363. };
  26364. /**
  26365. * Sets the current transform matrix
  26366. * @param view defines the View matrix to use
  26367. * @param projection defines the Projection matrix to use
  26368. */
  26369. Scene.prototype.setTransformMatrix = function (view, projection) {
  26370. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26371. return;
  26372. }
  26373. this._viewUpdateFlag = view.updateFlag;
  26374. this._projectionUpdateFlag = projection.updateFlag;
  26375. this._viewMatrix = view;
  26376. this._projectionMatrix = projection;
  26377. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26378. // Update frustum
  26379. if (!this._frustumPlanes) {
  26380. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26381. }
  26382. else {
  26383. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26384. }
  26385. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26386. var otherCamera = this.activeCamera._alternateCamera;
  26387. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26388. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26389. }
  26390. if (this._sceneUbo.useUbo) {
  26391. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26392. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26393. this._sceneUbo.update();
  26394. }
  26395. };
  26396. /** @hidden */
  26397. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26398. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26399. return;
  26400. }
  26401. this._alternateViewUpdateFlag = view.updateFlag;
  26402. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26403. this._alternateViewMatrix = view;
  26404. this._alternateProjectionMatrix = projection;
  26405. if (!this._alternateTransformMatrix) {
  26406. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26407. }
  26408. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26409. if (!this._alternateSceneUbo) {
  26410. this._createAlternateUbo();
  26411. }
  26412. if (this._alternateSceneUbo.useUbo) {
  26413. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26414. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26415. this._alternateSceneUbo.update();
  26416. }
  26417. };
  26418. /**
  26419. * Gets the uniform buffer used to store scene data
  26420. * @returns a UniformBuffer
  26421. */
  26422. Scene.prototype.getSceneUniformBuffer = function () {
  26423. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26424. };
  26425. /**
  26426. * Gets an unique (relatively to the current scene) Id
  26427. * @returns an unique number for the scene
  26428. */
  26429. Scene.prototype.getUniqueId = function () {
  26430. var result = Scene._uniqueIdCounter;
  26431. Scene._uniqueIdCounter++;
  26432. return result;
  26433. };
  26434. /**
  26435. * Add a mesh to the list of scene's meshes
  26436. * @param newMesh defines the mesh to add
  26437. * @param recursive if all child meshes should also be added to the scene
  26438. */
  26439. Scene.prototype.addMesh = function (newMesh, recursive) {
  26440. var _this = this;
  26441. if (recursive === void 0) { recursive = false; }
  26442. this.meshes.push(newMesh);
  26443. //notify the collision coordinator
  26444. if (this.collisionCoordinator) {
  26445. this.collisionCoordinator.onMeshAdded(newMesh);
  26446. }
  26447. newMesh._resyncLightSources();
  26448. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26449. if (recursive) {
  26450. newMesh.getChildMeshes().forEach(function (m) {
  26451. _this.addMesh(m);
  26452. });
  26453. }
  26454. };
  26455. /**
  26456. * Remove a mesh for the list of scene's meshes
  26457. * @param toRemove defines the mesh to remove
  26458. * @param recursive if all child meshes should also be removed from the scene
  26459. * @returns the index where the mesh was in the mesh list
  26460. */
  26461. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26462. var _this = this;
  26463. if (recursive === void 0) { recursive = false; }
  26464. var index = this.meshes.indexOf(toRemove);
  26465. if (index !== -1) {
  26466. // Remove from the scene if mesh found
  26467. this.meshes.splice(index, 1);
  26468. }
  26469. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26470. if (recursive) {
  26471. toRemove.getChildMeshes().forEach(function (m) {
  26472. _this.removeMesh(m);
  26473. });
  26474. }
  26475. return index;
  26476. };
  26477. /**
  26478. * Add a transform node to the list of scene's transform nodes
  26479. * @param newTransformNode defines the transform node to add
  26480. */
  26481. Scene.prototype.addTransformNode = function (newTransformNode) {
  26482. this.transformNodes.push(newTransformNode);
  26483. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26484. };
  26485. /**
  26486. * Remove a transform node for the list of scene's transform nodes
  26487. * @param toRemove defines the transform node to remove
  26488. * @returns the index where the transform node was in the transform node list
  26489. */
  26490. Scene.prototype.removeTransformNode = function (toRemove) {
  26491. var index = this.transformNodes.indexOf(toRemove);
  26492. if (index !== -1) {
  26493. // Remove from the scene if found
  26494. this.transformNodes.splice(index, 1);
  26495. }
  26496. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26497. return index;
  26498. };
  26499. /**
  26500. * Remove a skeleton for the list of scene's skeletons
  26501. * @param toRemove defines the skeleton to remove
  26502. * @returns the index where the skeleton was in the skeleton list
  26503. */
  26504. Scene.prototype.removeSkeleton = function (toRemove) {
  26505. var index = this.skeletons.indexOf(toRemove);
  26506. if (index !== -1) {
  26507. // Remove from the scene if found
  26508. this.skeletons.splice(index, 1);
  26509. }
  26510. return index;
  26511. };
  26512. /**
  26513. * Remove a morph target for the list of scene's morph targets
  26514. * @param toRemove defines the morph target to remove
  26515. * @returns the index where the morph target was in the morph target list
  26516. */
  26517. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26518. var index = this.morphTargetManagers.indexOf(toRemove);
  26519. if (index !== -1) {
  26520. // Remove from the scene if found
  26521. this.morphTargetManagers.splice(index, 1);
  26522. }
  26523. return index;
  26524. };
  26525. /**
  26526. * Remove a light for the list of scene's lights
  26527. * @param toRemove defines the light to remove
  26528. * @returns the index where the light was in the light list
  26529. */
  26530. Scene.prototype.removeLight = function (toRemove) {
  26531. var index = this.lights.indexOf(toRemove);
  26532. if (index !== -1) {
  26533. // Remove from meshes
  26534. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26535. var mesh = _a[_i];
  26536. mesh._removeLightSource(toRemove);
  26537. }
  26538. // Remove from the scene if mesh found
  26539. this.lights.splice(index, 1);
  26540. this.sortLightsByPriority();
  26541. }
  26542. this.onLightRemovedObservable.notifyObservers(toRemove);
  26543. return index;
  26544. };
  26545. /**
  26546. * Remove a camera for the list of scene's cameras
  26547. * @param toRemove defines the camera to remove
  26548. * @returns the index where the camera was in the camera list
  26549. */
  26550. Scene.prototype.removeCamera = function (toRemove) {
  26551. var index = this.cameras.indexOf(toRemove);
  26552. if (index !== -1) {
  26553. // Remove from the scene if mesh found
  26554. this.cameras.splice(index, 1);
  26555. }
  26556. // Remove from activeCameras
  26557. var index2 = this.activeCameras.indexOf(toRemove);
  26558. if (index2 !== -1) {
  26559. // Remove from the scene if mesh found
  26560. this.activeCameras.splice(index2, 1);
  26561. }
  26562. // Reset the activeCamera
  26563. if (this.activeCamera === toRemove) {
  26564. if (this.cameras.length > 0) {
  26565. this.activeCamera = this.cameras[0];
  26566. }
  26567. else {
  26568. this.activeCamera = null;
  26569. }
  26570. }
  26571. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26572. return index;
  26573. };
  26574. /**
  26575. * Remove a particle system for the list of scene's particle systems
  26576. * @param toRemove defines the particle system to remove
  26577. * @returns the index where the particle system was in the particle system list
  26578. */
  26579. Scene.prototype.removeParticleSystem = function (toRemove) {
  26580. var index = this.particleSystems.indexOf(toRemove);
  26581. if (index !== -1) {
  26582. this.particleSystems.splice(index, 1);
  26583. }
  26584. return index;
  26585. };
  26586. /**
  26587. * Remove a animation for the list of scene's animations
  26588. * @param toRemove defines the animation to remove
  26589. * @returns the index where the animation was in the animation list
  26590. */
  26591. Scene.prototype.removeAnimation = function (toRemove) {
  26592. var index = this.animations.indexOf(toRemove);
  26593. if (index !== -1) {
  26594. this.animations.splice(index, 1);
  26595. }
  26596. return index;
  26597. };
  26598. /**
  26599. * Removes the given animation group from this scene.
  26600. * @param toRemove The animation group to remove
  26601. * @returns The index of the removed animation group
  26602. */
  26603. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26604. var index = this.animationGroups.indexOf(toRemove);
  26605. if (index !== -1) {
  26606. this.animationGroups.splice(index, 1);
  26607. }
  26608. return index;
  26609. };
  26610. /**
  26611. * Removes the given multi-material from this scene.
  26612. * @param toRemove The multi-material to remove
  26613. * @returns The index of the removed multi-material
  26614. */
  26615. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26616. var index = this.multiMaterials.indexOf(toRemove);
  26617. if (index !== -1) {
  26618. this.multiMaterials.splice(index, 1);
  26619. }
  26620. return index;
  26621. };
  26622. /**
  26623. * Removes the given material from this scene.
  26624. * @param toRemove The material to remove
  26625. * @returns The index of the removed material
  26626. */
  26627. Scene.prototype.removeMaterial = function (toRemove) {
  26628. var index = this.materials.indexOf(toRemove);
  26629. if (index !== -1) {
  26630. this.materials.splice(index, 1);
  26631. }
  26632. return index;
  26633. };
  26634. /**
  26635. * Removes the given action manager from this scene.
  26636. * @param toRemove The action manager to remove
  26637. * @returns The index of the removed action manager
  26638. */
  26639. Scene.prototype.removeActionManager = function (toRemove) {
  26640. var index = this.actionManagers.indexOf(toRemove);
  26641. if (index !== -1) {
  26642. this.actionManagers.splice(index, 1);
  26643. }
  26644. return index;
  26645. };
  26646. /**
  26647. * Removes the given texture from this scene.
  26648. * @param toRemove The texture to remove
  26649. * @returns The index of the removed texture
  26650. */
  26651. Scene.prototype.removeTexture = function (toRemove) {
  26652. var index = this.textures.indexOf(toRemove);
  26653. if (index !== -1) {
  26654. this.textures.splice(index, 1);
  26655. }
  26656. return index;
  26657. };
  26658. /**
  26659. * Adds the given light to this scene
  26660. * @param newLight The light to add
  26661. */
  26662. Scene.prototype.addLight = function (newLight) {
  26663. this.lights.push(newLight);
  26664. this.sortLightsByPriority();
  26665. // Add light to all meshes (To support if the light is removed and then readded)
  26666. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26667. var mesh = _a[_i];
  26668. if (mesh._lightSources.indexOf(newLight) === -1) {
  26669. mesh._lightSources.push(newLight);
  26670. mesh._resyncLightSources();
  26671. }
  26672. }
  26673. this.onNewLightAddedObservable.notifyObservers(newLight);
  26674. };
  26675. /**
  26676. * Sorts the list list based on light priorities
  26677. */
  26678. Scene.prototype.sortLightsByPriority = function () {
  26679. if (this.requireLightSorting) {
  26680. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26681. }
  26682. };
  26683. /**
  26684. * Adds the given camera to this scene
  26685. * @param newCamera The camera to add
  26686. */
  26687. Scene.prototype.addCamera = function (newCamera) {
  26688. this.cameras.push(newCamera);
  26689. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26690. };
  26691. /**
  26692. * Adds the given skeleton to this scene
  26693. * @param newSkeleton The skeleton to add
  26694. */
  26695. Scene.prototype.addSkeleton = function (newSkeleton) {
  26696. this.skeletons.push(newSkeleton);
  26697. };
  26698. /**
  26699. * Adds the given particle system to this scene
  26700. * @param newParticleSystem The particle system to add
  26701. */
  26702. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26703. this.particleSystems.push(newParticleSystem);
  26704. };
  26705. /**
  26706. * Adds the given animation to this scene
  26707. * @param newAnimation The animation to add
  26708. */
  26709. Scene.prototype.addAnimation = function (newAnimation) {
  26710. this.animations.push(newAnimation);
  26711. };
  26712. /**
  26713. * Adds the given animation group to this scene.
  26714. * @param newAnimationGroup The animation group to add
  26715. */
  26716. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26717. this.animationGroups.push(newAnimationGroup);
  26718. };
  26719. /**
  26720. * Adds the given multi-material to this scene
  26721. * @param newMultiMaterial The multi-material to add
  26722. */
  26723. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26724. this.multiMaterials.push(newMultiMaterial);
  26725. };
  26726. /**
  26727. * Adds the given material to this scene
  26728. * @param newMaterial The material to add
  26729. */
  26730. Scene.prototype.addMaterial = function (newMaterial) {
  26731. this.materials.push(newMaterial);
  26732. };
  26733. /**
  26734. * Adds the given morph target to this scene
  26735. * @param newMorphTargetManager The morph target to add
  26736. */
  26737. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26738. this.morphTargetManagers.push(newMorphTargetManager);
  26739. };
  26740. /**
  26741. * Adds the given geometry to this scene
  26742. * @param newGeometry The geometry to add
  26743. */
  26744. Scene.prototype.addGeometry = function (newGeometry) {
  26745. this.geometries.push(newGeometry);
  26746. };
  26747. /**
  26748. * Adds the given action manager to this scene
  26749. * @param newActionManager The action manager to add
  26750. */
  26751. Scene.prototype.addActionManager = function (newActionManager) {
  26752. this.actionManagers.push(newActionManager);
  26753. };
  26754. /**
  26755. * Adds the given texture to this scene.
  26756. * @param newTexture The texture to add
  26757. */
  26758. Scene.prototype.addTexture = function (newTexture) {
  26759. this.textures.push(newTexture);
  26760. };
  26761. /**
  26762. * Switch active camera
  26763. * @param newCamera defines the new active camera
  26764. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26765. */
  26766. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26767. if (attachControl === void 0) { attachControl = true; }
  26768. var canvas = this._engine.getRenderingCanvas();
  26769. if (!canvas) {
  26770. return;
  26771. }
  26772. if (this.activeCamera) {
  26773. this.activeCamera.detachControl(canvas);
  26774. }
  26775. this.activeCamera = newCamera;
  26776. if (attachControl) {
  26777. newCamera.attachControl(canvas);
  26778. }
  26779. };
  26780. /**
  26781. * sets the active camera of the scene using its ID
  26782. * @param id defines the camera's ID
  26783. * @return the new active camera or null if none found.
  26784. */
  26785. Scene.prototype.setActiveCameraByID = function (id) {
  26786. var camera = this.getCameraByID(id);
  26787. if (camera) {
  26788. this.activeCamera = camera;
  26789. return camera;
  26790. }
  26791. return null;
  26792. };
  26793. /**
  26794. * sets the active camera of the scene using its name
  26795. * @param name defines the camera's name
  26796. * @returns the new active camera or null if none found.
  26797. */
  26798. Scene.prototype.setActiveCameraByName = function (name) {
  26799. var camera = this.getCameraByName(name);
  26800. if (camera) {
  26801. this.activeCamera = camera;
  26802. return camera;
  26803. }
  26804. return null;
  26805. };
  26806. /**
  26807. * get an animation group using its name
  26808. * @param name defines the material's name
  26809. * @return the animation group or null if none found.
  26810. */
  26811. Scene.prototype.getAnimationGroupByName = function (name) {
  26812. for (var index = 0; index < this.animationGroups.length; index++) {
  26813. if (this.animationGroups[index].name === name) {
  26814. return this.animationGroups[index];
  26815. }
  26816. }
  26817. return null;
  26818. };
  26819. /**
  26820. * get a material using its id
  26821. * @param id defines the material's ID
  26822. * @return the material or null if none found.
  26823. */
  26824. Scene.prototype.getMaterialByID = function (id) {
  26825. for (var index = 0; index < this.materials.length; index++) {
  26826. if (this.materials[index].id === id) {
  26827. return this.materials[index];
  26828. }
  26829. }
  26830. return null;
  26831. };
  26832. /**
  26833. * Gets a material using its name
  26834. * @param name defines the material's name
  26835. * @return the material or null if none found.
  26836. */
  26837. Scene.prototype.getMaterialByName = function (name) {
  26838. for (var index = 0; index < this.materials.length; index++) {
  26839. if (this.materials[index].name === name) {
  26840. return this.materials[index];
  26841. }
  26842. }
  26843. return null;
  26844. };
  26845. /**
  26846. * Gets a camera using its id
  26847. * @param id defines the id to look for
  26848. * @returns the camera or null if not found
  26849. */
  26850. Scene.prototype.getCameraByID = function (id) {
  26851. for (var index = 0; index < this.cameras.length; index++) {
  26852. if (this.cameras[index].id === id) {
  26853. return this.cameras[index];
  26854. }
  26855. }
  26856. return null;
  26857. };
  26858. /**
  26859. * Gets a camera using its unique id
  26860. * @param uniqueId defines the unique id to look for
  26861. * @returns the camera or null if not found
  26862. */
  26863. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26864. for (var index = 0; index < this.cameras.length; index++) {
  26865. if (this.cameras[index].uniqueId === uniqueId) {
  26866. return this.cameras[index];
  26867. }
  26868. }
  26869. return null;
  26870. };
  26871. /**
  26872. * Gets a camera using its name
  26873. * @param name defines the camera's name
  26874. * @return the camera or null if none found.
  26875. */
  26876. Scene.prototype.getCameraByName = function (name) {
  26877. for (var index = 0; index < this.cameras.length; index++) {
  26878. if (this.cameras[index].name === name) {
  26879. return this.cameras[index];
  26880. }
  26881. }
  26882. return null;
  26883. };
  26884. /**
  26885. * Gets a bone using its id
  26886. * @param id defines the bone's id
  26887. * @return the bone or null if not found
  26888. */
  26889. Scene.prototype.getBoneByID = function (id) {
  26890. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26891. var skeleton = this.skeletons[skeletonIndex];
  26892. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26893. if (skeleton.bones[boneIndex].id === id) {
  26894. return skeleton.bones[boneIndex];
  26895. }
  26896. }
  26897. }
  26898. return null;
  26899. };
  26900. /**
  26901. * Gets a bone using its id
  26902. * @param name defines the bone's name
  26903. * @return the bone or null if not found
  26904. */
  26905. Scene.prototype.getBoneByName = function (name) {
  26906. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26907. var skeleton = this.skeletons[skeletonIndex];
  26908. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26909. if (skeleton.bones[boneIndex].name === name) {
  26910. return skeleton.bones[boneIndex];
  26911. }
  26912. }
  26913. }
  26914. return null;
  26915. };
  26916. /**
  26917. * Gets a light node using its name
  26918. * @param name defines the the light's name
  26919. * @return the light or null if none found.
  26920. */
  26921. Scene.prototype.getLightByName = function (name) {
  26922. for (var index = 0; index < this.lights.length; index++) {
  26923. if (this.lights[index].name === name) {
  26924. return this.lights[index];
  26925. }
  26926. }
  26927. return null;
  26928. };
  26929. /**
  26930. * Gets a light node using its id
  26931. * @param id defines the light's id
  26932. * @return the light or null if none found.
  26933. */
  26934. Scene.prototype.getLightByID = function (id) {
  26935. for (var index = 0; index < this.lights.length; index++) {
  26936. if (this.lights[index].id === id) {
  26937. return this.lights[index];
  26938. }
  26939. }
  26940. return null;
  26941. };
  26942. /**
  26943. * Gets a light node using its scene-generated unique ID
  26944. * @param uniqueId defines the light's unique id
  26945. * @return the light or null if none found.
  26946. */
  26947. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26948. for (var index = 0; index < this.lights.length; index++) {
  26949. if (this.lights[index].uniqueId === uniqueId) {
  26950. return this.lights[index];
  26951. }
  26952. }
  26953. return null;
  26954. };
  26955. /**
  26956. * Gets a particle system by id
  26957. * @param id defines the particle system id
  26958. * @return the corresponding system or null if none found
  26959. */
  26960. Scene.prototype.getParticleSystemByID = function (id) {
  26961. for (var index = 0; index < this.particleSystems.length; index++) {
  26962. if (this.particleSystems[index].id === id) {
  26963. return this.particleSystems[index];
  26964. }
  26965. }
  26966. return null;
  26967. };
  26968. /**
  26969. * Gets a geometry using its ID
  26970. * @param id defines the geometry's id
  26971. * @return the geometry or null if none found.
  26972. */
  26973. Scene.prototype.getGeometryByID = function (id) {
  26974. for (var index = 0; index < this.geometries.length; index++) {
  26975. if (this.geometries[index].id === id) {
  26976. return this.geometries[index];
  26977. }
  26978. }
  26979. return null;
  26980. };
  26981. /**
  26982. * Add a new geometry to this scene
  26983. * @param geometry defines the geometry to be added to the scene.
  26984. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26985. * @return a boolean defining if the geometry was added or not
  26986. */
  26987. Scene.prototype.pushGeometry = function (geometry, force) {
  26988. if (!force && this.getGeometryByID(geometry.id)) {
  26989. return false;
  26990. }
  26991. this.geometries.push(geometry);
  26992. //notify the collision coordinator
  26993. if (this.collisionCoordinator) {
  26994. this.collisionCoordinator.onGeometryAdded(geometry);
  26995. }
  26996. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26997. return true;
  26998. };
  26999. /**
  27000. * Removes an existing geometry
  27001. * @param geometry defines the geometry to be removed from the scene
  27002. * @return a boolean defining if the geometry was removed or not
  27003. */
  27004. Scene.prototype.removeGeometry = function (geometry) {
  27005. var index = this.geometries.indexOf(geometry);
  27006. if (index > -1) {
  27007. this.geometries.splice(index, 1);
  27008. //notify the collision coordinator
  27009. if (this.collisionCoordinator) {
  27010. this.collisionCoordinator.onGeometryDeleted(geometry);
  27011. }
  27012. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27013. return true;
  27014. }
  27015. return false;
  27016. };
  27017. /**
  27018. * Gets the list of geometries attached to the scene
  27019. * @returns an array of Geometry
  27020. */
  27021. Scene.prototype.getGeometries = function () {
  27022. return this.geometries;
  27023. };
  27024. /**
  27025. * Gets the first added mesh found of a given ID
  27026. * @param id defines the id to search for
  27027. * @return the mesh found or null if not found at all
  27028. */
  27029. Scene.prototype.getMeshByID = function (id) {
  27030. for (var index = 0; index < this.meshes.length; index++) {
  27031. if (this.meshes[index].id === id) {
  27032. return this.meshes[index];
  27033. }
  27034. }
  27035. return null;
  27036. };
  27037. /**
  27038. * Gets a list of meshes using their id
  27039. * @param id defines the id to search for
  27040. * @returns a list of meshes
  27041. */
  27042. Scene.prototype.getMeshesByID = function (id) {
  27043. return this.meshes.filter(function (m) {
  27044. return m.id === id;
  27045. });
  27046. };
  27047. /**
  27048. * Gets the first added transform node found of a given ID
  27049. * @param id defines the id to search for
  27050. * @return the found transform node or null if not found at all.
  27051. */
  27052. Scene.prototype.getTransformNodeByID = function (id) {
  27053. for (var index = 0; index < this.transformNodes.length; index++) {
  27054. if (this.transformNodes[index].id === id) {
  27055. return this.transformNodes[index];
  27056. }
  27057. }
  27058. return null;
  27059. };
  27060. /**
  27061. * Gets a list of transform nodes using their id
  27062. * @param id defines the id to search for
  27063. * @returns a list of transform nodes
  27064. */
  27065. Scene.prototype.getTransformNodesByID = function (id) {
  27066. return this.transformNodes.filter(function (m) {
  27067. return m.id === id;
  27068. });
  27069. };
  27070. /**
  27071. * Gets a mesh with its auto-generated unique id
  27072. * @param uniqueId defines the unique id to search for
  27073. * @return the found mesh or null if not found at all.
  27074. */
  27075. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27076. for (var index = 0; index < this.meshes.length; index++) {
  27077. if (this.meshes[index].uniqueId === uniqueId) {
  27078. return this.meshes[index];
  27079. }
  27080. }
  27081. return null;
  27082. };
  27083. /**
  27084. * Gets a the last added mesh using a given id
  27085. * @param id defines the id to search for
  27086. * @return the found mesh or null if not found at all.
  27087. */
  27088. Scene.prototype.getLastMeshByID = function (id) {
  27089. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27090. if (this.meshes[index].id === id) {
  27091. return this.meshes[index];
  27092. }
  27093. }
  27094. return null;
  27095. };
  27096. /**
  27097. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27098. * @param id defines the id to search for
  27099. * @return the found node or null if not found at all
  27100. */
  27101. Scene.prototype.getLastEntryByID = function (id) {
  27102. var index;
  27103. for (index = this.meshes.length - 1; index >= 0; index--) {
  27104. if (this.meshes[index].id === id) {
  27105. return this.meshes[index];
  27106. }
  27107. }
  27108. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27109. if (this.transformNodes[index].id === id) {
  27110. return this.transformNodes[index];
  27111. }
  27112. }
  27113. for (index = this.cameras.length - 1; index >= 0; index--) {
  27114. if (this.cameras[index].id === id) {
  27115. return this.cameras[index];
  27116. }
  27117. }
  27118. for (index = this.lights.length - 1; index >= 0; index--) {
  27119. if (this.lights[index].id === id) {
  27120. return this.lights[index];
  27121. }
  27122. }
  27123. return null;
  27124. };
  27125. /**
  27126. * Gets a node (Mesh, Camera, Light) using a given id
  27127. * @param id defines the id to search for
  27128. * @return the found node or null if not found at all
  27129. */
  27130. Scene.prototype.getNodeByID = function (id) {
  27131. var mesh = this.getMeshByID(id);
  27132. if (mesh) {
  27133. return mesh;
  27134. }
  27135. var light = this.getLightByID(id);
  27136. if (light) {
  27137. return light;
  27138. }
  27139. var camera = this.getCameraByID(id);
  27140. if (camera) {
  27141. return camera;
  27142. }
  27143. var bone = this.getBoneByID(id);
  27144. return bone;
  27145. };
  27146. /**
  27147. * Gets a node (Mesh, Camera, Light) using a given name
  27148. * @param name defines the name to search for
  27149. * @return the found node or null if not found at all.
  27150. */
  27151. Scene.prototype.getNodeByName = function (name) {
  27152. var mesh = this.getMeshByName(name);
  27153. if (mesh) {
  27154. return mesh;
  27155. }
  27156. var light = this.getLightByName(name);
  27157. if (light) {
  27158. return light;
  27159. }
  27160. var camera = this.getCameraByName(name);
  27161. if (camera) {
  27162. return camera;
  27163. }
  27164. var bone = this.getBoneByName(name);
  27165. return bone;
  27166. };
  27167. /**
  27168. * Gets a mesh using a given name
  27169. * @param name defines the name to search for
  27170. * @return the found mesh or null if not found at all.
  27171. */
  27172. Scene.prototype.getMeshByName = function (name) {
  27173. for (var index = 0; index < this.meshes.length; index++) {
  27174. if (this.meshes[index].name === name) {
  27175. return this.meshes[index];
  27176. }
  27177. }
  27178. return null;
  27179. };
  27180. /**
  27181. * Gets a transform node using a given name
  27182. * @param name defines the name to search for
  27183. * @return the found transform node or null if not found at all.
  27184. */
  27185. Scene.prototype.getTransformNodeByName = function (name) {
  27186. for (var index = 0; index < this.transformNodes.length; index++) {
  27187. if (this.transformNodes[index].name === name) {
  27188. return this.transformNodes[index];
  27189. }
  27190. }
  27191. return null;
  27192. };
  27193. /**
  27194. * Gets a sound using a given name
  27195. * @param name defines the name to search for
  27196. * @return the found sound or null if not found at all.
  27197. */
  27198. Scene.prototype.getSoundByName = function (name) {
  27199. var index;
  27200. if (BABYLON.AudioEngine) {
  27201. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27202. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27203. return this.mainSoundTrack.soundCollection[index];
  27204. }
  27205. }
  27206. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27207. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27208. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27209. return this.soundTracks[sdIndex].soundCollection[index];
  27210. }
  27211. }
  27212. }
  27213. }
  27214. return null;
  27215. };
  27216. /**
  27217. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27218. * @param id defines the id to search for
  27219. * @return the found skeleton or null if not found at all.
  27220. */
  27221. Scene.prototype.getLastSkeletonByID = function (id) {
  27222. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27223. if (this.skeletons[index].id === id) {
  27224. return this.skeletons[index];
  27225. }
  27226. }
  27227. return null;
  27228. };
  27229. /**
  27230. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27231. * @param id defines the id to search for
  27232. * @return the found skeleton or null if not found at all.
  27233. */
  27234. Scene.prototype.getSkeletonById = function (id) {
  27235. for (var index = 0; index < this.skeletons.length; index++) {
  27236. if (this.skeletons[index].id === id) {
  27237. return this.skeletons[index];
  27238. }
  27239. }
  27240. return null;
  27241. };
  27242. /**
  27243. * Gets a skeleton using a given name
  27244. * @param name defines the name to search for
  27245. * @return the found skeleton or null if not found at all.
  27246. */
  27247. Scene.prototype.getSkeletonByName = function (name) {
  27248. for (var index = 0; index < this.skeletons.length; index++) {
  27249. if (this.skeletons[index].name === name) {
  27250. return this.skeletons[index];
  27251. }
  27252. }
  27253. return null;
  27254. };
  27255. /**
  27256. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27257. * @param id defines the id to search for
  27258. * @return the found morph target manager or null if not found at all.
  27259. */
  27260. Scene.prototype.getMorphTargetManagerById = function (id) {
  27261. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27262. if (this.morphTargetManagers[index].uniqueId === id) {
  27263. return this.morphTargetManagers[index];
  27264. }
  27265. }
  27266. return null;
  27267. };
  27268. /**
  27269. * Gets a boolean indicating if the given mesh is active
  27270. * @param mesh defines the mesh to look for
  27271. * @returns true if the mesh is in the active list
  27272. */
  27273. Scene.prototype.isActiveMesh = function (mesh) {
  27274. return (this._activeMeshes.indexOf(mesh) !== -1);
  27275. };
  27276. Object.defineProperty(Scene.prototype, "uid", {
  27277. /**
  27278. * Return a unique id as a string which can serve as an identifier for the scene
  27279. */
  27280. get: function () {
  27281. if (!this._uid) {
  27282. this._uid = BABYLON.Tools.RandomId();
  27283. }
  27284. return this._uid;
  27285. },
  27286. enumerable: true,
  27287. configurable: true
  27288. });
  27289. /**
  27290. * Add an externaly attached data from its key.
  27291. * This method call will fail and return false, if such key already exists.
  27292. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27293. * @param key the unique key that identifies the data
  27294. * @param data the data object to associate to the key for this Engine instance
  27295. * @return true if no such key were already present and the data was added successfully, false otherwise
  27296. */
  27297. Scene.prototype.addExternalData = function (key, data) {
  27298. if (!this._externalData) {
  27299. this._externalData = new BABYLON.StringDictionary();
  27300. }
  27301. return this._externalData.add(key, data);
  27302. };
  27303. /**
  27304. * Get an externaly attached data from its key
  27305. * @param key the unique key that identifies the data
  27306. * @return the associated data, if present (can be null), or undefined if not present
  27307. */
  27308. Scene.prototype.getExternalData = function (key) {
  27309. if (!this._externalData) {
  27310. return null;
  27311. }
  27312. return this._externalData.get(key);
  27313. };
  27314. /**
  27315. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27316. * @param key the unique key that identifies the data
  27317. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27318. * @return the associated data, can be null if the factory returned null.
  27319. */
  27320. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27321. if (!this._externalData) {
  27322. this._externalData = new BABYLON.StringDictionary();
  27323. }
  27324. return this._externalData.getOrAddWithFactory(key, factory);
  27325. };
  27326. /**
  27327. * Remove an externaly attached data from the Engine instance
  27328. * @param key the unique key that identifies the data
  27329. * @return true if the data was successfully removed, false if it doesn't exist
  27330. */
  27331. Scene.prototype.removeExternalData = function (key) {
  27332. return this._externalData.remove(key);
  27333. };
  27334. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27335. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27336. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27337. var step = _a[_i];
  27338. step.action(mesh, subMesh);
  27339. }
  27340. var material = subMesh.getMaterial();
  27341. if (material !== null && material !== undefined) {
  27342. // Render targets
  27343. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27344. if (this._processedMaterials.indexOf(material) === -1) {
  27345. this._processedMaterials.push(material);
  27346. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27347. }
  27348. }
  27349. // Dispatch
  27350. this._activeIndices.addCount(subMesh.indexCount, false);
  27351. this._renderingManager.dispatch(subMesh, mesh, material);
  27352. }
  27353. }
  27354. };
  27355. /**
  27356. * Clear the processed materials smart array preventing retention point in material dispose.
  27357. */
  27358. Scene.prototype.freeProcessedMaterials = function () {
  27359. this._processedMaterials.dispose();
  27360. };
  27361. /**
  27362. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27363. */
  27364. Scene.prototype.freeActiveMeshes = function () {
  27365. this._activeMeshes.dispose();
  27366. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27367. this.activeCamera._activeMeshes.dispose();
  27368. }
  27369. if (this.activeCameras) {
  27370. for (var i = 0; i < this.activeCameras.length; i++) {
  27371. var activeCamera = this.activeCameras[i];
  27372. if (activeCamera && activeCamera._activeMeshes) {
  27373. activeCamera._activeMeshes.dispose();
  27374. }
  27375. }
  27376. }
  27377. };
  27378. /**
  27379. * Clear the info related to rendering groups preventing retention points during dispose.
  27380. */
  27381. Scene.prototype.freeRenderingGroups = function () {
  27382. if (this._renderingManager) {
  27383. this._renderingManager.freeRenderingGroups();
  27384. }
  27385. if (this.textures) {
  27386. for (var i = 0; i < this.textures.length; i++) {
  27387. var texture = this.textures[i];
  27388. if (texture && texture.renderList) {
  27389. texture.freeRenderingGroups();
  27390. }
  27391. }
  27392. }
  27393. };
  27394. /** @hidden */
  27395. Scene.prototype._isInIntermediateRendering = function () {
  27396. return this._intermediateRendering;
  27397. };
  27398. /**
  27399. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27400. * @returns the current scene
  27401. */
  27402. Scene.prototype.freezeActiveMeshes = function () {
  27403. if (!this.activeCamera) {
  27404. return this;
  27405. }
  27406. if (!this._frustumPlanes) {
  27407. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27408. }
  27409. this._evaluateActiveMeshes();
  27410. this._activeMeshesFrozen = true;
  27411. return this;
  27412. };
  27413. /**
  27414. * Use this function to restart evaluating active meshes on every frame
  27415. * @returns the current scene
  27416. */
  27417. Scene.prototype.unfreezeActiveMeshes = function () {
  27418. this._activeMeshesFrozen = false;
  27419. return this;
  27420. };
  27421. Scene.prototype._evaluateActiveMeshes = function () {
  27422. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27423. return;
  27424. }
  27425. if (!this.activeCamera) {
  27426. return;
  27427. }
  27428. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27429. this.activeCamera._activeMeshes.reset();
  27430. this._activeMeshes.reset();
  27431. this._renderingManager.reset();
  27432. this._processedMaterials.reset();
  27433. this._activeParticleSystems.reset();
  27434. this._activeSkeletons.reset();
  27435. this._softwareSkinnedMeshes.reset();
  27436. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27437. var step = _a[_i];
  27438. step.action();
  27439. }
  27440. // Determine mesh candidates
  27441. var meshes = this.getActiveMeshCandidates();
  27442. // Check each mesh
  27443. var len = meshes.length;
  27444. for (var i = 0; i < len; i++) {
  27445. var mesh = meshes.data[i];
  27446. if (mesh.isBlocked) {
  27447. continue;
  27448. }
  27449. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27450. if (!mesh.isReady() || !mesh.isEnabled()) {
  27451. continue;
  27452. }
  27453. mesh.computeWorldMatrix();
  27454. // Intersections
  27455. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27456. this._meshesForIntersections.pushNoDuplicate(mesh);
  27457. }
  27458. // Switch to current LOD
  27459. var meshLOD = mesh.getLOD(this.activeCamera);
  27460. if (meshLOD === undefined || meshLOD === null) {
  27461. continue;
  27462. }
  27463. mesh._preActivate();
  27464. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27465. this._activeMeshes.push(mesh);
  27466. this.activeCamera._activeMeshes.push(mesh);
  27467. mesh._activate(this._renderId);
  27468. if (meshLOD !== mesh) {
  27469. meshLOD._activate(this._renderId);
  27470. }
  27471. this._activeMesh(mesh, meshLOD);
  27472. }
  27473. }
  27474. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27475. // Particle systems
  27476. if (this.particlesEnabled) {
  27477. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27478. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27479. var particleSystem = this.particleSystems[particleIndex];
  27480. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27481. continue;
  27482. }
  27483. var emitter = particleSystem.emitter;
  27484. if (!emitter.position || emitter.isEnabled()) {
  27485. this._activeParticleSystems.push(particleSystem);
  27486. particleSystem.animate();
  27487. this._renderingManager.dispatchParticles(particleSystem);
  27488. }
  27489. }
  27490. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27491. }
  27492. };
  27493. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27494. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27495. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27496. mesh.skeleton.prepare();
  27497. }
  27498. if (!mesh.computeBonesUsingShaders) {
  27499. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27500. }
  27501. }
  27502. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27503. var step = _a[_i];
  27504. step.action(sourceMesh, mesh);
  27505. }
  27506. if (mesh !== undefined && mesh !== null
  27507. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27508. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27509. var len = subMeshes.length;
  27510. for (var i = 0; i < len; i++) {
  27511. var subMesh = subMeshes.data[i];
  27512. this._evaluateSubMesh(subMesh, mesh);
  27513. }
  27514. }
  27515. };
  27516. /**
  27517. * Update the transform matrix to update from the current active camera
  27518. * @param force defines a boolean used to force the update even if cache is up to date
  27519. */
  27520. Scene.prototype.updateTransformMatrix = function (force) {
  27521. if (!this.activeCamera) {
  27522. return;
  27523. }
  27524. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27525. };
  27526. /**
  27527. * 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)
  27528. * @param alternateCamera defines the camera to use
  27529. */
  27530. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27531. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27532. };
  27533. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27534. if (camera && camera._skipRendering) {
  27535. return;
  27536. }
  27537. var engine = this._engine;
  27538. this.activeCamera = camera;
  27539. if (!this.activeCamera)
  27540. throw new Error("Active camera not set");
  27541. // Viewport
  27542. engine.setViewport(this.activeCamera.viewport);
  27543. // Camera
  27544. this.resetCachedMaterial();
  27545. this._renderId++;
  27546. this.updateTransformMatrix();
  27547. if (camera._alternateCamera) {
  27548. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27549. this._alternateRendering = true;
  27550. }
  27551. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27552. // Meshes
  27553. this._evaluateActiveMeshes();
  27554. // Software skinning
  27555. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27556. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27557. mesh.applySkeleton(mesh.skeleton);
  27558. }
  27559. // Render targets
  27560. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27561. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27562. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27563. }
  27564. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27565. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27566. }
  27567. // Collects render targets from external components.
  27568. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27569. var step = _a[_i];
  27570. step.action(this._renderTargets);
  27571. }
  27572. if (this.renderTargetsEnabled) {
  27573. this._intermediateRendering = true;
  27574. if (this._renderTargets.length > 0) {
  27575. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27576. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27577. var renderTarget = this._renderTargets.data[renderIndex];
  27578. if (renderTarget._shouldRender()) {
  27579. this._renderId++;
  27580. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27581. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27582. }
  27583. }
  27584. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27585. this._renderId++;
  27586. }
  27587. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27588. var step = _c[_b];
  27589. step.action(this.activeCamera);
  27590. }
  27591. this._intermediateRendering = false;
  27592. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27593. }
  27594. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27595. // Prepare Frame
  27596. if (this.postProcessManager) {
  27597. this.postProcessManager._prepareFrame();
  27598. }
  27599. // Before Camera Draw
  27600. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27601. var step = _e[_d];
  27602. step.action(this.activeCamera);
  27603. }
  27604. // Render
  27605. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27606. this._renderingManager.render(null, null, true, true);
  27607. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27608. // After Camera Draw
  27609. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27610. var step = _g[_f];
  27611. step.action(this.activeCamera);
  27612. }
  27613. // Finalize frame
  27614. if (this.postProcessManager) {
  27615. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27616. }
  27617. // Reset some special arrays
  27618. this._renderTargets.reset();
  27619. this._alternateRendering = false;
  27620. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27621. };
  27622. Scene.prototype._processSubCameras = function (camera) {
  27623. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27624. this._renderForCamera(camera);
  27625. return;
  27626. }
  27627. // rig cameras
  27628. for (var index = 0; index < camera._rigCameras.length; index++) {
  27629. this._renderForCamera(camera._rigCameras[index], camera);
  27630. }
  27631. this.activeCamera = camera;
  27632. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27633. };
  27634. Scene.prototype._checkIntersections = function () {
  27635. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27636. var sourceMesh = this._meshesForIntersections.data[index];
  27637. if (!sourceMesh.actionManager) {
  27638. continue;
  27639. }
  27640. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27641. var action = sourceMesh.actionManager.actions[actionIndex];
  27642. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27643. var parameters = action.getTriggerParameter();
  27644. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27645. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27646. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27647. if (areIntersecting && currentIntersectionInProgress === -1) {
  27648. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27649. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27650. sourceMesh._intersectionsInProgress.push(otherMesh);
  27651. }
  27652. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27653. sourceMesh._intersectionsInProgress.push(otherMesh);
  27654. }
  27655. }
  27656. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27657. //They intersected, and now they don't.
  27658. //is this trigger an exit trigger? execute an event.
  27659. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27660. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27661. }
  27662. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27663. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27664. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27665. return otherMesh === parameterMesh;
  27666. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27667. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27668. }
  27669. }
  27670. }
  27671. }
  27672. }
  27673. };
  27674. /**
  27675. * Render the scene
  27676. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27677. */
  27678. Scene.prototype.render = function (updateCameras) {
  27679. if (updateCameras === void 0) { updateCameras = true; }
  27680. if (this.isDisposed) {
  27681. return;
  27682. }
  27683. this._frameId++;
  27684. // Register components that have been associated lately to the scene.
  27685. this._registerTransientComponents();
  27686. this._activeParticles.fetchNewFrame();
  27687. this._totalVertices.fetchNewFrame();
  27688. this._activeIndices.fetchNewFrame();
  27689. this._activeBones.fetchNewFrame();
  27690. this._meshesForIntersections.reset();
  27691. this.resetCachedMaterial();
  27692. this.onBeforeAnimationsObservable.notifyObservers(this);
  27693. // Actions
  27694. if (this.actionManager) {
  27695. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27696. }
  27697. if (this._engine.isDeterministicLockStep()) {
  27698. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27699. var defaultFPS = (60.0 / 1000.0);
  27700. var defaultFrameTime = 1000 / 60; // frame time in MS
  27701. if (this._physicsEngine) {
  27702. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27703. }
  27704. var stepsTaken = 0;
  27705. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27706. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27707. internalSteps = Math.min(internalSteps, maxSubSteps);
  27708. do {
  27709. this.onBeforeStepObservable.notifyObservers(this);
  27710. // Animations
  27711. this._animationRatio = defaultFrameTime * defaultFPS;
  27712. this._animate();
  27713. this.onAfterAnimationsObservable.notifyObservers(this);
  27714. // Physics
  27715. if (this._physicsEngine) {
  27716. this.onBeforePhysicsObservable.notifyObservers(this);
  27717. this._physicsEngine._step(defaultFrameTime / 1000);
  27718. this.onAfterPhysicsObservable.notifyObservers(this);
  27719. }
  27720. this.onAfterStepObservable.notifyObservers(this);
  27721. this._currentStepId++;
  27722. stepsTaken++;
  27723. deltaTime -= defaultFrameTime;
  27724. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27725. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27726. }
  27727. else {
  27728. // Animations
  27729. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27730. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27731. this._animate();
  27732. this.onAfterAnimationsObservable.notifyObservers(this);
  27733. // Physics
  27734. if (this._physicsEngine) {
  27735. this.onBeforePhysicsObservable.notifyObservers(this);
  27736. this._physicsEngine._step(deltaTime / 1000.0);
  27737. this.onAfterPhysicsObservable.notifyObservers(this);
  27738. }
  27739. }
  27740. // Before camera update steps
  27741. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27742. var step = _a[_i];
  27743. step.action();
  27744. }
  27745. // Update Cameras
  27746. if (updateCameras) {
  27747. if (this.activeCameras.length > 0) {
  27748. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27749. var camera = this.activeCameras[cameraIndex];
  27750. camera.update();
  27751. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27752. // rig cameras
  27753. for (var index = 0; index < camera._rigCameras.length; index++) {
  27754. camera._rigCameras[index].update();
  27755. }
  27756. }
  27757. }
  27758. }
  27759. else if (this.activeCamera) {
  27760. this.activeCamera.update();
  27761. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27762. // rig cameras
  27763. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27764. this.activeCamera._rigCameras[index].update();
  27765. }
  27766. }
  27767. }
  27768. }
  27769. // Before render
  27770. this.onBeforeRenderObservable.notifyObservers(this);
  27771. // Customs render targets
  27772. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27773. var engine = this.getEngine();
  27774. var currentActiveCamera = this.activeCamera;
  27775. if (this.renderTargetsEnabled) {
  27776. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27777. this._intermediateRendering = true;
  27778. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27779. var renderTarget = this.customRenderTargets[customIndex];
  27780. if (renderTarget._shouldRender()) {
  27781. this._renderId++;
  27782. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27783. if (!this.activeCamera)
  27784. throw new Error("Active camera not set");
  27785. // Viewport
  27786. engine.setViewport(this.activeCamera.viewport);
  27787. // Camera
  27788. this.updateTransformMatrix();
  27789. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27790. }
  27791. }
  27792. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27793. this._intermediateRendering = false;
  27794. this._renderId++;
  27795. }
  27796. // Restore back buffer
  27797. if (this.customRenderTargets.length > 0) {
  27798. engine.restoreDefaultFramebuffer();
  27799. }
  27800. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27801. this.activeCamera = currentActiveCamera;
  27802. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  27803. var step = _c[_b];
  27804. step.action();
  27805. }
  27806. // Clear
  27807. if (this.autoClearDepthAndStencil || this.autoClear) {
  27808. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27809. }
  27810. // Collects render targets from external components.
  27811. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  27812. var step = _e[_d];
  27813. step.action(this._renderTargets);
  27814. }
  27815. // Multi-cameras?
  27816. if (this.activeCameras.length > 0) {
  27817. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27818. if (cameraIndex > 0) {
  27819. this._engine.clear(null, false, true, true);
  27820. }
  27821. this._processSubCameras(this.activeCameras[cameraIndex]);
  27822. }
  27823. }
  27824. else {
  27825. if (!this.activeCamera) {
  27826. throw new Error("No camera defined");
  27827. }
  27828. this._processSubCameras(this.activeCamera);
  27829. }
  27830. // Intersection checks
  27831. this._checkIntersections();
  27832. // Update the audio listener attached to the camera
  27833. if (BABYLON.AudioEngine) {
  27834. this._updateAudioParameters();
  27835. }
  27836. // After render
  27837. if (this.afterRender) {
  27838. this.afterRender();
  27839. }
  27840. this.onAfterRenderObservable.notifyObservers(this);
  27841. // Cleaning
  27842. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27843. var data = this._toBeDisposed.data[index];
  27844. if (data) {
  27845. data.dispose();
  27846. }
  27847. }
  27848. this._toBeDisposed.reset();
  27849. if (this.dumpNextRenderTargets) {
  27850. this.dumpNextRenderTargets = false;
  27851. }
  27852. this._activeBones.addCount(0, true);
  27853. this._activeIndices.addCount(0, true);
  27854. this._activeParticles.addCount(0, true);
  27855. };
  27856. Scene.prototype._updateAudioParameters = function () {
  27857. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27858. return;
  27859. }
  27860. var listeningCamera;
  27861. var audioEngine = BABYLON.Engine.audioEngine;
  27862. if (this.activeCameras.length > 0) {
  27863. listeningCamera = this.activeCameras[0];
  27864. }
  27865. else {
  27866. listeningCamera = this.activeCamera;
  27867. }
  27868. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27869. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27870. // for VR cameras
  27871. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27872. listeningCamera = listeningCamera.rigCameras[0];
  27873. }
  27874. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27875. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27876. cameraDirection.normalize();
  27877. // To avoid some errors on GearVR
  27878. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27879. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27880. }
  27881. var i;
  27882. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27883. var sound = this.mainSoundTrack.soundCollection[i];
  27884. if (sound.useCustomAttenuation) {
  27885. sound.updateDistanceFromListener();
  27886. }
  27887. }
  27888. for (i = 0; i < this.soundTracks.length; i++) {
  27889. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27890. sound = this.soundTracks[i].soundCollection[j];
  27891. if (sound.useCustomAttenuation) {
  27892. sound.updateDistanceFromListener();
  27893. }
  27894. }
  27895. }
  27896. }
  27897. };
  27898. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27899. // Audio
  27900. /**
  27901. * Gets or sets if audio support is enabled
  27902. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27903. */
  27904. get: function () {
  27905. return this._audioEnabled;
  27906. },
  27907. set: function (value) {
  27908. this._audioEnabled = value;
  27909. if (BABYLON.AudioEngine) {
  27910. if (this._audioEnabled) {
  27911. this._enableAudio();
  27912. }
  27913. else {
  27914. this._disableAudio();
  27915. }
  27916. }
  27917. },
  27918. enumerable: true,
  27919. configurable: true
  27920. });
  27921. Scene.prototype._disableAudio = function () {
  27922. var i;
  27923. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27924. this.mainSoundTrack.soundCollection[i].pause();
  27925. }
  27926. for (i = 0; i < this.soundTracks.length; i++) {
  27927. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27928. this.soundTracks[i].soundCollection[j].pause();
  27929. }
  27930. }
  27931. };
  27932. Scene.prototype._enableAudio = function () {
  27933. var i;
  27934. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27935. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27936. this.mainSoundTrack.soundCollection[i].play();
  27937. }
  27938. }
  27939. for (i = 0; i < this.soundTracks.length; i++) {
  27940. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27941. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27942. this.soundTracks[i].soundCollection[j].play();
  27943. }
  27944. }
  27945. }
  27946. };
  27947. Object.defineProperty(Scene.prototype, "headphone", {
  27948. /**
  27949. * Gets or sets if audio will be output to headphones
  27950. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27951. */
  27952. get: function () {
  27953. return this._headphone;
  27954. },
  27955. set: function (value) {
  27956. this._headphone = value;
  27957. if (BABYLON.AudioEngine) {
  27958. if (this._headphone) {
  27959. this._switchAudioModeForHeadphones();
  27960. }
  27961. else {
  27962. this._switchAudioModeForNormalSpeakers();
  27963. }
  27964. }
  27965. },
  27966. enumerable: true,
  27967. configurable: true
  27968. });
  27969. Scene.prototype._switchAudioModeForHeadphones = function () {
  27970. this.mainSoundTrack.switchPanningModelToHRTF();
  27971. for (var i = 0; i < this.soundTracks.length; i++) {
  27972. this.soundTracks[i].switchPanningModelToHRTF();
  27973. }
  27974. };
  27975. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27976. this.mainSoundTrack.switchPanningModelToEqualPower();
  27977. for (var i = 0; i < this.soundTracks.length; i++) {
  27978. this.soundTracks[i].switchPanningModelToEqualPower();
  27979. }
  27980. };
  27981. /**
  27982. * Freeze all materials
  27983. * A frozen material will not be updatable but should be faster to render
  27984. */
  27985. Scene.prototype.freezeMaterials = function () {
  27986. for (var i = 0; i < this.materials.length; i++) {
  27987. this.materials[i].freeze();
  27988. }
  27989. };
  27990. /**
  27991. * Unfreeze all materials
  27992. * A frozen material will not be updatable but should be faster to render
  27993. */
  27994. Scene.prototype.unfreezeMaterials = function () {
  27995. for (var i = 0; i < this.materials.length; i++) {
  27996. this.materials[i].unfreeze();
  27997. }
  27998. };
  27999. /**
  28000. * Releases all held ressources
  28001. */
  28002. Scene.prototype.dispose = function () {
  28003. this.beforeRender = null;
  28004. this.afterRender = null;
  28005. this.skeletons = [];
  28006. this.morphTargetManagers = [];
  28007. this._transientComponents = [];
  28008. this._isReadyForMeshStage.clear();
  28009. this._beforeEvaluateActiveMeshStage.clear();
  28010. this._evaluateSubMeshStage.clear();
  28011. this._activeMeshStage.clear();
  28012. this._cameraDrawRenderTargetStage.clear();
  28013. this._beforeCameraDrawStage.clear();
  28014. this._beforeRenderingGroupDrawStage.clear();
  28015. this._beforeRenderingMeshStage.clear();
  28016. this._afterRenderingMeshStage.clear();
  28017. this._afterRenderingGroupDrawStage.clear();
  28018. this._afterCameraDrawStage.clear();
  28019. this._beforeCameraUpdateStage.clear();
  28020. this._beforeClearStage.clear();
  28021. this._gatherRenderTargetsStage.clear();
  28022. this._gatherActiveCameraRenderTargetsStage.clear();
  28023. this._pointerMoveStage.clear();
  28024. this._pointerDownStage.clear();
  28025. this._pointerUpStage.clear();
  28026. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28027. var component = _a[_i];
  28028. component.dispose();
  28029. }
  28030. this.importedMeshesFiles = new Array();
  28031. this.stopAllAnimations();
  28032. this.resetCachedMaterial();
  28033. // Smart arrays
  28034. if (this.activeCamera) {
  28035. this.activeCamera._activeMeshes.dispose();
  28036. this.activeCamera = null;
  28037. }
  28038. this._activeMeshes.dispose();
  28039. this._renderingManager.dispose();
  28040. this._processedMaterials.dispose();
  28041. this._activeParticleSystems.dispose();
  28042. this._activeSkeletons.dispose();
  28043. this._softwareSkinnedMeshes.dispose();
  28044. this._renderTargets.dispose();
  28045. this._registeredForLateAnimationBindings.dispose();
  28046. this._meshesForIntersections.dispose();
  28047. this._toBeDisposed.dispose();
  28048. // Abort active requests
  28049. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28050. var request = _c[_b];
  28051. request.abort();
  28052. }
  28053. // Events
  28054. this.onDisposeObservable.notifyObservers(this);
  28055. this.onDisposeObservable.clear();
  28056. this.onBeforeRenderObservable.clear();
  28057. this.onAfterRenderObservable.clear();
  28058. this.onBeforeRenderTargetsRenderObservable.clear();
  28059. this.onAfterRenderTargetsRenderObservable.clear();
  28060. this.onAfterStepObservable.clear();
  28061. this.onBeforeStepObservable.clear();
  28062. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28063. this.onAfterActiveMeshesEvaluationObservable.clear();
  28064. this.onBeforeParticlesRenderingObservable.clear();
  28065. this.onAfterParticlesRenderingObservable.clear();
  28066. this.onBeforeDrawPhaseObservable.clear();
  28067. this.onAfterDrawPhaseObservable.clear();
  28068. this.onBeforePhysicsObservable.clear();
  28069. this.onAfterPhysicsObservable.clear();
  28070. this.onBeforeAnimationsObservable.clear();
  28071. this.onAfterAnimationsObservable.clear();
  28072. this.onDataLoadedObservable.clear();
  28073. this.onBeforeRenderingGroupObservable.clear();
  28074. this.onAfterRenderingGroupObservable.clear();
  28075. this.onMeshImportedObservable.clear();
  28076. this.detachControl();
  28077. // Release sounds & sounds tracks
  28078. if (BABYLON.AudioEngine) {
  28079. this.disposeSounds();
  28080. }
  28081. // Detach cameras
  28082. var canvas = this._engine.getRenderingCanvas();
  28083. if (canvas) {
  28084. var index;
  28085. for (index = 0; index < this.cameras.length; index++) {
  28086. this.cameras[index].detachControl(canvas);
  28087. }
  28088. }
  28089. // Release animation groups
  28090. while (this.animationGroups.length) {
  28091. this.animationGroups[0].dispose();
  28092. }
  28093. // Release lights
  28094. while (this.lights.length) {
  28095. this.lights[0].dispose();
  28096. }
  28097. // Release meshes
  28098. while (this.meshes.length) {
  28099. this.meshes[0].dispose(true);
  28100. }
  28101. while (this.transformNodes.length) {
  28102. this.removeTransformNode(this.transformNodes[0]);
  28103. }
  28104. // Release cameras
  28105. while (this.cameras.length) {
  28106. this.cameras[0].dispose();
  28107. }
  28108. // Release materials
  28109. if (this.defaultMaterial) {
  28110. this.defaultMaterial.dispose();
  28111. }
  28112. while (this.multiMaterials.length) {
  28113. this.multiMaterials[0].dispose();
  28114. }
  28115. while (this.materials.length) {
  28116. this.materials[0].dispose();
  28117. }
  28118. // Release particles
  28119. while (this.particleSystems.length) {
  28120. this.particleSystems[0].dispose();
  28121. }
  28122. // Release postProcesses
  28123. while (this.postProcesses.length) {
  28124. this.postProcesses[0].dispose();
  28125. }
  28126. // Release textures
  28127. while (this.textures.length) {
  28128. this.textures[0].dispose();
  28129. }
  28130. // Release UBO
  28131. this._sceneUbo.dispose();
  28132. if (this._alternateSceneUbo) {
  28133. this._alternateSceneUbo.dispose();
  28134. }
  28135. // Post-processes
  28136. this.postProcessManager.dispose();
  28137. // Physics
  28138. if (this._physicsEngine) {
  28139. this.disablePhysicsEngine();
  28140. }
  28141. // Remove from engine
  28142. index = this._engine.scenes.indexOf(this);
  28143. if (index > -1) {
  28144. this._engine.scenes.splice(index, 1);
  28145. }
  28146. this._engine.wipeCaches(true);
  28147. this._isDisposed = true;
  28148. };
  28149. Object.defineProperty(Scene.prototype, "isDisposed", {
  28150. /**
  28151. * Gets if the scene is already disposed
  28152. */
  28153. get: function () {
  28154. return this._isDisposed;
  28155. },
  28156. enumerable: true,
  28157. configurable: true
  28158. });
  28159. /**
  28160. * Releases sounds & soundtracks
  28161. */
  28162. Scene.prototype.disposeSounds = function () {
  28163. if (!this._mainSoundTrack) {
  28164. return;
  28165. }
  28166. this.mainSoundTrack.dispose();
  28167. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28168. this.soundTracks[scIndex].dispose();
  28169. }
  28170. };
  28171. /**
  28172. * Call this function to reduce memory footprint of the scene.
  28173. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28174. */
  28175. Scene.prototype.clearCachedVertexData = function () {
  28176. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28177. var mesh = this.meshes[meshIndex];
  28178. var geometry = mesh.geometry;
  28179. if (geometry) {
  28180. geometry._indices = [];
  28181. for (var vbName in geometry._vertexBuffers) {
  28182. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28183. continue;
  28184. }
  28185. geometry._vertexBuffers[vbName]._buffer._data = null;
  28186. }
  28187. }
  28188. }
  28189. };
  28190. /**
  28191. * This function will remove the local cached buffer data from texture.
  28192. * It will save memory but will prevent the texture from being rebuilt
  28193. */
  28194. Scene.prototype.cleanCachedTextureBuffer = function () {
  28195. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28196. var baseTexture = _a[_i];
  28197. var buffer = baseTexture._buffer;
  28198. if (buffer) {
  28199. baseTexture._buffer = null;
  28200. }
  28201. }
  28202. };
  28203. /**
  28204. * Get the world extend vectors with an optional filter
  28205. *
  28206. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28207. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28208. */
  28209. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28210. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28211. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28212. filterPredicate = filterPredicate || (function () { return true; });
  28213. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28214. mesh.computeWorldMatrix(true);
  28215. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28216. return;
  28217. }
  28218. var boundingInfo = mesh.getBoundingInfo();
  28219. var minBox = boundingInfo.boundingBox.minimumWorld;
  28220. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28221. BABYLON.Tools.CheckExtends(minBox, min, max);
  28222. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28223. });
  28224. return {
  28225. min: min,
  28226. max: max
  28227. };
  28228. };
  28229. // Picking
  28230. /**
  28231. * Creates a ray that can be used to pick in the scene
  28232. * @param x defines the x coordinate of the origin (on-screen)
  28233. * @param y defines the y coordinate of the origin (on-screen)
  28234. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28235. * @param camera defines the camera to use for the picking
  28236. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28237. * @returns a Ray
  28238. */
  28239. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28240. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28241. var result = BABYLON.Ray.Zero();
  28242. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28243. return result;
  28244. };
  28245. /**
  28246. * Creates a ray that can be used to pick in the scene
  28247. * @param x defines the x coordinate of the origin (on-screen)
  28248. * @param y defines the y coordinate of the origin (on-screen)
  28249. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28250. * @param result defines the ray where to store the picking ray
  28251. * @param camera defines the camera to use for the picking
  28252. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28253. * @returns the current scene
  28254. */
  28255. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28256. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28257. var engine = this._engine;
  28258. if (!camera) {
  28259. if (!this.activeCamera)
  28260. throw new Error("Active camera not set");
  28261. camera = this.activeCamera;
  28262. }
  28263. var cameraViewport = camera.viewport;
  28264. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28265. // Moving coordinates to local viewport world
  28266. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28267. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28268. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28269. return this;
  28270. };
  28271. /**
  28272. * Creates a ray that can be used to pick in the scene
  28273. * @param x defines the x coordinate of the origin (on-screen)
  28274. * @param y defines the y coordinate of the origin (on-screen)
  28275. * @param camera defines the camera to use for the picking
  28276. * @returns a Ray
  28277. */
  28278. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28279. var result = BABYLON.Ray.Zero();
  28280. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28281. return result;
  28282. };
  28283. /**
  28284. * Creates a ray that can be used to pick in the scene
  28285. * @param x defines the x coordinate of the origin (on-screen)
  28286. * @param y defines the y coordinate of the origin (on-screen)
  28287. * @param result defines the ray where to store the picking ray
  28288. * @param camera defines the camera to use for the picking
  28289. * @returns the current scene
  28290. */
  28291. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28292. if (!BABYLON.PickingInfo) {
  28293. return this;
  28294. }
  28295. var engine = this._engine;
  28296. if (!camera) {
  28297. if (!this.activeCamera)
  28298. throw new Error("Active camera not set");
  28299. camera = this.activeCamera;
  28300. }
  28301. var cameraViewport = camera.viewport;
  28302. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28303. var identity = BABYLON.Matrix.Identity();
  28304. // Moving coordinates to local viewport world
  28305. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28306. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28307. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28308. return this;
  28309. };
  28310. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28311. if (!BABYLON.PickingInfo) {
  28312. return null;
  28313. }
  28314. var pickingInfo = null;
  28315. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28316. var mesh = this.meshes[meshIndex];
  28317. if (predicate) {
  28318. if (!predicate(mesh)) {
  28319. continue;
  28320. }
  28321. }
  28322. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28323. continue;
  28324. }
  28325. var world = mesh.getWorldMatrix();
  28326. var ray = rayFunction(world);
  28327. var result = mesh.intersects(ray, fastCheck);
  28328. if (!result || !result.hit)
  28329. continue;
  28330. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28331. continue;
  28332. pickingInfo = result;
  28333. if (fastCheck) {
  28334. break;
  28335. }
  28336. }
  28337. return pickingInfo || new BABYLON.PickingInfo();
  28338. };
  28339. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28340. if (!BABYLON.PickingInfo) {
  28341. return null;
  28342. }
  28343. var pickingInfos = new Array();
  28344. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28345. var mesh = this.meshes[meshIndex];
  28346. if (predicate) {
  28347. if (!predicate(mesh)) {
  28348. continue;
  28349. }
  28350. }
  28351. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28352. continue;
  28353. }
  28354. var world = mesh.getWorldMatrix();
  28355. var ray = rayFunction(world);
  28356. var result = mesh.intersects(ray, false);
  28357. if (!result || !result.hit)
  28358. continue;
  28359. pickingInfos.push(result);
  28360. }
  28361. return pickingInfos;
  28362. };
  28363. /** Launch a ray to try to pick a mesh in the scene
  28364. * @param x position on screen
  28365. * @param y position on screen
  28366. * @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
  28367. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28368. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28369. * @returns a PickingInfo
  28370. */
  28371. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28372. var _this = this;
  28373. if (!BABYLON.PickingInfo) {
  28374. return null;
  28375. }
  28376. var result = this._internalPick(function (world) {
  28377. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28378. return _this._tempPickingRay;
  28379. }, predicate, fastCheck);
  28380. if (result) {
  28381. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28382. }
  28383. return result;
  28384. };
  28385. /** Use the given ray to pick a mesh in the scene
  28386. * @param ray The ray to use to pick meshes
  28387. * @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
  28388. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28389. * @returns a PickingInfo
  28390. */
  28391. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28392. var _this = this;
  28393. var result = this._internalPick(function (world) {
  28394. if (!_this._pickWithRayInverseMatrix) {
  28395. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28396. }
  28397. world.invertToRef(_this._pickWithRayInverseMatrix);
  28398. if (!_this._cachedRayForTransform) {
  28399. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28400. }
  28401. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28402. return _this._cachedRayForTransform;
  28403. }, predicate, fastCheck);
  28404. if (result) {
  28405. result.ray = ray;
  28406. }
  28407. return result;
  28408. };
  28409. /**
  28410. * Launch a ray to try to pick a mesh in the scene
  28411. * @param x X position on screen
  28412. * @param y Y position on screen
  28413. * @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
  28414. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28415. * @returns an array of PickingInfo
  28416. */
  28417. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28418. var _this = this;
  28419. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28420. };
  28421. /**
  28422. * Launch a ray to try to pick a mesh in the scene
  28423. * @param ray Ray to use
  28424. * @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
  28425. * @returns an array of PickingInfo
  28426. */
  28427. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28428. var _this = this;
  28429. return this._internalMultiPick(function (world) {
  28430. if (!_this._pickWithRayInverseMatrix) {
  28431. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28432. }
  28433. world.invertToRef(_this._pickWithRayInverseMatrix);
  28434. if (!_this._cachedRayForTransform) {
  28435. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28436. }
  28437. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28438. return _this._cachedRayForTransform;
  28439. }, predicate);
  28440. };
  28441. /**
  28442. * Force the value of meshUnderPointer
  28443. * @param mesh defines the mesh to use
  28444. */
  28445. Scene.prototype.setPointerOverMesh = function (mesh) {
  28446. if (this._pointerOverMesh === mesh) {
  28447. return;
  28448. }
  28449. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28450. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28451. }
  28452. this._pointerOverMesh = mesh;
  28453. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28454. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28455. }
  28456. };
  28457. /**
  28458. * Gets the mesh under the pointer
  28459. * @returns a Mesh or null if no mesh is under the pointer
  28460. */
  28461. Scene.prototype.getPointerOverMesh = function () {
  28462. return this._pointerOverMesh;
  28463. };
  28464. // Physics
  28465. /**
  28466. * Gets the current physics engine
  28467. * @returns a PhysicsEngine or null if none attached
  28468. */
  28469. Scene.prototype.getPhysicsEngine = function () {
  28470. return this._physicsEngine;
  28471. };
  28472. /**
  28473. * Enables physics to the current scene
  28474. * @param gravity defines the scene's gravity for the physics engine
  28475. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28476. * @return a boolean indicating if the physics engine was initialized
  28477. */
  28478. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28479. if (gravity === void 0) { gravity = null; }
  28480. if (this._physicsEngine) {
  28481. return true;
  28482. }
  28483. try {
  28484. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28485. return true;
  28486. }
  28487. catch (e) {
  28488. BABYLON.Tools.Error(e.message);
  28489. return false;
  28490. }
  28491. };
  28492. /**
  28493. * Disables and disposes the physics engine associated with the scene
  28494. */
  28495. Scene.prototype.disablePhysicsEngine = function () {
  28496. if (!this._physicsEngine) {
  28497. return;
  28498. }
  28499. this._physicsEngine.dispose();
  28500. this._physicsEngine = null;
  28501. };
  28502. /**
  28503. * Gets a boolean indicating if there is an active physics engine
  28504. * @returns a boolean indicating if there is an active physics engine
  28505. */
  28506. Scene.prototype.isPhysicsEnabled = function () {
  28507. return this._physicsEngine !== undefined;
  28508. };
  28509. /**
  28510. * Deletes a physics compound impostor
  28511. * @param compound defines the compound to delete
  28512. */
  28513. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28514. var mesh = compound.parts[0].mesh;
  28515. if (mesh.physicsImpostor) {
  28516. mesh.physicsImpostor.dispose( /*true*/);
  28517. mesh.physicsImpostor = null;
  28518. }
  28519. };
  28520. // Misc.
  28521. /** @hidden */
  28522. Scene.prototype._rebuildGeometries = function () {
  28523. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28524. var geometry = _a[_i];
  28525. geometry._rebuild();
  28526. }
  28527. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28528. var mesh = _c[_b];
  28529. mesh._rebuild();
  28530. }
  28531. if (this.postProcessManager) {
  28532. this.postProcessManager._rebuild();
  28533. }
  28534. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28535. var component = _e[_d];
  28536. component.rebuild();
  28537. }
  28538. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28539. var system = _g[_f];
  28540. system.rebuild();
  28541. }
  28542. };
  28543. /** @hidden */
  28544. Scene.prototype._rebuildTextures = function () {
  28545. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28546. var texture = _a[_i];
  28547. texture._rebuild();
  28548. }
  28549. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28550. };
  28551. // Tags
  28552. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28553. if (tagsQuery === undefined) {
  28554. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28555. return list;
  28556. }
  28557. var listByTags = [];
  28558. forEach = forEach || (function (item) { return; });
  28559. for (var i in list) {
  28560. var item = list[i];
  28561. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28562. listByTags.push(item);
  28563. forEach(item);
  28564. }
  28565. }
  28566. return listByTags;
  28567. };
  28568. /**
  28569. * Get a list of meshes by tags
  28570. * @param tagsQuery defines the tags query to use
  28571. * @param forEach defines a predicate used to filter results
  28572. * @returns an array of Mesh
  28573. */
  28574. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28575. return this._getByTags(this.meshes, tagsQuery, forEach);
  28576. };
  28577. /**
  28578. * Get a list of cameras by tags
  28579. * @param tagsQuery defines the tags query to use
  28580. * @param forEach defines a predicate used to filter results
  28581. * @returns an array of Camera
  28582. */
  28583. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28584. return this._getByTags(this.cameras, tagsQuery, forEach);
  28585. };
  28586. /**
  28587. * Get a list of lights by tags
  28588. * @param tagsQuery defines the tags query to use
  28589. * @param forEach defines a predicate used to filter results
  28590. * @returns an array of Light
  28591. */
  28592. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28593. return this._getByTags(this.lights, tagsQuery, forEach);
  28594. };
  28595. /**
  28596. * Get a list of materials by tags
  28597. * @param tagsQuery defines the tags query to use
  28598. * @param forEach defines a predicate used to filter results
  28599. * @returns an array of Material
  28600. */
  28601. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28602. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28603. };
  28604. /**
  28605. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28606. * This allowed control for front to back rendering or reversly depending of the special needs.
  28607. *
  28608. * @param renderingGroupId The rendering group id corresponding to its index
  28609. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28610. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28611. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28612. */
  28613. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28614. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28615. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28616. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28617. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28618. };
  28619. /**
  28620. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28621. *
  28622. * @param renderingGroupId The rendering group id corresponding to its index
  28623. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28624. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28625. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28626. */
  28627. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28628. if (depth === void 0) { depth = true; }
  28629. if (stencil === void 0) { stencil = true; }
  28630. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28631. };
  28632. /**
  28633. * Gets the current auto clear configuration for one rendering group of the rendering
  28634. * manager.
  28635. * @param index the rendering group index to get the information for
  28636. * @returns The auto clear setup for the requested rendering group
  28637. */
  28638. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28639. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28640. };
  28641. /**
  28642. * Will flag all materials as dirty to trigger new shader compilation
  28643. * @param flag defines the flag used to specify which material part must be marked as dirty
  28644. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28645. */
  28646. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28647. if (this.blockMaterialDirtyMechanism) {
  28648. return;
  28649. }
  28650. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28651. var material = _a[_i];
  28652. if (predicate && !predicate(material)) {
  28653. continue;
  28654. }
  28655. material.markAsDirty(flag);
  28656. }
  28657. };
  28658. /** @hidden */
  28659. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28660. var _this = this;
  28661. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28662. this._activeRequests.push(request);
  28663. request.onCompleteObservable.add(function (request) {
  28664. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28665. });
  28666. return request;
  28667. };
  28668. /** @hidden */
  28669. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28670. var _this = this;
  28671. return new Promise(function (resolve, reject) {
  28672. _this._loadFile(url, function (data) {
  28673. resolve(data);
  28674. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28675. reject(exception);
  28676. });
  28677. });
  28678. };
  28679. // Statics
  28680. Scene._uniqueIdCounter = 0;
  28681. /** The fog is deactivated */
  28682. Scene.FOGMODE_NONE = 0;
  28683. /** The fog density is following an exponential function */
  28684. Scene.FOGMODE_EXP = 1;
  28685. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28686. Scene.FOGMODE_EXP2 = 2;
  28687. /** The fog density is following a linear function. */
  28688. Scene.FOGMODE_LINEAR = 3;
  28689. /**
  28690. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28691. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28692. */
  28693. Scene.MinDeltaTime = 1.0;
  28694. /**
  28695. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28696. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28697. */
  28698. Scene.MaxDeltaTime = 1000.0;
  28699. /** The distance in pixel that you have to move to prevent some events */
  28700. Scene.DragMovementThreshold = 10; // in pixels
  28701. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28702. Scene.LongPressDelay = 500; // in milliseconds
  28703. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28704. Scene.DoubleClickDelay = 300; // in milliseconds
  28705. /** If you need to check double click without raising a single click at first click, enable this flag */
  28706. Scene.ExclusiveDoubleClickMode = false;
  28707. return Scene;
  28708. }(BABYLON.AbstractScene));
  28709. BABYLON.Scene = Scene;
  28710. })(BABYLON || (BABYLON = {}));
  28711. //# sourceMappingURL=babylon.scene.js.map
  28712. var BABYLON;
  28713. (function (BABYLON) {
  28714. /**
  28715. * Set of assets to keep when moving a scene into an asset container.
  28716. */
  28717. var KeepAssets = /** @class */ (function (_super) {
  28718. __extends(KeepAssets, _super);
  28719. function KeepAssets() {
  28720. return _super !== null && _super.apply(this, arguments) || this;
  28721. }
  28722. return KeepAssets;
  28723. }(BABYLON.AbstractScene));
  28724. BABYLON.KeepAssets = KeepAssets;
  28725. /**
  28726. * Container with a set of assets that can be added or removed from a scene.
  28727. */
  28728. var AssetContainer = /** @class */ (function (_super) {
  28729. __extends(AssetContainer, _super);
  28730. /**
  28731. * Instantiates an AssetContainer.
  28732. * @param scene The scene the AssetContainer belongs to.
  28733. */
  28734. function AssetContainer(scene) {
  28735. var _this = _super.call(this) || this;
  28736. _this.scene = scene;
  28737. return _this;
  28738. }
  28739. /**
  28740. * Adds all the assets from the container to the scene.
  28741. */
  28742. AssetContainer.prototype.addAllToScene = function () {
  28743. var _this = this;
  28744. this.cameras.forEach(function (o) {
  28745. _this.scene.addCamera(o);
  28746. });
  28747. this.lights.forEach(function (o) {
  28748. _this.scene.addLight(o);
  28749. });
  28750. this.meshes.forEach(function (o) {
  28751. _this.scene.addMesh(o);
  28752. });
  28753. this.skeletons.forEach(function (o) {
  28754. _this.scene.addSkeleton(o);
  28755. });
  28756. this.animations.forEach(function (o) {
  28757. _this.scene.addAnimation(o);
  28758. });
  28759. this.animationGroups.forEach(function (o) {
  28760. _this.scene.addAnimationGroup(o);
  28761. });
  28762. this.multiMaterials.forEach(function (o) {
  28763. _this.scene.addMultiMaterial(o);
  28764. });
  28765. this.materials.forEach(function (o) {
  28766. _this.scene.addMaterial(o);
  28767. });
  28768. this.morphTargetManagers.forEach(function (o) {
  28769. _this.scene.addMorphTargetManager(o);
  28770. });
  28771. this.geometries.forEach(function (o) {
  28772. _this.scene.addGeometry(o);
  28773. });
  28774. this.transformNodes.forEach(function (o) {
  28775. _this.scene.addTransformNode(o);
  28776. });
  28777. this.actionManagers.forEach(function (o) {
  28778. _this.scene.addActionManager(o);
  28779. });
  28780. this.sounds.forEach(function (o) {
  28781. o.play();
  28782. o.autoplay = true;
  28783. _this.scene.mainSoundTrack.AddSound(o);
  28784. });
  28785. this.textures.forEach(function (o) {
  28786. _this.scene.addTexture(o);
  28787. });
  28788. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28789. var component = _a[_i];
  28790. component.addFromContainer(this.scene);
  28791. }
  28792. };
  28793. /**
  28794. * Removes all the assets in the container from the scene
  28795. */
  28796. AssetContainer.prototype.removeAllFromScene = function () {
  28797. var _this = this;
  28798. this.cameras.forEach(function (o) {
  28799. _this.scene.removeCamera(o);
  28800. });
  28801. this.lights.forEach(function (o) {
  28802. _this.scene.removeLight(o);
  28803. });
  28804. this.meshes.forEach(function (o) {
  28805. _this.scene.removeMesh(o);
  28806. });
  28807. this.skeletons.forEach(function (o) {
  28808. _this.scene.removeSkeleton(o);
  28809. });
  28810. this.animations.forEach(function (o) {
  28811. _this.scene.removeAnimation(o);
  28812. });
  28813. this.animationGroups.forEach(function (o) {
  28814. _this.scene.removeAnimationGroup(o);
  28815. });
  28816. this.multiMaterials.forEach(function (o) {
  28817. _this.scene.removeMultiMaterial(o);
  28818. });
  28819. this.materials.forEach(function (o) {
  28820. _this.scene.removeMaterial(o);
  28821. });
  28822. this.morphTargetManagers.forEach(function (o) {
  28823. _this.scene.removeMorphTargetManager(o);
  28824. });
  28825. this.geometries.forEach(function (o) {
  28826. _this.scene.removeGeometry(o);
  28827. });
  28828. this.transformNodes.forEach(function (o) {
  28829. _this.scene.removeTransformNode(o);
  28830. });
  28831. this.actionManagers.forEach(function (o) {
  28832. _this.scene.removeActionManager(o);
  28833. });
  28834. this.sounds.forEach(function (o) {
  28835. o.stop();
  28836. o.autoplay = false;
  28837. _this.scene.mainSoundTrack.RemoveSound(o);
  28838. });
  28839. this.textures.forEach(function (o) {
  28840. _this.scene.removeTexture(o);
  28841. });
  28842. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28843. var component = _a[_i];
  28844. component.removeFromContainer(this.scene);
  28845. }
  28846. };
  28847. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28848. if (!sourceAssets) {
  28849. return;
  28850. }
  28851. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28852. var asset = sourceAssets_1[_i];
  28853. var move = true;
  28854. if (keepAssets) {
  28855. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28856. var keepAsset = keepAssets_1[_a];
  28857. if (asset === keepAsset) {
  28858. move = false;
  28859. break;
  28860. }
  28861. }
  28862. }
  28863. if (move) {
  28864. targetAssets.push(asset);
  28865. }
  28866. }
  28867. };
  28868. /**
  28869. * Removes all the assets contained in the scene and adds them to the container.
  28870. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28871. */
  28872. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28873. if (keepAssets === undefined) {
  28874. keepAssets = new KeepAssets();
  28875. }
  28876. for (var key in this) {
  28877. if (this.hasOwnProperty(key)) {
  28878. this[key] = this[key] || [];
  28879. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28880. }
  28881. }
  28882. this.removeAllFromScene();
  28883. };
  28884. /**
  28885. * 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.
  28886. * @returns the root mesh
  28887. */
  28888. AssetContainer.prototype.createRootMesh = function () {
  28889. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28890. this.meshes.forEach(function (m) {
  28891. if (!m.parent) {
  28892. rootMesh.addChild(m);
  28893. }
  28894. });
  28895. this.meshes.unshift(rootMesh);
  28896. return rootMesh;
  28897. };
  28898. return AssetContainer;
  28899. }(BABYLON.AbstractScene));
  28900. BABYLON.AssetContainer = AssetContainer;
  28901. })(BABYLON || (BABYLON = {}));
  28902. //# sourceMappingURL=babylon.assetContainer.js.map
  28903. var BABYLON;
  28904. (function (BABYLON) {
  28905. var Buffer = /** @class */ (function () {
  28906. /**
  28907. * Constructor
  28908. * @param engine the engine
  28909. * @param data the data to use for this buffer
  28910. * @param updatable whether the data is updatable
  28911. * @param stride the stride (optional)
  28912. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28913. * @param instanced whether the buffer is instanced (optional)
  28914. * @param useBytes set to true if the stride in in bytes (optional)
  28915. */
  28916. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28917. if (stride === void 0) { stride = 0; }
  28918. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28919. if (instanced === void 0) { instanced = false; }
  28920. if (useBytes === void 0) { useBytes = false; }
  28921. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28922. this._engine = engine.getScene().getEngine();
  28923. }
  28924. else {
  28925. this._engine = engine;
  28926. }
  28927. this._updatable = updatable;
  28928. this._instanced = instanced;
  28929. this._data = data;
  28930. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28931. if (!postponeInternalCreation) { // by default
  28932. this.create();
  28933. }
  28934. }
  28935. /**
  28936. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28937. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28938. * @param offset defines offset in the buffer (0 by default)
  28939. * @param size defines the size in floats of attributes (position is 3 for instance)
  28940. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28941. * @param instanced defines if the vertex buffer contains indexed data
  28942. * @param useBytes defines if the offset and stride are in bytes
  28943. * @returns the new vertex buffer
  28944. */
  28945. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28946. if (useBytes === void 0) { useBytes = false; }
  28947. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28948. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28949. // a lot of these parameters are ignored as they are overriden by the buffer
  28950. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28951. };
  28952. // Properties
  28953. Buffer.prototype.isUpdatable = function () {
  28954. return this._updatable;
  28955. };
  28956. Buffer.prototype.getData = function () {
  28957. return this._data;
  28958. };
  28959. Buffer.prototype.getBuffer = function () {
  28960. return this._buffer;
  28961. };
  28962. /**
  28963. * Gets the stride in float32 units (i.e. byte stride / 4).
  28964. * May not be an integer if the byte stride is not divisible by 4.
  28965. * DEPRECATED. Use byteStride instead.
  28966. * @returns the stride in float32 units
  28967. */
  28968. Buffer.prototype.getStrideSize = function () {
  28969. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28970. };
  28971. // Methods
  28972. Buffer.prototype.create = function (data) {
  28973. if (data === void 0) { data = null; }
  28974. if (!data && this._buffer) {
  28975. return; // nothing to do
  28976. }
  28977. data = data || this._data;
  28978. if (!data) {
  28979. return;
  28980. }
  28981. if (!this._buffer) { // create buffer
  28982. if (this._updatable) {
  28983. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28984. this._data = data;
  28985. }
  28986. else {
  28987. this._buffer = this._engine.createVertexBuffer(data);
  28988. }
  28989. }
  28990. else if (this._updatable) { // update buffer
  28991. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28992. this._data = data;
  28993. }
  28994. };
  28995. /** @hidden */
  28996. Buffer.prototype._rebuild = function () {
  28997. this._buffer = null;
  28998. this.create(this._data);
  28999. };
  29000. Buffer.prototype.update = function (data) {
  29001. this.create(data);
  29002. };
  29003. /**
  29004. * Updates the data directly.
  29005. * @param data the new data
  29006. * @param offset the new offset
  29007. * @param vertexCount the vertex count (optional)
  29008. * @param useBytes set to true if the offset is in bytes
  29009. */
  29010. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29011. if (useBytes === void 0) { useBytes = false; }
  29012. if (!this._buffer) {
  29013. return;
  29014. }
  29015. if (this._updatable) { // update buffer
  29016. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29017. this._data = null;
  29018. }
  29019. };
  29020. Buffer.prototype.dispose = function () {
  29021. if (!this._buffer) {
  29022. return;
  29023. }
  29024. if (this._engine._releaseBuffer(this._buffer)) {
  29025. this._buffer = null;
  29026. }
  29027. };
  29028. return Buffer;
  29029. }());
  29030. BABYLON.Buffer = Buffer;
  29031. })(BABYLON || (BABYLON = {}));
  29032. //# sourceMappingURL=babylon.buffer.js.map
  29033. var BABYLON;
  29034. (function (BABYLON) {
  29035. var VertexBuffer = /** @class */ (function () {
  29036. /**
  29037. * Constructor
  29038. * @param engine the engine
  29039. * @param data the data to use for this vertex buffer
  29040. * @param kind the vertex buffer kind
  29041. * @param updatable whether the data is updatable
  29042. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29043. * @param stride the stride (optional)
  29044. * @param instanced whether the buffer is instanced (optional)
  29045. * @param offset the offset of the data (optional)
  29046. * @param size the number of components (optional)
  29047. * @param type the type of the component (optional)
  29048. * @param normalized whether the data contains normalized data (optional)
  29049. * @param useBytes set to true if stride and offset are in bytes (optional)
  29050. */
  29051. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29052. if (normalized === void 0) { normalized = false; }
  29053. if (useBytes === void 0) { useBytes = false; }
  29054. if (data instanceof BABYLON.Buffer) {
  29055. this._buffer = data;
  29056. this._ownsBuffer = false;
  29057. }
  29058. else {
  29059. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29060. this._ownsBuffer = true;
  29061. }
  29062. this._kind = kind;
  29063. if (type == undefined) {
  29064. var data_1 = this.getData();
  29065. this.type = VertexBuffer.FLOAT;
  29066. if (data_1 instanceof Int8Array)
  29067. this.type = VertexBuffer.BYTE;
  29068. else if (data_1 instanceof Uint8Array)
  29069. this.type = VertexBuffer.UNSIGNED_BYTE;
  29070. else if (data_1 instanceof Int16Array)
  29071. this.type = VertexBuffer.SHORT;
  29072. else if (data_1 instanceof Uint16Array)
  29073. this.type = VertexBuffer.UNSIGNED_SHORT;
  29074. else if (data_1 instanceof Int32Array)
  29075. this.type = VertexBuffer.INT;
  29076. else if (data_1 instanceof Uint32Array)
  29077. this.type = VertexBuffer.UNSIGNED_INT;
  29078. }
  29079. else {
  29080. this.type = type;
  29081. }
  29082. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29083. if (useBytes) {
  29084. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29085. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29086. this.byteOffset = offset || 0;
  29087. }
  29088. else {
  29089. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29090. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29091. this.byteOffset = (offset || 0) * typeByteLength;
  29092. }
  29093. this.normalized = normalized;
  29094. this._instanced = instanced !== undefined ? instanced : false;
  29095. this._instanceDivisor = instanced ? 1 : 0;
  29096. }
  29097. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29098. /**
  29099. * Gets or sets the instance divisor when in instanced mode
  29100. */
  29101. get: function () {
  29102. return this._instanceDivisor;
  29103. },
  29104. set: function (value) {
  29105. this._instanceDivisor = value;
  29106. if (value == 0) {
  29107. this._instanced = false;
  29108. }
  29109. else {
  29110. this._instanced = true;
  29111. }
  29112. },
  29113. enumerable: true,
  29114. configurable: true
  29115. });
  29116. /** @hidden */
  29117. VertexBuffer.prototype._rebuild = function () {
  29118. if (!this._buffer) {
  29119. return;
  29120. }
  29121. this._buffer._rebuild();
  29122. };
  29123. /**
  29124. * Returns the kind of the VertexBuffer (string).
  29125. */
  29126. VertexBuffer.prototype.getKind = function () {
  29127. return this._kind;
  29128. };
  29129. // Properties
  29130. /**
  29131. * Boolean : is the VertexBuffer updatable ?
  29132. */
  29133. VertexBuffer.prototype.isUpdatable = function () {
  29134. return this._buffer.isUpdatable();
  29135. };
  29136. /**
  29137. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29138. */
  29139. VertexBuffer.prototype.getData = function () {
  29140. return this._buffer.getData();
  29141. };
  29142. /**
  29143. * Returns the WebGLBuffer associated to the VertexBuffer.
  29144. */
  29145. VertexBuffer.prototype.getBuffer = function () {
  29146. return this._buffer.getBuffer();
  29147. };
  29148. /**
  29149. * Returns the stride as a multiple of the type byte length.
  29150. * DEPRECATED. Use byteStride instead.
  29151. */
  29152. VertexBuffer.prototype.getStrideSize = function () {
  29153. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29154. };
  29155. /**
  29156. * Returns the offset as a multiple of the type byte length.
  29157. * DEPRECATED. Use byteOffset instead.
  29158. */
  29159. VertexBuffer.prototype.getOffset = function () {
  29160. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29161. };
  29162. /**
  29163. * Returns the number of components per vertex attribute (integer).
  29164. */
  29165. VertexBuffer.prototype.getSize = function () {
  29166. return this._size;
  29167. };
  29168. /**
  29169. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29170. */
  29171. VertexBuffer.prototype.getIsInstanced = function () {
  29172. return this._instanced;
  29173. };
  29174. /**
  29175. * Returns the instancing divisor, zero for non-instanced (integer).
  29176. */
  29177. VertexBuffer.prototype.getInstanceDivisor = function () {
  29178. return this._instanceDivisor;
  29179. };
  29180. // Methods
  29181. /**
  29182. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29183. * Returns the created WebGLBuffer.
  29184. */
  29185. VertexBuffer.prototype.create = function (data) {
  29186. return this._buffer.create(data);
  29187. };
  29188. /**
  29189. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29190. * This function will create a new buffer if the current one is not updatable
  29191. * Returns the updated WebGLBuffer.
  29192. */
  29193. VertexBuffer.prototype.update = function (data) {
  29194. return this._buffer.update(data);
  29195. };
  29196. /**
  29197. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29198. * Returns the directly updated WebGLBuffer.
  29199. * @param data the new data
  29200. * @param offset the new offset
  29201. * @param useBytes set to true if the offset is in bytes
  29202. */
  29203. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29204. if (useBytes === void 0) { useBytes = false; }
  29205. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29206. };
  29207. /**
  29208. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29209. */
  29210. VertexBuffer.prototype.dispose = function () {
  29211. if (this._ownsBuffer) {
  29212. this._buffer.dispose();
  29213. }
  29214. };
  29215. /**
  29216. * Enumerates each value of this vertex buffer as numbers.
  29217. * @param count the number of values to enumerate
  29218. * @param callback the callback function called for each value
  29219. */
  29220. VertexBuffer.prototype.forEach = function (count, callback) {
  29221. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29222. };
  29223. Object.defineProperty(VertexBuffer, "PositionKind", {
  29224. get: function () {
  29225. return VertexBuffer._PositionKind;
  29226. },
  29227. enumerable: true,
  29228. configurable: true
  29229. });
  29230. Object.defineProperty(VertexBuffer, "NormalKind", {
  29231. get: function () {
  29232. return VertexBuffer._NormalKind;
  29233. },
  29234. enumerable: true,
  29235. configurable: true
  29236. });
  29237. Object.defineProperty(VertexBuffer, "TangentKind", {
  29238. get: function () {
  29239. return VertexBuffer._TangentKind;
  29240. },
  29241. enumerable: true,
  29242. configurable: true
  29243. });
  29244. Object.defineProperty(VertexBuffer, "UVKind", {
  29245. get: function () {
  29246. return VertexBuffer._UVKind;
  29247. },
  29248. enumerable: true,
  29249. configurable: true
  29250. });
  29251. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29252. get: function () {
  29253. return VertexBuffer._UV2Kind;
  29254. },
  29255. enumerable: true,
  29256. configurable: true
  29257. });
  29258. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29259. get: function () {
  29260. return VertexBuffer._UV3Kind;
  29261. },
  29262. enumerable: true,
  29263. configurable: true
  29264. });
  29265. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29266. get: function () {
  29267. return VertexBuffer._UV4Kind;
  29268. },
  29269. enumerable: true,
  29270. configurable: true
  29271. });
  29272. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29273. get: function () {
  29274. return VertexBuffer._UV5Kind;
  29275. },
  29276. enumerable: true,
  29277. configurable: true
  29278. });
  29279. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29280. get: function () {
  29281. return VertexBuffer._UV6Kind;
  29282. },
  29283. enumerable: true,
  29284. configurable: true
  29285. });
  29286. Object.defineProperty(VertexBuffer, "ColorKind", {
  29287. get: function () {
  29288. return VertexBuffer._ColorKind;
  29289. },
  29290. enumerable: true,
  29291. configurable: true
  29292. });
  29293. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29294. get: function () {
  29295. return VertexBuffer._MatricesIndicesKind;
  29296. },
  29297. enumerable: true,
  29298. configurable: true
  29299. });
  29300. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29301. get: function () {
  29302. return VertexBuffer._MatricesWeightsKind;
  29303. },
  29304. enumerable: true,
  29305. configurable: true
  29306. });
  29307. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29308. get: function () {
  29309. return VertexBuffer._MatricesIndicesExtraKind;
  29310. },
  29311. enumerable: true,
  29312. configurable: true
  29313. });
  29314. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29315. get: function () {
  29316. return VertexBuffer._MatricesWeightsExtraKind;
  29317. },
  29318. enumerable: true,
  29319. configurable: true
  29320. });
  29321. /**
  29322. * Deduces the stride given a kind.
  29323. * @param kind The kind string to deduce
  29324. * @returns The deduced stride
  29325. */
  29326. VertexBuffer.DeduceStride = function (kind) {
  29327. switch (kind) {
  29328. case VertexBuffer.UVKind:
  29329. case VertexBuffer.UV2Kind:
  29330. case VertexBuffer.UV3Kind:
  29331. case VertexBuffer.UV4Kind:
  29332. case VertexBuffer.UV5Kind:
  29333. case VertexBuffer.UV6Kind:
  29334. return 2;
  29335. case VertexBuffer.NormalKind:
  29336. case VertexBuffer.PositionKind:
  29337. return 3;
  29338. case VertexBuffer.ColorKind:
  29339. case VertexBuffer.MatricesIndicesKind:
  29340. case VertexBuffer.MatricesIndicesExtraKind:
  29341. case VertexBuffer.MatricesWeightsKind:
  29342. case VertexBuffer.MatricesWeightsExtraKind:
  29343. case VertexBuffer.TangentKind:
  29344. return 4;
  29345. default:
  29346. throw new Error("Invalid kind '" + kind + "'");
  29347. }
  29348. };
  29349. /**
  29350. * Gets the byte length of the given type.
  29351. * @param type the type
  29352. * @returns the number of bytes
  29353. */
  29354. VertexBuffer.GetTypeByteLength = function (type) {
  29355. switch (type) {
  29356. case VertexBuffer.BYTE:
  29357. case VertexBuffer.UNSIGNED_BYTE:
  29358. return 1;
  29359. case VertexBuffer.SHORT:
  29360. case VertexBuffer.UNSIGNED_SHORT:
  29361. return 2;
  29362. case VertexBuffer.INT:
  29363. case VertexBuffer.FLOAT:
  29364. return 4;
  29365. default:
  29366. throw new Error("Invalid type '" + type + "'");
  29367. }
  29368. };
  29369. /**
  29370. * Enumerates each value of the given parameters as numbers.
  29371. * @param data the data to enumerate
  29372. * @param byteOffset the byte offset of the data
  29373. * @param byteStride the byte stride of the data
  29374. * @param componentCount the number of components per element
  29375. * @param componentType the type of the component
  29376. * @param count the total number of components
  29377. * @param normalized whether the data is normalized
  29378. * @param callback the callback function called for each value
  29379. */
  29380. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29381. if (data instanceof Array) {
  29382. var offset = byteOffset / 4;
  29383. var stride = byteStride / 4;
  29384. for (var index = 0; index < count; index += componentCount) {
  29385. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29386. callback(data[offset + componentIndex], index + componentIndex);
  29387. }
  29388. offset += stride;
  29389. }
  29390. }
  29391. else {
  29392. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29393. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29394. for (var index = 0; index < count; index += componentCount) {
  29395. var componentByteOffset = byteOffset;
  29396. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29397. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29398. callback(value, index + componentIndex);
  29399. componentByteOffset += componentByteLength;
  29400. }
  29401. byteOffset += byteStride;
  29402. }
  29403. }
  29404. };
  29405. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29406. switch (type) {
  29407. case VertexBuffer.BYTE: {
  29408. var value = dataView.getInt8(byteOffset);
  29409. if (normalized) {
  29410. value = Math.max(value / 127, -1);
  29411. }
  29412. return value;
  29413. }
  29414. case VertexBuffer.UNSIGNED_BYTE: {
  29415. var value = dataView.getUint8(byteOffset);
  29416. if (normalized) {
  29417. value = value / 255;
  29418. }
  29419. return value;
  29420. }
  29421. case VertexBuffer.SHORT: {
  29422. var value = dataView.getInt16(byteOffset, true);
  29423. if (normalized) {
  29424. value = Math.max(value / 16383, -1);
  29425. }
  29426. return value;
  29427. }
  29428. case VertexBuffer.UNSIGNED_SHORT: {
  29429. var value = dataView.getUint16(byteOffset, true);
  29430. if (normalized) {
  29431. value = value / 65535;
  29432. }
  29433. return value;
  29434. }
  29435. case VertexBuffer.FLOAT: {
  29436. return dataView.getFloat32(byteOffset, true);
  29437. }
  29438. default: {
  29439. throw new Error("Invalid component type " + type);
  29440. }
  29441. }
  29442. };
  29443. /**
  29444. * The byte type.
  29445. */
  29446. VertexBuffer.BYTE = 5120;
  29447. /**
  29448. * The unsigned byte type.
  29449. */
  29450. VertexBuffer.UNSIGNED_BYTE = 5121;
  29451. /**
  29452. * The short type.
  29453. */
  29454. VertexBuffer.SHORT = 5122;
  29455. /**
  29456. * The unsigned short type.
  29457. */
  29458. VertexBuffer.UNSIGNED_SHORT = 5123;
  29459. /**
  29460. * The integer type.
  29461. */
  29462. VertexBuffer.INT = 5124;
  29463. /**
  29464. * The unsigned integer type.
  29465. */
  29466. VertexBuffer.UNSIGNED_INT = 5125;
  29467. /**
  29468. * The float type.
  29469. */
  29470. VertexBuffer.FLOAT = 5126;
  29471. // Enums
  29472. VertexBuffer._PositionKind = "position";
  29473. VertexBuffer._NormalKind = "normal";
  29474. VertexBuffer._TangentKind = "tangent";
  29475. VertexBuffer._UVKind = "uv";
  29476. VertexBuffer._UV2Kind = "uv2";
  29477. VertexBuffer._UV3Kind = "uv3";
  29478. VertexBuffer._UV4Kind = "uv4";
  29479. VertexBuffer._UV5Kind = "uv5";
  29480. VertexBuffer._UV6Kind = "uv6";
  29481. VertexBuffer._ColorKind = "color";
  29482. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29483. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29484. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29485. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29486. return VertexBuffer;
  29487. }());
  29488. BABYLON.VertexBuffer = VertexBuffer;
  29489. })(BABYLON || (BABYLON = {}));
  29490. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29491. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29492. var BABYLON;
  29493. (function (BABYLON) {
  29494. /**
  29495. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29496. */
  29497. var DummyInternalTextureTracker = /** @class */ (function () {
  29498. function DummyInternalTextureTracker() {
  29499. /**
  29500. * Gets or set the previous tracker in the list
  29501. */
  29502. this.previous = null;
  29503. /**
  29504. * Gets or set the next tracker in the list
  29505. */
  29506. this.next = null;
  29507. }
  29508. return DummyInternalTextureTracker;
  29509. }());
  29510. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29511. })(BABYLON || (BABYLON = {}));
  29512. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29513. var BABYLON;
  29514. (function (BABYLON) {
  29515. /**
  29516. * Class used to store data associated with WebGL texture data for the engine
  29517. * This class should not be used directly
  29518. */
  29519. var InternalTexture = /** @class */ (function () {
  29520. /**
  29521. * Creates a new InternalTexture
  29522. * @param engine defines the engine to use
  29523. * @param dataSource defines the type of data that will be used
  29524. */
  29525. function InternalTexture(engine, dataSource) {
  29526. /**
  29527. * Observable called when the texture is loaded
  29528. */
  29529. this.onLoadedObservable = new BABYLON.Observable();
  29530. /**
  29531. * Gets or set the previous tracker in the list
  29532. */
  29533. this.previous = null;
  29534. /**
  29535. * Gets or set the next tracker in the list
  29536. */
  29537. this.next = null;
  29538. // Private
  29539. /** @hidden */
  29540. this._initialSlot = -1;
  29541. /** @hidden */
  29542. this._designatedSlot = -1;
  29543. /** @hidden */
  29544. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29545. /** @hidden */
  29546. this._comparisonFunction = 0;
  29547. /** @hidden */
  29548. this._sphericalPolynomial = null;
  29549. /** @hidden */
  29550. this._lodGenerationScale = 0;
  29551. /** @hidden */
  29552. this._lodGenerationOffset = 0;
  29553. /** @hidden */
  29554. this._isRGBD = false;
  29555. /** @hidden */
  29556. this._references = 1;
  29557. this._engine = engine;
  29558. this._dataSource = dataSource;
  29559. this._webGLTexture = engine._createTexture();
  29560. }
  29561. /**
  29562. * Gets the Engine the texture belongs to.
  29563. * @returns The babylon engine
  29564. */
  29565. InternalTexture.prototype.getEngine = function () {
  29566. return this._engine;
  29567. };
  29568. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29569. /**
  29570. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29571. */
  29572. get: function () {
  29573. return this._dataSource;
  29574. },
  29575. enumerable: true,
  29576. configurable: true
  29577. });
  29578. /**
  29579. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29580. */
  29581. InternalTexture.prototype.incrementReferences = function () {
  29582. this._references++;
  29583. };
  29584. /**
  29585. * Change the size of the texture (not the size of the content)
  29586. * @param width defines the new width
  29587. * @param height defines the new height
  29588. * @param depth defines the new depth (1 by default)
  29589. */
  29590. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29591. if (depth === void 0) { depth = 1; }
  29592. this.width = width;
  29593. this.height = height;
  29594. this.depth = depth;
  29595. this.baseWidth = width;
  29596. this.baseHeight = height;
  29597. this.baseDepth = depth;
  29598. this._size = width * height * depth;
  29599. };
  29600. /** @hidden */
  29601. InternalTexture.prototype._rebuild = function () {
  29602. var _this = this;
  29603. var proxy;
  29604. this.isReady = false;
  29605. this._cachedCoordinatesMode = null;
  29606. this._cachedWrapU = null;
  29607. this._cachedWrapV = null;
  29608. this._cachedAnisotropicFilteringLevel = null;
  29609. switch (this._dataSource) {
  29610. case InternalTexture.DATASOURCE_TEMP:
  29611. return;
  29612. case InternalTexture.DATASOURCE_URL:
  29613. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29614. _this.isReady = true;
  29615. }, null, this._buffer, undefined, this.format);
  29616. proxy._swapAndDie(this);
  29617. return;
  29618. case InternalTexture.DATASOURCE_RAW:
  29619. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29620. proxy._swapAndDie(this);
  29621. this.isReady = true;
  29622. return;
  29623. case InternalTexture.DATASOURCE_RAW3D:
  29624. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29625. proxy._swapAndDie(this);
  29626. this.isReady = true;
  29627. return;
  29628. case InternalTexture.DATASOURCE_DYNAMIC:
  29629. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29630. proxy._swapAndDie(this);
  29631. // The engine will make sure to update content so no need to flag it as isReady = true
  29632. return;
  29633. case InternalTexture.DATASOURCE_RENDERTARGET:
  29634. var options = new BABYLON.RenderTargetCreationOptions();
  29635. options.generateDepthBuffer = this._generateDepthBuffer;
  29636. options.generateMipMaps = this.generateMipMaps;
  29637. options.generateStencilBuffer = this._generateStencilBuffer;
  29638. options.samplingMode = this.samplingMode;
  29639. options.type = this.type;
  29640. if (this.isCube) {
  29641. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29642. }
  29643. else {
  29644. var size = {
  29645. width: this.width,
  29646. height: this.height
  29647. };
  29648. proxy = this._engine.createRenderTargetTexture(size, options);
  29649. }
  29650. proxy._swapAndDie(this);
  29651. this.isReady = true;
  29652. return;
  29653. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29654. var depthTextureOptions = {
  29655. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29656. comparisonFunction: this._comparisonFunction,
  29657. generateStencil: this._generateStencilBuffer,
  29658. isCube: this.isCube
  29659. };
  29660. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29661. proxy._swapAndDie(this);
  29662. this.isReady = true;
  29663. return;
  29664. case InternalTexture.DATASOURCE_CUBE:
  29665. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29666. _this.isReady = true;
  29667. }, null, this.format, this._extension);
  29668. proxy._swapAndDie(this);
  29669. return;
  29670. case InternalTexture.DATASOURCE_CUBERAW:
  29671. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29672. proxy._swapAndDie(this);
  29673. this.isReady = true;
  29674. return;
  29675. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29676. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29677. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29678. _this.isReady = true;
  29679. });
  29680. proxy._swapAndDie(this);
  29681. return;
  29682. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29683. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29684. if (proxy) {
  29685. proxy._swapAndDie(_this);
  29686. }
  29687. _this.isReady = true;
  29688. }, null, this.format, this._extension);
  29689. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29690. return;
  29691. }
  29692. };
  29693. /** @hidden */
  29694. InternalTexture.prototype._swapAndDie = function (target) {
  29695. target._webGLTexture = this._webGLTexture;
  29696. if (this._framebuffer) {
  29697. target._framebuffer = this._framebuffer;
  29698. }
  29699. if (this._depthStencilBuffer) {
  29700. target._depthStencilBuffer = this._depthStencilBuffer;
  29701. }
  29702. if (this._lodTextureHigh) {
  29703. if (target._lodTextureHigh) {
  29704. target._lodTextureHigh.dispose();
  29705. }
  29706. target._lodTextureHigh = this._lodTextureHigh;
  29707. }
  29708. if (this._lodTextureMid) {
  29709. if (target._lodTextureMid) {
  29710. target._lodTextureMid.dispose();
  29711. }
  29712. target._lodTextureMid = this._lodTextureMid;
  29713. }
  29714. if (this._lodTextureLow) {
  29715. if (target._lodTextureLow) {
  29716. target._lodTextureLow.dispose();
  29717. }
  29718. target._lodTextureLow = this._lodTextureLow;
  29719. }
  29720. var cache = this._engine.getLoadedTexturesCache();
  29721. var index = cache.indexOf(this);
  29722. if (index !== -1) {
  29723. cache.splice(index, 1);
  29724. }
  29725. };
  29726. /**
  29727. * Dispose the current allocated resources
  29728. */
  29729. InternalTexture.prototype.dispose = function () {
  29730. if (!this._webGLTexture) {
  29731. return;
  29732. }
  29733. this._references--;
  29734. if (this._references === 0) {
  29735. this._engine._releaseTexture(this);
  29736. this._webGLTexture = null;
  29737. this.previous = null;
  29738. this.next = null;
  29739. }
  29740. };
  29741. /**
  29742. * The source of the texture data is unknown
  29743. */
  29744. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29745. /**
  29746. * Texture data comes from an URL
  29747. */
  29748. InternalTexture.DATASOURCE_URL = 1;
  29749. /**
  29750. * Texture data is only used for temporary storage
  29751. */
  29752. InternalTexture.DATASOURCE_TEMP = 2;
  29753. /**
  29754. * Texture data comes from raw data (ArrayBuffer)
  29755. */
  29756. InternalTexture.DATASOURCE_RAW = 3;
  29757. /**
  29758. * Texture content is dynamic (video or dynamic texture)
  29759. */
  29760. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29761. /**
  29762. * Texture content is generated by rendering to it
  29763. */
  29764. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29765. /**
  29766. * Texture content is part of a multi render target process
  29767. */
  29768. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29769. /**
  29770. * Texture data comes from a cube data file
  29771. */
  29772. InternalTexture.DATASOURCE_CUBE = 7;
  29773. /**
  29774. * Texture data comes from a raw cube data
  29775. */
  29776. InternalTexture.DATASOURCE_CUBERAW = 8;
  29777. /**
  29778. * Texture data come from a prefiltered cube data file
  29779. */
  29780. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29781. /**
  29782. * Texture content is raw 3D data
  29783. */
  29784. InternalTexture.DATASOURCE_RAW3D = 10;
  29785. /**
  29786. * Texture content is a depth texture
  29787. */
  29788. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29789. /**
  29790. * Texture data comes from a raw cube data encoded with RGBD
  29791. */
  29792. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29793. return InternalTexture;
  29794. }());
  29795. BABYLON.InternalTexture = InternalTexture;
  29796. })(BABYLON || (BABYLON = {}));
  29797. //# sourceMappingURL=babylon.internalTexture.js.map
  29798. var BABYLON;
  29799. (function (BABYLON) {
  29800. var BaseTexture = /** @class */ (function () {
  29801. function BaseTexture(scene) {
  29802. this._hasAlpha = false;
  29803. this.getAlphaFromRGB = false;
  29804. this.level = 1;
  29805. this.coordinatesIndex = 0;
  29806. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29807. /**
  29808. * | Value | Type | Description |
  29809. * | ----- | ------------------ | ----------- |
  29810. * | 0 | CLAMP_ADDRESSMODE | |
  29811. * | 1 | WRAP_ADDRESSMODE | |
  29812. * | 2 | MIRROR_ADDRESSMODE | |
  29813. */
  29814. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29815. /**
  29816. * | Value | Type | Description |
  29817. * | ----- | ------------------ | ----------- |
  29818. * | 0 | CLAMP_ADDRESSMODE | |
  29819. * | 1 | WRAP_ADDRESSMODE | |
  29820. * | 2 | MIRROR_ADDRESSMODE | |
  29821. */
  29822. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29823. /**
  29824. * | Value | Type | Description |
  29825. * | ----- | ------------------ | ----------- |
  29826. * | 0 | CLAMP_ADDRESSMODE | |
  29827. * | 1 | WRAP_ADDRESSMODE | |
  29828. * | 2 | MIRROR_ADDRESSMODE | |
  29829. */
  29830. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29831. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29832. this.isCube = false;
  29833. this.is3D = false;
  29834. this.gammaSpace = true;
  29835. this.invertZ = false;
  29836. this.lodLevelInAlpha = false;
  29837. this.isRenderTarget = false;
  29838. this.animations = new Array();
  29839. /**
  29840. * An event triggered when the texture is disposed.
  29841. */
  29842. this.onDisposeObservable = new BABYLON.Observable();
  29843. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29844. this._cachedSize = BABYLON.Size.Zero();
  29845. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29846. if (this._scene) {
  29847. this._scene.textures.push(this);
  29848. }
  29849. this._uid = null;
  29850. }
  29851. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29852. get: function () {
  29853. return this._hasAlpha;
  29854. },
  29855. set: function (value) {
  29856. if (this._hasAlpha === value) {
  29857. return;
  29858. }
  29859. this._hasAlpha = value;
  29860. if (this._scene) {
  29861. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29862. }
  29863. },
  29864. enumerable: true,
  29865. configurable: true
  29866. });
  29867. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29868. get: function () {
  29869. return this._coordinatesMode;
  29870. },
  29871. /**
  29872. * How a texture is mapped.
  29873. *
  29874. * | Value | Type | Description |
  29875. * | ----- | ----------------------------------- | ----------- |
  29876. * | 0 | EXPLICIT_MODE | |
  29877. * | 1 | SPHERICAL_MODE | |
  29878. * | 2 | PLANAR_MODE | |
  29879. * | 3 | CUBIC_MODE | |
  29880. * | 4 | PROJECTION_MODE | |
  29881. * | 5 | SKYBOX_MODE | |
  29882. * | 6 | INVCUBIC_MODE | |
  29883. * | 7 | EQUIRECTANGULAR_MODE | |
  29884. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29885. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29886. */
  29887. set: function (value) {
  29888. if (this._coordinatesMode === value) {
  29889. return;
  29890. }
  29891. this._coordinatesMode = value;
  29892. if (this._scene) {
  29893. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29894. }
  29895. },
  29896. enumerable: true,
  29897. configurable: true
  29898. });
  29899. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29900. /**
  29901. * Gets whether or not the texture contains RGBD data.
  29902. */
  29903. get: function () {
  29904. return this._texture != null && this._texture._isRGBD;
  29905. },
  29906. enumerable: true,
  29907. configurable: true
  29908. });
  29909. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29910. get: function () {
  29911. if (this._texture)
  29912. return this._texture._lodGenerationOffset;
  29913. return 0.0;
  29914. },
  29915. set: function (value) {
  29916. if (this._texture)
  29917. this._texture._lodGenerationOffset = value;
  29918. },
  29919. enumerable: true,
  29920. configurable: true
  29921. });
  29922. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29923. get: function () {
  29924. if (this._texture)
  29925. return this._texture._lodGenerationScale;
  29926. return 0.0;
  29927. },
  29928. set: function (value) {
  29929. if (this._texture)
  29930. this._texture._lodGenerationScale = value;
  29931. },
  29932. enumerable: true,
  29933. configurable: true
  29934. });
  29935. Object.defineProperty(BaseTexture.prototype, "uid", {
  29936. get: function () {
  29937. if (!this._uid) {
  29938. this._uid = BABYLON.Tools.RandomId();
  29939. }
  29940. return this._uid;
  29941. },
  29942. enumerable: true,
  29943. configurable: true
  29944. });
  29945. BaseTexture.prototype.toString = function () {
  29946. return this.name;
  29947. };
  29948. BaseTexture.prototype.getClassName = function () {
  29949. return "BaseTexture";
  29950. };
  29951. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29952. set: function (callback) {
  29953. if (this._onDisposeObserver) {
  29954. this.onDisposeObservable.remove(this._onDisposeObserver);
  29955. }
  29956. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29957. },
  29958. enumerable: true,
  29959. configurable: true
  29960. });
  29961. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29962. get: function () {
  29963. return true;
  29964. },
  29965. enumerable: true,
  29966. configurable: true
  29967. });
  29968. BaseTexture.prototype.getScene = function () {
  29969. return this._scene;
  29970. };
  29971. BaseTexture.prototype.getTextureMatrix = function () {
  29972. return BABYLON.Matrix.IdentityReadOnly;
  29973. };
  29974. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29975. return BABYLON.Matrix.IdentityReadOnly;
  29976. };
  29977. BaseTexture.prototype.getInternalTexture = function () {
  29978. return this._texture;
  29979. };
  29980. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29981. return !this.isBlocking || this.isReady();
  29982. };
  29983. BaseTexture.prototype.isReady = function () {
  29984. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29985. this.delayLoad();
  29986. return false;
  29987. }
  29988. if (this._texture) {
  29989. return this._texture.isReady;
  29990. }
  29991. return false;
  29992. };
  29993. BaseTexture.prototype.getSize = function () {
  29994. if (this._texture) {
  29995. if (this._texture.width) {
  29996. this._cachedSize.width = this._texture.width;
  29997. this._cachedSize.height = this._texture.height;
  29998. return this._cachedSize;
  29999. }
  30000. if (this._texture._size) {
  30001. this._cachedSize.width = this._texture._size;
  30002. this._cachedSize.height = this._texture._size;
  30003. return this._cachedSize;
  30004. }
  30005. }
  30006. return this._cachedSize;
  30007. };
  30008. BaseTexture.prototype.getBaseSize = function () {
  30009. if (!this.isReady() || !this._texture)
  30010. return BABYLON.Size.Zero();
  30011. if (this._texture._size) {
  30012. return new BABYLON.Size(this._texture._size, this._texture._size);
  30013. }
  30014. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30015. };
  30016. BaseTexture.prototype.scale = function (ratio) {
  30017. };
  30018. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30019. get: function () {
  30020. return false;
  30021. },
  30022. enumerable: true,
  30023. configurable: true
  30024. });
  30025. /** @hidden */
  30026. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30027. if (!this._scene) {
  30028. return null;
  30029. }
  30030. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30031. for (var index = 0; index < texturesCache.length; index++) {
  30032. var texturesCacheEntry = texturesCache[index];
  30033. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30034. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30035. texturesCacheEntry.incrementReferences();
  30036. return texturesCacheEntry;
  30037. }
  30038. }
  30039. }
  30040. return null;
  30041. };
  30042. /** @hidden */
  30043. BaseTexture.prototype._rebuild = function () {
  30044. };
  30045. BaseTexture.prototype.delayLoad = function () {
  30046. };
  30047. BaseTexture.prototype.clone = function () {
  30048. return null;
  30049. };
  30050. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30051. get: function () {
  30052. if (!this._texture) {
  30053. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30054. }
  30055. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30056. },
  30057. enumerable: true,
  30058. configurable: true
  30059. });
  30060. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30061. get: function () {
  30062. if (!this._texture) {
  30063. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30064. }
  30065. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30066. },
  30067. enumerable: true,
  30068. configurable: true
  30069. });
  30070. /**
  30071. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30072. * This will returns an RGBA array buffer containing either in values (0-255) or
  30073. * float values (0-1) depending of the underlying buffer type.
  30074. * @param faceIndex The face of the texture to read (in case of cube texture)
  30075. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30076. * @returns The Array buffer containing the pixels data.
  30077. */
  30078. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30079. if (faceIndex === void 0) { faceIndex = 0; }
  30080. if (level === void 0) { level = 0; }
  30081. if (!this._texture) {
  30082. return null;
  30083. }
  30084. var size = this.getSize();
  30085. var width = size.width;
  30086. var height = size.height;
  30087. var scene = this.getScene();
  30088. if (!scene) {
  30089. return null;
  30090. }
  30091. var engine = scene.getEngine();
  30092. if (level != 0) {
  30093. width = width / Math.pow(2, level);
  30094. height = height / Math.pow(2, level);
  30095. width = Math.round(width);
  30096. height = Math.round(height);
  30097. }
  30098. if (this._texture.isCube) {
  30099. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30100. }
  30101. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30102. };
  30103. BaseTexture.prototype.releaseInternalTexture = function () {
  30104. if (this._texture) {
  30105. this._texture.dispose();
  30106. this._texture = null;
  30107. }
  30108. };
  30109. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30110. get: function () {
  30111. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30112. return null;
  30113. }
  30114. if (!this._texture._sphericalPolynomial) {
  30115. this._texture._sphericalPolynomial =
  30116. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30117. }
  30118. return this._texture._sphericalPolynomial;
  30119. },
  30120. set: function (value) {
  30121. if (this._texture) {
  30122. this._texture._sphericalPolynomial = value;
  30123. }
  30124. },
  30125. enumerable: true,
  30126. configurable: true
  30127. });
  30128. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30129. get: function () {
  30130. if (this._texture) {
  30131. return this._texture._lodTextureHigh;
  30132. }
  30133. return null;
  30134. },
  30135. enumerable: true,
  30136. configurable: true
  30137. });
  30138. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30139. get: function () {
  30140. if (this._texture) {
  30141. return this._texture._lodTextureMid;
  30142. }
  30143. return null;
  30144. },
  30145. enumerable: true,
  30146. configurable: true
  30147. });
  30148. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30149. get: function () {
  30150. if (this._texture) {
  30151. return this._texture._lodTextureLow;
  30152. }
  30153. return null;
  30154. },
  30155. enumerable: true,
  30156. configurable: true
  30157. });
  30158. BaseTexture.prototype.dispose = function () {
  30159. if (!this._scene) {
  30160. return;
  30161. }
  30162. // Animations
  30163. this._scene.stopAnimation(this);
  30164. // Remove from scene
  30165. this._scene._removePendingData(this);
  30166. var index = this._scene.textures.indexOf(this);
  30167. if (index >= 0) {
  30168. this._scene.textures.splice(index, 1);
  30169. }
  30170. if (this._texture === undefined) {
  30171. return;
  30172. }
  30173. // Release
  30174. this.releaseInternalTexture();
  30175. // Callback
  30176. this.onDisposeObservable.notifyObservers(this);
  30177. this.onDisposeObservable.clear();
  30178. };
  30179. BaseTexture.prototype.serialize = function () {
  30180. if (!this.name) {
  30181. return null;
  30182. }
  30183. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30184. // Animations
  30185. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30186. return serializationObject;
  30187. };
  30188. BaseTexture.WhenAllReady = function (textures, callback) {
  30189. var numRemaining = textures.length;
  30190. if (numRemaining === 0) {
  30191. callback();
  30192. return;
  30193. }
  30194. var _loop_1 = function () {
  30195. texture = textures[i];
  30196. if (texture.isReady()) {
  30197. if (--numRemaining === 0) {
  30198. callback();
  30199. }
  30200. }
  30201. else {
  30202. onLoadObservable = texture.onLoadObservable;
  30203. var onLoadCallback_1 = function () {
  30204. onLoadObservable.removeCallback(onLoadCallback_1);
  30205. if (--numRemaining === 0) {
  30206. callback();
  30207. }
  30208. };
  30209. onLoadObservable.add(onLoadCallback_1);
  30210. }
  30211. };
  30212. var texture, onLoadObservable;
  30213. for (var i = 0; i < textures.length; i++) {
  30214. _loop_1();
  30215. }
  30216. };
  30217. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30218. __decorate([
  30219. BABYLON.serialize()
  30220. ], BaseTexture.prototype, "name", void 0);
  30221. __decorate([
  30222. BABYLON.serialize("hasAlpha")
  30223. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30224. __decorate([
  30225. BABYLON.serialize()
  30226. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30227. __decorate([
  30228. BABYLON.serialize()
  30229. ], BaseTexture.prototype, "level", void 0);
  30230. __decorate([
  30231. BABYLON.serialize()
  30232. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30233. __decorate([
  30234. BABYLON.serialize("coordinatesMode")
  30235. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30236. __decorate([
  30237. BABYLON.serialize()
  30238. ], BaseTexture.prototype, "wrapU", void 0);
  30239. __decorate([
  30240. BABYLON.serialize()
  30241. ], BaseTexture.prototype, "wrapV", void 0);
  30242. __decorate([
  30243. BABYLON.serialize()
  30244. ], BaseTexture.prototype, "wrapR", void 0);
  30245. __decorate([
  30246. BABYLON.serialize()
  30247. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30248. __decorate([
  30249. BABYLON.serialize()
  30250. ], BaseTexture.prototype, "isCube", void 0);
  30251. __decorate([
  30252. BABYLON.serialize()
  30253. ], BaseTexture.prototype, "is3D", void 0);
  30254. __decorate([
  30255. BABYLON.serialize()
  30256. ], BaseTexture.prototype, "gammaSpace", void 0);
  30257. __decorate([
  30258. BABYLON.serialize()
  30259. ], BaseTexture.prototype, "invertZ", void 0);
  30260. __decorate([
  30261. BABYLON.serialize()
  30262. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30263. __decorate([
  30264. BABYLON.serialize()
  30265. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30266. __decorate([
  30267. BABYLON.serialize()
  30268. ], BaseTexture.prototype, "lodGenerationScale", null);
  30269. __decorate([
  30270. BABYLON.serialize()
  30271. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30272. return BaseTexture;
  30273. }());
  30274. BABYLON.BaseTexture = BaseTexture;
  30275. })(BABYLON || (BABYLON = {}));
  30276. //# sourceMappingURL=babylon.baseTexture.js.map
  30277. var BABYLON;
  30278. (function (BABYLON) {
  30279. var Texture = /** @class */ (function (_super) {
  30280. __extends(Texture, _super);
  30281. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30282. if (noMipmap === void 0) { noMipmap = false; }
  30283. if (invertY === void 0) { invertY = true; }
  30284. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30285. if (onLoad === void 0) { onLoad = null; }
  30286. if (onError === void 0) { onError = null; }
  30287. if (buffer === void 0) { buffer = null; }
  30288. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30289. var _this = _super.call(this, scene) || this;
  30290. _this.uOffset = 0;
  30291. _this.vOffset = 0;
  30292. _this.uScale = 1.0;
  30293. _this.vScale = 1.0;
  30294. _this.uAng = 0;
  30295. _this.vAng = 0;
  30296. _this.wAng = 0;
  30297. /**
  30298. * Defines the center of rotation (U)
  30299. */
  30300. _this.uRotationCenter = 0.5;
  30301. /**
  30302. * Defines the center of rotation (V)
  30303. */
  30304. _this.vRotationCenter = 0.5;
  30305. /**
  30306. * Defines the center of rotation (W)
  30307. */
  30308. _this.wRotationCenter = 0.5;
  30309. _this._isBlocking = true;
  30310. _this.name = url || "";
  30311. _this.url = url;
  30312. _this._noMipmap = noMipmap;
  30313. _this._invertY = invertY;
  30314. _this._samplingMode = samplingMode;
  30315. _this._buffer = buffer;
  30316. _this._deleteBuffer = deleteBuffer;
  30317. if (format) {
  30318. _this._format = format;
  30319. }
  30320. scene = _this.getScene();
  30321. if (!scene) {
  30322. return _this;
  30323. }
  30324. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30325. var load = function () {
  30326. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30327. _this.onLoadObservable.notifyObservers(_this);
  30328. }
  30329. if (onLoad) {
  30330. onLoad();
  30331. }
  30332. if (!_this.isBlocking && scene) {
  30333. scene.resetCachedMaterial();
  30334. }
  30335. };
  30336. if (!_this.url) {
  30337. _this._delayedOnLoad = load;
  30338. _this._delayedOnError = onError;
  30339. return _this;
  30340. }
  30341. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30342. if (!_this._texture) {
  30343. if (!scene.useDelayedTextureLoading) {
  30344. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30345. if (deleteBuffer) {
  30346. delete _this._buffer;
  30347. }
  30348. }
  30349. else {
  30350. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30351. _this._delayedOnLoad = load;
  30352. _this._delayedOnError = onError;
  30353. }
  30354. }
  30355. else {
  30356. if (_this._texture.isReady) {
  30357. BABYLON.Tools.SetImmediate(function () { return load(); });
  30358. }
  30359. else {
  30360. _this._texture.onLoadedObservable.add(load);
  30361. }
  30362. }
  30363. return _this;
  30364. }
  30365. Object.defineProperty(Texture.prototype, "noMipmap", {
  30366. get: function () {
  30367. return this._noMipmap;
  30368. },
  30369. enumerable: true,
  30370. configurable: true
  30371. });
  30372. Object.defineProperty(Texture.prototype, "isBlocking", {
  30373. get: function () {
  30374. return this._isBlocking;
  30375. },
  30376. set: function (value) {
  30377. this._isBlocking = value;
  30378. },
  30379. enumerable: true,
  30380. configurable: true
  30381. });
  30382. Object.defineProperty(Texture.prototype, "samplingMode", {
  30383. get: function () {
  30384. return this._samplingMode;
  30385. },
  30386. enumerable: true,
  30387. configurable: true
  30388. });
  30389. /**
  30390. * Update the url (and optional buffer) of this texture if url was null during construction.
  30391. * @param url the url of the texture
  30392. * @param buffer the buffer of the texture (defaults to null)
  30393. */
  30394. Texture.prototype.updateURL = function (url, buffer) {
  30395. if (buffer === void 0) { buffer = null; }
  30396. if (this.url) {
  30397. throw new Error("URL is already set");
  30398. }
  30399. this.url = url;
  30400. this._buffer = buffer;
  30401. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30402. this.delayLoad();
  30403. };
  30404. Texture.prototype.delayLoad = function () {
  30405. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30406. return;
  30407. }
  30408. var scene = this.getScene();
  30409. if (!scene) {
  30410. return;
  30411. }
  30412. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30413. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30414. if (!this._texture) {
  30415. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30416. if (this._deleteBuffer) {
  30417. delete this._buffer;
  30418. }
  30419. }
  30420. else {
  30421. if (this._delayedOnLoad) {
  30422. if (this._texture.isReady) {
  30423. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30424. }
  30425. else {
  30426. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30427. }
  30428. }
  30429. }
  30430. this._delayedOnLoad = null;
  30431. this._delayedOnError = null;
  30432. };
  30433. /**
  30434. * Default is Trilinear mode.
  30435. *
  30436. * | Value | Type | Description |
  30437. * | ----- | ------------------ | ----------- |
  30438. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30439. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30440. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30441. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30442. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30443. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30444. * | 7 | NEAREST_LINEAR | |
  30445. * | 8 | NEAREST_NEAREST | |
  30446. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30447. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30448. * | 11 | LINEAR_LINEAR | |
  30449. * | 12 | LINEAR_NEAREST | |
  30450. *
  30451. * > _mag_: magnification filter (close to the viewer)
  30452. * > _min_: minification filter (far from the viewer)
  30453. * > _mip_: filter used between mip map levels
  30454. *
  30455. */
  30456. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30457. if (!this._texture) {
  30458. return;
  30459. }
  30460. var scene = this.getScene();
  30461. if (!scene) {
  30462. return;
  30463. }
  30464. this._samplingMode = samplingMode;
  30465. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30466. };
  30467. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30468. x *= this.uScale;
  30469. y *= this.vScale;
  30470. x -= this.uRotationCenter * this.uScale;
  30471. y -= this.vRotationCenter * this.vScale;
  30472. z -= this.wRotationCenter;
  30473. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30474. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30475. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30476. t.z += this.wRotationCenter;
  30477. };
  30478. Texture.prototype.getTextureMatrix = function () {
  30479. var _this = this;
  30480. if (this.uOffset === this._cachedUOffset &&
  30481. this.vOffset === this._cachedVOffset &&
  30482. this.uScale === this._cachedUScale &&
  30483. this.vScale === this._cachedVScale &&
  30484. this.uAng === this._cachedUAng &&
  30485. this.vAng === this._cachedVAng &&
  30486. this.wAng === this._cachedWAng) {
  30487. return this._cachedTextureMatrix;
  30488. }
  30489. this._cachedUOffset = this.uOffset;
  30490. this._cachedVOffset = this.vOffset;
  30491. this._cachedUScale = this.uScale;
  30492. this._cachedVScale = this.vScale;
  30493. this._cachedUAng = this.uAng;
  30494. this._cachedVAng = this.vAng;
  30495. this._cachedWAng = this.wAng;
  30496. if (!this._cachedTextureMatrix) {
  30497. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30498. this._rowGenerationMatrix = new BABYLON.Matrix();
  30499. this._t0 = BABYLON.Vector3.Zero();
  30500. this._t1 = BABYLON.Vector3.Zero();
  30501. this._t2 = BABYLON.Vector3.Zero();
  30502. }
  30503. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30504. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30505. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30506. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30507. this._t1.subtractInPlace(this._t0);
  30508. this._t2.subtractInPlace(this._t0);
  30509. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30510. this._cachedTextureMatrix.m[0] = this._t1.x;
  30511. this._cachedTextureMatrix.m[1] = this._t1.y;
  30512. this._cachedTextureMatrix.m[2] = this._t1.z;
  30513. this._cachedTextureMatrix.m[4] = this._t2.x;
  30514. this._cachedTextureMatrix.m[5] = this._t2.y;
  30515. this._cachedTextureMatrix.m[6] = this._t2.z;
  30516. this._cachedTextureMatrix.m[8] = this._t0.x;
  30517. this._cachedTextureMatrix.m[9] = this._t0.y;
  30518. this._cachedTextureMatrix.m[10] = this._t0.z;
  30519. var scene = this.getScene();
  30520. if (!scene) {
  30521. return this._cachedTextureMatrix;
  30522. }
  30523. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30524. return mat.hasTexture(_this);
  30525. });
  30526. return this._cachedTextureMatrix;
  30527. };
  30528. Texture.prototype.getReflectionTextureMatrix = function () {
  30529. var _this = this;
  30530. var scene = this.getScene();
  30531. if (!scene) {
  30532. return this._cachedTextureMatrix;
  30533. }
  30534. if (this.uOffset === this._cachedUOffset &&
  30535. this.vOffset === this._cachedVOffset &&
  30536. this.uScale === this._cachedUScale &&
  30537. this.vScale === this._cachedVScale &&
  30538. this.coordinatesMode === this._cachedCoordinatesMode) {
  30539. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30540. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30541. return this._cachedTextureMatrix;
  30542. }
  30543. }
  30544. else {
  30545. return this._cachedTextureMatrix;
  30546. }
  30547. }
  30548. if (!this._cachedTextureMatrix) {
  30549. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30550. }
  30551. if (!this._projectionModeMatrix) {
  30552. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30553. }
  30554. this._cachedUOffset = this.uOffset;
  30555. this._cachedVOffset = this.vOffset;
  30556. this._cachedUScale = this.uScale;
  30557. this._cachedVScale = this.vScale;
  30558. this._cachedCoordinatesMode = this.coordinatesMode;
  30559. switch (this.coordinatesMode) {
  30560. case Texture.PLANAR_MODE:
  30561. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30562. this._cachedTextureMatrix[0] = this.uScale;
  30563. this._cachedTextureMatrix[5] = this.vScale;
  30564. this._cachedTextureMatrix[12] = this.uOffset;
  30565. this._cachedTextureMatrix[13] = this.vOffset;
  30566. break;
  30567. case Texture.PROJECTION_MODE:
  30568. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30569. this._projectionModeMatrix.m[0] = 0.5;
  30570. this._projectionModeMatrix.m[5] = -0.5;
  30571. this._projectionModeMatrix.m[10] = 0.0;
  30572. this._projectionModeMatrix.m[12] = 0.5;
  30573. this._projectionModeMatrix.m[13] = 0.5;
  30574. this._projectionModeMatrix.m[14] = 1.0;
  30575. this._projectionModeMatrix.m[15] = 1.0;
  30576. var projectionMatrix = scene.getProjectionMatrix();
  30577. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30578. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30579. break;
  30580. default:
  30581. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30582. break;
  30583. }
  30584. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30585. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30586. });
  30587. return this._cachedTextureMatrix;
  30588. };
  30589. Texture.prototype.clone = function () {
  30590. var _this = this;
  30591. return BABYLON.SerializationHelper.Clone(function () {
  30592. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30593. }, this);
  30594. };
  30595. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30596. get: function () {
  30597. if (!this._onLoadObservable) {
  30598. this._onLoadObservable = new BABYLON.Observable();
  30599. }
  30600. return this._onLoadObservable;
  30601. },
  30602. enumerable: true,
  30603. configurable: true
  30604. });
  30605. Texture.prototype.serialize = function () {
  30606. var serializationObject = _super.prototype.serialize.call(this);
  30607. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30608. serializationObject.base64String = this._buffer;
  30609. serializationObject.name = serializationObject.name.replace("data:", "");
  30610. }
  30611. serializationObject.invertY = this._invertY;
  30612. serializationObject.samplingMode = this.samplingMode;
  30613. return serializationObject;
  30614. };
  30615. Texture.prototype.getClassName = function () {
  30616. return "Texture";
  30617. };
  30618. Texture.prototype.dispose = function () {
  30619. _super.prototype.dispose.call(this);
  30620. if (this._onLoadObservable) {
  30621. this._onLoadObservable.clear();
  30622. this._onLoadObservable = null;
  30623. }
  30624. this._delayedOnLoad = null;
  30625. this._delayedOnError = null;
  30626. };
  30627. // Statics
  30628. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30629. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30630. if (onLoad === void 0) { onLoad = null; }
  30631. if (onError === void 0) { onError = null; }
  30632. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30633. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30634. };
  30635. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30636. if (parsedTexture.customType) {
  30637. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30638. // Update Sampling Mode
  30639. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30640. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30641. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30642. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30643. }
  30644. }
  30645. return parsedCustomTexture;
  30646. }
  30647. if (parsedTexture.isCube) {
  30648. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30649. }
  30650. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30651. return null;
  30652. }
  30653. var texture = BABYLON.SerializationHelper.Parse(function () {
  30654. var generateMipMaps = true;
  30655. if (parsedTexture.noMipmap) {
  30656. generateMipMaps = false;
  30657. }
  30658. if (parsedTexture.mirrorPlane) {
  30659. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30660. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30661. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30662. return mirrorTexture;
  30663. }
  30664. else if (parsedTexture.isRenderTarget) {
  30665. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30666. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30667. return renderTargetTexture;
  30668. }
  30669. else {
  30670. var texture;
  30671. if (parsedTexture.base64String) {
  30672. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30673. }
  30674. else {
  30675. var url = rootUrl + parsedTexture.name;
  30676. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30677. url = parsedTexture.url;
  30678. }
  30679. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30680. }
  30681. return texture;
  30682. }
  30683. }, parsedTexture, scene);
  30684. // Update Sampling Mode
  30685. if (parsedTexture.samplingMode) {
  30686. var sampling = parsedTexture.samplingMode;
  30687. if (texture._samplingMode !== sampling) {
  30688. texture.updateSamplingMode(sampling);
  30689. }
  30690. }
  30691. // Animations
  30692. if (parsedTexture.animations) {
  30693. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30694. var parsedAnimation = parsedTexture.animations[animationIndex];
  30695. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30696. }
  30697. }
  30698. return texture;
  30699. };
  30700. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30701. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30702. if (noMipmap === void 0) { noMipmap = false; }
  30703. if (invertY === void 0) { invertY = true; }
  30704. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30705. if (onLoad === void 0) { onLoad = null; }
  30706. if (onError === void 0) { onError = null; }
  30707. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30708. if (name.substr(0, 5) !== "data:") {
  30709. name = "data:" + name;
  30710. }
  30711. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30712. };
  30713. // Constants
  30714. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30715. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30716. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30717. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30718. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30719. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30720. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30721. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30722. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30723. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30724. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30725. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30726. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30727. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30728. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30729. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30730. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30731. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30732. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30733. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30734. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30735. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30736. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30737. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30738. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30739. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30740. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30741. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30742. /**
  30743. * 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
  30744. */
  30745. Texture.UseSerializedUrlIfAny = false;
  30746. __decorate([
  30747. BABYLON.serialize()
  30748. ], Texture.prototype, "url", void 0);
  30749. __decorate([
  30750. BABYLON.serialize()
  30751. ], Texture.prototype, "uOffset", void 0);
  30752. __decorate([
  30753. BABYLON.serialize()
  30754. ], Texture.prototype, "vOffset", void 0);
  30755. __decorate([
  30756. BABYLON.serialize()
  30757. ], Texture.prototype, "uScale", void 0);
  30758. __decorate([
  30759. BABYLON.serialize()
  30760. ], Texture.prototype, "vScale", void 0);
  30761. __decorate([
  30762. BABYLON.serialize()
  30763. ], Texture.prototype, "uAng", void 0);
  30764. __decorate([
  30765. BABYLON.serialize()
  30766. ], Texture.prototype, "vAng", void 0);
  30767. __decorate([
  30768. BABYLON.serialize()
  30769. ], Texture.prototype, "wAng", void 0);
  30770. __decorate([
  30771. BABYLON.serialize()
  30772. ], Texture.prototype, "uRotationCenter", void 0);
  30773. __decorate([
  30774. BABYLON.serialize()
  30775. ], Texture.prototype, "vRotationCenter", void 0);
  30776. __decorate([
  30777. BABYLON.serialize()
  30778. ], Texture.prototype, "wRotationCenter", void 0);
  30779. __decorate([
  30780. BABYLON.serialize()
  30781. ], Texture.prototype, "isBlocking", null);
  30782. return Texture;
  30783. }(BABYLON.BaseTexture));
  30784. BABYLON.Texture = Texture;
  30785. })(BABYLON || (BABYLON = {}));
  30786. //# sourceMappingURL=babylon.texture.js.map
  30787. var BABYLON;
  30788. (function (BABYLON) {
  30789. /**
  30790. * @hidden
  30791. **/
  30792. var _InstancesBatch = /** @class */ (function () {
  30793. function _InstancesBatch() {
  30794. this.mustReturn = false;
  30795. this.visibleInstances = new Array();
  30796. this.renderSelf = new Array();
  30797. }
  30798. return _InstancesBatch;
  30799. }());
  30800. BABYLON._InstancesBatch = _InstancesBatch;
  30801. var Mesh = /** @class */ (function (_super) {
  30802. __extends(Mesh, _super);
  30803. /**
  30804. * @constructor
  30805. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30806. * @param {Scene} scene The scene to add this mesh to.
  30807. * @param {Node} parent The parent of this mesh, if it has one
  30808. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30809. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30810. * When false, achieved by calling a clone(), also passing False.
  30811. * This will make creation of children, recursive.
  30812. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30813. */
  30814. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30815. if (scene === void 0) { scene = null; }
  30816. if (parent === void 0) { parent = null; }
  30817. if (source === void 0) { source = null; }
  30818. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30819. var _this = _super.call(this, name, scene) || this;
  30820. // Members
  30821. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30822. _this.instances = new Array();
  30823. _this._LODLevels = new Array();
  30824. /** @hidden */
  30825. _this._visibleInstances = {};
  30826. _this._renderIdForInstances = new Array();
  30827. _this._batchCache = new _InstancesBatch();
  30828. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30829. // Use by builder only to know what orientation were the mesh build in.
  30830. /** @hidden */
  30831. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30832. _this.overrideMaterialSideOrientation = null;
  30833. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30834. // Will be used to save a source mesh reference, If any
  30835. _this._source = null;
  30836. scene = _this.getScene();
  30837. if (source) {
  30838. // Geometry
  30839. if (source._geometry) {
  30840. source._geometry.applyToMesh(_this);
  30841. }
  30842. // Deep copy
  30843. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30844. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30845. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30846. ], ["_poseMatrix"]);
  30847. // Source mesh
  30848. _this._source = source;
  30849. // Construction Params
  30850. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  30851. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  30852. var myAnyThis = _this;
  30853. var myAnySource = source;
  30854. myAnyThis._closePath = myAnySource._closePath;
  30855. myAnyThis._idx = myAnySource._idx;
  30856. myAnyThis.dashSize = myAnySource.dashSize;
  30857. myAnyThis.gapSize = myAnySource.gapSize;
  30858. myAnyThis.path3D = myAnySource.path3D;
  30859. myAnyThis.pathArray = myAnySource.pathArray;
  30860. myAnyThis.arc = myAnySource.arc;
  30861. myAnyThis.radius = myAnySource.radius;
  30862. // Animation ranges
  30863. if (_this._source._ranges) {
  30864. var ranges = _this._source._ranges;
  30865. for (var name in ranges) {
  30866. if (!ranges.hasOwnProperty(name)) {
  30867. continue;
  30868. }
  30869. if (!ranges[name]) {
  30870. continue;
  30871. }
  30872. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  30873. }
  30874. }
  30875. // Metadata
  30876. if (source.metadata && source.metadata.clone) {
  30877. _this.metadata = source.metadata.clone();
  30878. }
  30879. else {
  30880. _this.metadata = source.metadata;
  30881. }
  30882. // Tags
  30883. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30884. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30885. }
  30886. // Parent
  30887. _this.parent = source.parent;
  30888. // Pivot
  30889. _this.setPivotMatrix(source.getPivotMatrix());
  30890. _this.id = name + "." + source.id;
  30891. // Material
  30892. _this.material = source.material;
  30893. var index;
  30894. if (!doNotCloneChildren) {
  30895. // Children
  30896. var directDescendants = source.getDescendants(true);
  30897. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30898. var child = directDescendants[index_1];
  30899. if (child.clone) {
  30900. child.clone(name + "." + child.name, _this);
  30901. }
  30902. }
  30903. }
  30904. // Physics clone
  30905. var physicsEngine = _this.getScene().getPhysicsEngine();
  30906. if (clonePhysicsImpostor && physicsEngine) {
  30907. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30908. if (impostor) {
  30909. _this.physicsImpostor = impostor.clone(_this);
  30910. }
  30911. }
  30912. // Particles
  30913. for (index = 0; index < scene.particleSystems.length; index++) {
  30914. var system = scene.particleSystems[index];
  30915. if (system.emitter === source) {
  30916. system.clone(system.name, _this);
  30917. }
  30918. }
  30919. _this.refreshBoundingInfo();
  30920. _this.computeWorldMatrix(true);
  30921. }
  30922. // Parent
  30923. if (parent !== null) {
  30924. _this.parent = parent;
  30925. }
  30926. return _this;
  30927. }
  30928. Object.defineProperty(Mesh, "FRONTSIDE", {
  30929. /**
  30930. * Mesh side orientation : usually the external or front surface
  30931. */
  30932. get: function () {
  30933. return Mesh._FRONTSIDE;
  30934. },
  30935. enumerable: true,
  30936. configurable: true
  30937. });
  30938. Object.defineProperty(Mesh, "BACKSIDE", {
  30939. /**
  30940. * Mesh side orientation : usually the internal or back surface
  30941. */
  30942. get: function () {
  30943. return Mesh._BACKSIDE;
  30944. },
  30945. enumerable: true,
  30946. configurable: true
  30947. });
  30948. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30949. /**
  30950. * Mesh side orientation : both internal and external or front and back surfaces
  30951. */
  30952. get: function () {
  30953. return Mesh._DOUBLESIDE;
  30954. },
  30955. enumerable: true,
  30956. configurable: true
  30957. });
  30958. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30959. /**
  30960. * Mesh side orientation : by default, `FRONTSIDE`
  30961. */
  30962. get: function () {
  30963. return Mesh._DEFAULTSIDE;
  30964. },
  30965. enumerable: true,
  30966. configurable: true
  30967. });
  30968. Object.defineProperty(Mesh, "NO_CAP", {
  30969. /**
  30970. * Mesh cap setting : no cap
  30971. */
  30972. get: function () {
  30973. return Mesh._NO_CAP;
  30974. },
  30975. enumerable: true,
  30976. configurable: true
  30977. });
  30978. Object.defineProperty(Mesh, "CAP_START", {
  30979. /**
  30980. * Mesh cap setting : one cap at the beginning of the mesh
  30981. */
  30982. get: function () {
  30983. return Mesh._CAP_START;
  30984. },
  30985. enumerable: true,
  30986. configurable: true
  30987. });
  30988. Object.defineProperty(Mesh, "CAP_END", {
  30989. /**
  30990. * Mesh cap setting : one cap at the end of the mesh
  30991. */
  30992. get: function () {
  30993. return Mesh._CAP_END;
  30994. },
  30995. enumerable: true,
  30996. configurable: true
  30997. });
  30998. Object.defineProperty(Mesh, "CAP_ALL", {
  30999. /**
  31000. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31001. */
  31002. get: function () {
  31003. return Mesh._CAP_ALL;
  31004. },
  31005. enumerable: true,
  31006. configurable: true
  31007. });
  31008. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31009. /**
  31010. * An event triggered before rendering the mesh
  31011. */
  31012. get: function () {
  31013. if (!this._onBeforeRenderObservable) {
  31014. this._onBeforeRenderObservable = new BABYLON.Observable();
  31015. }
  31016. return this._onBeforeRenderObservable;
  31017. },
  31018. enumerable: true,
  31019. configurable: true
  31020. });
  31021. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31022. /**
  31023. * An event triggered after rendering the mesh
  31024. */
  31025. get: function () {
  31026. if (!this._onAfterRenderObservable) {
  31027. this._onAfterRenderObservable = new BABYLON.Observable();
  31028. }
  31029. return this._onAfterRenderObservable;
  31030. },
  31031. enumerable: true,
  31032. configurable: true
  31033. });
  31034. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31035. /**
  31036. * An event triggered before drawing the mesh
  31037. */
  31038. get: function () {
  31039. if (!this._onBeforeDrawObservable) {
  31040. this._onBeforeDrawObservable = new BABYLON.Observable();
  31041. }
  31042. return this._onBeforeDrawObservable;
  31043. },
  31044. enumerable: true,
  31045. configurable: true
  31046. });
  31047. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31048. set: function (callback) {
  31049. if (this._onBeforeDrawObserver) {
  31050. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31051. }
  31052. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31053. },
  31054. enumerable: true,
  31055. configurable: true
  31056. });
  31057. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31058. get: function () {
  31059. return this._morphTargetManager;
  31060. },
  31061. set: function (value) {
  31062. if (this._morphTargetManager === value) {
  31063. return;
  31064. }
  31065. this._morphTargetManager = value;
  31066. this._syncGeometryWithMorphTargetManager();
  31067. },
  31068. enumerable: true,
  31069. configurable: true
  31070. });
  31071. Object.defineProperty(Mesh.prototype, "source", {
  31072. get: function () {
  31073. return this._source;
  31074. },
  31075. enumerable: true,
  31076. configurable: true
  31077. });
  31078. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31079. get: function () {
  31080. return this._unIndexed;
  31081. },
  31082. set: function (value) {
  31083. if (this._unIndexed !== value) {
  31084. this._unIndexed = value;
  31085. this._markSubMeshesAsAttributesDirty();
  31086. }
  31087. },
  31088. enumerable: true,
  31089. configurable: true
  31090. });
  31091. // Methods
  31092. /**
  31093. * Returns the string "Mesh".
  31094. */
  31095. Mesh.prototype.getClassName = function () {
  31096. return "Mesh";
  31097. };
  31098. /**
  31099. * Returns a string.
  31100. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31101. */
  31102. Mesh.prototype.toString = function (fullDetails) {
  31103. var ret = _super.prototype.toString.call(this, fullDetails);
  31104. ret += ", n vertices: " + this.getTotalVertices();
  31105. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31106. if (this.animations) {
  31107. for (var i = 0; i < this.animations.length; i++) {
  31108. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31109. }
  31110. }
  31111. if (fullDetails) {
  31112. if (this._geometry) {
  31113. var ib = this.getIndices();
  31114. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31115. if (vb && ib) {
  31116. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31117. }
  31118. }
  31119. else {
  31120. ret += ", flat shading: UNKNOWN";
  31121. }
  31122. }
  31123. return ret;
  31124. };
  31125. /** @hidden */
  31126. Mesh.prototype._unBindEffect = function () {
  31127. _super.prototype._unBindEffect.call(this);
  31128. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31129. var instance = _a[_i];
  31130. instance._unBindEffect();
  31131. }
  31132. };
  31133. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31134. /**
  31135. * True if the mesh has some Levels Of Details (LOD).
  31136. * Returns a boolean.
  31137. */
  31138. get: function () {
  31139. return this._LODLevels.length > 0;
  31140. },
  31141. enumerable: true,
  31142. configurable: true
  31143. });
  31144. /**
  31145. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31146. * @returns an array of {BABYLON.MeshLODLevel}
  31147. */
  31148. Mesh.prototype.getLODLevels = function () {
  31149. return this._LODLevels;
  31150. };
  31151. Mesh.prototype._sortLODLevels = function () {
  31152. this._LODLevels.sort(function (a, b) {
  31153. if (a.distance < b.distance) {
  31154. return 1;
  31155. }
  31156. if (a.distance > b.distance) {
  31157. return -1;
  31158. }
  31159. return 0;
  31160. });
  31161. };
  31162. /**
  31163. * Add a mesh as LOD level triggered at the given distance.
  31164. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31165. * @param distance The distance from the center of the object to show this level
  31166. * @param mesh The mesh to be added as LOD level (can be null)
  31167. * @return This mesh (for chaining)
  31168. */
  31169. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31170. if (mesh && mesh._masterMesh) {
  31171. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31172. return this;
  31173. }
  31174. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31175. this._LODLevels.push(level);
  31176. if (mesh) {
  31177. mesh._masterMesh = this;
  31178. }
  31179. this._sortLODLevels();
  31180. return this;
  31181. };
  31182. /**
  31183. * Returns the LOD level mesh at the passed distance or null if not found.
  31184. * It is related to the method `addLODLevel(distance, mesh)`.
  31185. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31186. * Returns an object Mesh or `null`.
  31187. */
  31188. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31189. for (var index = 0; index < this._LODLevels.length; index++) {
  31190. var level = this._LODLevels[index];
  31191. if (level.distance === distance) {
  31192. return level.mesh;
  31193. }
  31194. }
  31195. return null;
  31196. };
  31197. /**
  31198. * Remove a mesh from the LOD array
  31199. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31200. * @param {Mesh} mesh The mesh to be removed.
  31201. * @return {Mesh} This mesh (for chaining)
  31202. */
  31203. Mesh.prototype.removeLODLevel = function (mesh) {
  31204. for (var index = 0; index < this._LODLevels.length; index++) {
  31205. if (this._LODLevels[index].mesh === mesh) {
  31206. this._LODLevels.splice(index, 1);
  31207. if (mesh) {
  31208. mesh._masterMesh = null;
  31209. }
  31210. }
  31211. }
  31212. this._sortLODLevels();
  31213. return this;
  31214. };
  31215. /**
  31216. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31217. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31218. */
  31219. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31220. if (!this._LODLevels || this._LODLevels.length === 0) {
  31221. return this;
  31222. }
  31223. var bSphere;
  31224. if (boundingSphere) {
  31225. bSphere = boundingSphere;
  31226. }
  31227. else {
  31228. var boundingInfo = this.getBoundingInfo();
  31229. bSphere = boundingInfo.boundingSphere;
  31230. }
  31231. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31232. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31233. if (this.onLODLevelSelection) {
  31234. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31235. }
  31236. return this;
  31237. }
  31238. for (var index = 0; index < this._LODLevels.length; index++) {
  31239. var level = this._LODLevels[index];
  31240. if (level.distance < distanceToCamera) {
  31241. if (level.mesh) {
  31242. level.mesh._preActivate();
  31243. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31244. }
  31245. if (this.onLODLevelSelection) {
  31246. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31247. }
  31248. return level.mesh;
  31249. }
  31250. }
  31251. if (this.onLODLevelSelection) {
  31252. this.onLODLevelSelection(distanceToCamera, this, this);
  31253. }
  31254. return this;
  31255. };
  31256. Object.defineProperty(Mesh.prototype, "geometry", {
  31257. /**
  31258. * Returns the mesh internal Geometry object.
  31259. */
  31260. get: function () {
  31261. return this._geometry;
  31262. },
  31263. enumerable: true,
  31264. configurable: true
  31265. });
  31266. /**
  31267. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31268. */
  31269. Mesh.prototype.getTotalVertices = function () {
  31270. if (this._geometry === null || this._geometry === undefined) {
  31271. return 0;
  31272. }
  31273. return this._geometry.getTotalVertices();
  31274. };
  31275. /**
  31276. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31277. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31278. * You can force the copy with forceCopy === true
  31279. * Returns null if the mesh has no geometry or no vertex buffer.
  31280. * Possible `kind` values :
  31281. * - BABYLON.VertexBuffer.PositionKind
  31282. * - BABYLON.VertexBuffer.UVKind
  31283. * - BABYLON.VertexBuffer.UV2Kind
  31284. * - BABYLON.VertexBuffer.UV3Kind
  31285. * - BABYLON.VertexBuffer.UV4Kind
  31286. * - BABYLON.VertexBuffer.UV5Kind
  31287. * - BABYLON.VertexBuffer.UV6Kind
  31288. * - BABYLON.VertexBuffer.ColorKind
  31289. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31290. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31291. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31292. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31293. */
  31294. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31295. if (!this._geometry) {
  31296. return null;
  31297. }
  31298. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31299. };
  31300. /**
  31301. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31302. * Returns `null` if the mesh has no geometry.
  31303. * Possible `kind` values :
  31304. * - BABYLON.VertexBuffer.PositionKind
  31305. * - BABYLON.VertexBuffer.UVKind
  31306. * - BABYLON.VertexBuffer.UV2Kind
  31307. * - BABYLON.VertexBuffer.UV3Kind
  31308. * - BABYLON.VertexBuffer.UV4Kind
  31309. * - BABYLON.VertexBuffer.UV5Kind
  31310. * - BABYLON.VertexBuffer.UV6Kind
  31311. * - BABYLON.VertexBuffer.ColorKind
  31312. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31313. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31314. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31315. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31316. */
  31317. Mesh.prototype.getVertexBuffer = function (kind) {
  31318. if (!this._geometry) {
  31319. return null;
  31320. }
  31321. return this._geometry.getVertexBuffer(kind);
  31322. };
  31323. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31324. if (!this._geometry) {
  31325. if (this._delayInfo) {
  31326. return this._delayInfo.indexOf(kind) !== -1;
  31327. }
  31328. return false;
  31329. }
  31330. return this._geometry.isVerticesDataPresent(kind);
  31331. };
  31332. /**
  31333. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31334. * Possible `kind` values :
  31335. * - BABYLON.VertexBuffer.PositionKind
  31336. * - BABYLON.VertexBuffer.UVKind
  31337. * - BABYLON.VertexBuffer.UV2Kind
  31338. * - BABYLON.VertexBuffer.UV3Kind
  31339. * - BABYLON.VertexBuffer.UV4Kind
  31340. * - BABYLON.VertexBuffer.UV5Kind
  31341. * - BABYLON.VertexBuffer.UV6Kind
  31342. * - BABYLON.VertexBuffer.ColorKind
  31343. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31344. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31345. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31346. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31347. */
  31348. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31349. if (!this._geometry) {
  31350. if (this._delayInfo) {
  31351. return this._delayInfo.indexOf(kind) !== -1;
  31352. }
  31353. return false;
  31354. }
  31355. return this._geometry.isVertexBufferUpdatable(kind);
  31356. };
  31357. /**
  31358. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31359. * Possible `kind` values :
  31360. * - BABYLON.VertexBuffer.PositionKind
  31361. * - BABYLON.VertexBuffer.UVKind
  31362. * - BABYLON.VertexBuffer.UV2Kind
  31363. * - BABYLON.VertexBuffer.UV3Kind
  31364. * - BABYLON.VertexBuffer.UV4Kind
  31365. * - BABYLON.VertexBuffer.UV5Kind
  31366. * - BABYLON.VertexBuffer.UV6Kind
  31367. * - BABYLON.VertexBuffer.ColorKind
  31368. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31369. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31370. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31371. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31372. */
  31373. Mesh.prototype.getVerticesDataKinds = function () {
  31374. if (!this._geometry) {
  31375. var result = new Array();
  31376. if (this._delayInfo) {
  31377. this._delayInfo.forEach(function (kind, index, array) {
  31378. result.push(kind);
  31379. });
  31380. }
  31381. return result;
  31382. }
  31383. return this._geometry.getVerticesDataKinds();
  31384. };
  31385. /**
  31386. * Returns a positive integer : the total number of indices in this mesh geometry.
  31387. * Returns zero if the mesh has no geometry.
  31388. */
  31389. Mesh.prototype.getTotalIndices = function () {
  31390. if (!this._geometry) {
  31391. return 0;
  31392. }
  31393. return this._geometry.getTotalIndices();
  31394. };
  31395. /**
  31396. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31397. * @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.
  31398. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31399. * @returns the indices array or an empty array if the mesh has no geometry
  31400. */
  31401. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31402. if (!this._geometry) {
  31403. return [];
  31404. }
  31405. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31406. };
  31407. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31408. get: function () {
  31409. return this._masterMesh !== null && this._masterMesh !== undefined;
  31410. },
  31411. enumerable: true,
  31412. configurable: true
  31413. });
  31414. /**
  31415. * Determine if the current mesh is ready to be rendered
  31416. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31417. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31418. * @returns true if all associated assets are ready (material, textures, shaders)
  31419. */
  31420. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31421. if (completeCheck === void 0) { completeCheck = false; }
  31422. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31423. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31424. return false;
  31425. }
  31426. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31427. return false;
  31428. }
  31429. if (!this.subMeshes || this.subMeshes.length === 0) {
  31430. return true;
  31431. }
  31432. if (!completeCheck) {
  31433. return true;
  31434. }
  31435. var engine = this.getEngine();
  31436. var scene = this.getScene();
  31437. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31438. this.computeWorldMatrix();
  31439. var mat = this.material || scene.defaultMaterial;
  31440. if (mat) {
  31441. if (mat.storeEffectOnSubMeshes) {
  31442. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31443. var subMesh = _a[_i];
  31444. var effectiveMaterial = subMesh.getMaterial();
  31445. if (effectiveMaterial) {
  31446. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31447. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31448. return false;
  31449. }
  31450. }
  31451. else {
  31452. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31453. return false;
  31454. }
  31455. }
  31456. }
  31457. }
  31458. }
  31459. else {
  31460. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31461. return false;
  31462. }
  31463. }
  31464. }
  31465. // Shadows
  31466. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31467. var light = _c[_b];
  31468. var generator = light.getShadowGenerator();
  31469. if (generator) {
  31470. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31471. var subMesh = _e[_d];
  31472. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31473. return false;
  31474. }
  31475. }
  31476. }
  31477. }
  31478. // LOD
  31479. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31480. var lod = _g[_f];
  31481. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31482. return false;
  31483. }
  31484. }
  31485. return true;
  31486. };
  31487. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31488. /**
  31489. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31490. * This property is pertinent only for updatable parametric shapes.
  31491. */
  31492. get: function () {
  31493. return this._areNormalsFrozen;
  31494. },
  31495. enumerable: true,
  31496. configurable: true
  31497. });
  31498. /**
  31499. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31500. * It has no effect at all on other shapes.
  31501. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31502. * Returns the Mesh.
  31503. */
  31504. Mesh.prototype.freezeNormals = function () {
  31505. this._areNormalsFrozen = true;
  31506. return this;
  31507. };
  31508. /**
  31509. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31510. * It has no effect at all on other shapes.
  31511. * It reactivates the mesh normals computation if it was previously frozen.
  31512. * Returns the Mesh.
  31513. */
  31514. Mesh.prototype.unfreezeNormals = function () {
  31515. this._areNormalsFrozen = false;
  31516. return this;
  31517. };
  31518. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31519. /**
  31520. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31521. */
  31522. set: function (count) {
  31523. this._overridenInstanceCount = count;
  31524. },
  31525. enumerable: true,
  31526. configurable: true
  31527. });
  31528. // Methods
  31529. /** @hidden */
  31530. Mesh.prototype._preActivate = function () {
  31531. var sceneRenderId = this.getScene().getRenderId();
  31532. if (this._preActivateId === sceneRenderId) {
  31533. return this;
  31534. }
  31535. this._preActivateId = sceneRenderId;
  31536. this._visibleInstances = null;
  31537. return this;
  31538. };
  31539. /** @hidden */
  31540. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31541. if (this._visibleInstances) {
  31542. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31543. }
  31544. return this;
  31545. };
  31546. /** @hidden */
  31547. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31548. if (!this._visibleInstances) {
  31549. this._visibleInstances = {};
  31550. this._visibleInstances.defaultRenderId = renderId;
  31551. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31552. }
  31553. if (!this._visibleInstances[renderId]) {
  31554. this._visibleInstances[renderId] = new Array();
  31555. }
  31556. this._visibleInstances[renderId].push(instance);
  31557. return this;
  31558. };
  31559. /**
  31560. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31561. * This means the mesh underlying bounding box and sphere are recomputed.
  31562. * Returns the Mesh.
  31563. */
  31564. Mesh.prototype.refreshBoundingInfo = function () {
  31565. return this._refreshBoundingInfo(false);
  31566. };
  31567. /** @hidden */
  31568. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31569. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31570. return this;
  31571. }
  31572. var data = this._getPositionData(applySkeleton);
  31573. if (data) {
  31574. var bias = this.geometry ? this.geometry.boundingBias : null;
  31575. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31576. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31577. }
  31578. if (this.subMeshes) {
  31579. for (var index = 0; index < this.subMeshes.length; index++) {
  31580. this.subMeshes[index].refreshBoundingInfo();
  31581. }
  31582. }
  31583. this._updateBoundingInfo();
  31584. return this;
  31585. };
  31586. Mesh.prototype._getPositionData = function (applySkeleton) {
  31587. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31588. if (data && applySkeleton && this.skeleton) {
  31589. data = BABYLON.Tools.Slice(data);
  31590. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31591. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31592. if (matricesWeightsData && matricesIndicesData) {
  31593. var needExtras = this.numBoneInfluencers > 4;
  31594. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31595. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31596. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31597. var tempVector = BABYLON.Tmp.Vector3[0];
  31598. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31599. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31600. var matWeightIdx = 0;
  31601. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31602. finalMatrix.reset();
  31603. var inf;
  31604. var weight;
  31605. for (inf = 0; inf < 4; inf++) {
  31606. weight = matricesWeightsData[matWeightIdx + inf];
  31607. if (weight > 0) {
  31608. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31609. finalMatrix.addToSelf(tempMatrix);
  31610. }
  31611. }
  31612. if (needExtras) {
  31613. for (inf = 0; inf < 4; inf++) {
  31614. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31615. if (weight > 0) {
  31616. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31617. finalMatrix.addToSelf(tempMatrix);
  31618. }
  31619. }
  31620. }
  31621. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31622. tempVector.toArray(data, index);
  31623. }
  31624. }
  31625. }
  31626. return data;
  31627. };
  31628. /** @hidden */
  31629. Mesh.prototype._createGlobalSubMesh = function (force) {
  31630. var totalVertices = this.getTotalVertices();
  31631. if (!totalVertices || !this.getIndices()) {
  31632. return null;
  31633. }
  31634. // Check if we need to recreate the submeshes
  31635. if (this.subMeshes && this.subMeshes.length > 0) {
  31636. var ib = this.getIndices();
  31637. if (!ib) {
  31638. return null;
  31639. }
  31640. var totalIndices = ib.length;
  31641. var needToRecreate = false;
  31642. if (force) {
  31643. needToRecreate = true;
  31644. }
  31645. else {
  31646. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31647. var submesh = _a[_i];
  31648. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31649. needToRecreate = true;
  31650. break;
  31651. }
  31652. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31653. needToRecreate = true;
  31654. break;
  31655. }
  31656. }
  31657. }
  31658. if (!needToRecreate) {
  31659. return this.subMeshes[0];
  31660. }
  31661. }
  31662. this.releaseSubMeshes();
  31663. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31664. };
  31665. Mesh.prototype.subdivide = function (count) {
  31666. if (count < 1) {
  31667. return;
  31668. }
  31669. var totalIndices = this.getTotalIndices();
  31670. var subdivisionSize = (totalIndices / count) | 0;
  31671. var offset = 0;
  31672. // Ensure that subdivisionSize is a multiple of 3
  31673. while (subdivisionSize % 3 !== 0) {
  31674. subdivisionSize++;
  31675. }
  31676. this.releaseSubMeshes();
  31677. for (var index = 0; index < count; index++) {
  31678. if (offset >= totalIndices) {
  31679. break;
  31680. }
  31681. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31682. offset += subdivisionSize;
  31683. }
  31684. this.synchronizeInstances();
  31685. };
  31686. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31687. if (updatable === void 0) { updatable = false; }
  31688. if (!this._geometry) {
  31689. var vertexData = new BABYLON.VertexData();
  31690. vertexData.set(data, kind);
  31691. var scene = this.getScene();
  31692. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31693. }
  31694. else {
  31695. this._geometry.setVerticesData(kind, data, updatable, stride);
  31696. }
  31697. return this;
  31698. };
  31699. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31700. if (updatable === void 0) { updatable = true; }
  31701. var vb = this.getVertexBuffer(kind);
  31702. if (!vb || vb.isUpdatable() === updatable) {
  31703. return;
  31704. }
  31705. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31706. };
  31707. /**
  31708. * Sets the mesh VertexBuffer.
  31709. * Returns the Mesh.
  31710. */
  31711. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31712. if (!this._geometry) {
  31713. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31714. }
  31715. this._geometry.setVerticesBuffer(buffer);
  31716. return this;
  31717. };
  31718. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31719. if (!this._geometry) {
  31720. return this;
  31721. }
  31722. if (!makeItUnique) {
  31723. this._geometry.updateVerticesData(kind, data, updateExtends);
  31724. }
  31725. else {
  31726. this.makeGeometryUnique();
  31727. this.updateVerticesData(kind, data, updateExtends, false);
  31728. }
  31729. return this;
  31730. };
  31731. /**
  31732. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31733. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31734. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31735. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31736. * Returns the Mesh.
  31737. */
  31738. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31739. if (computeNormals === void 0) { computeNormals = true; }
  31740. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31741. if (!positions) {
  31742. return this;
  31743. }
  31744. positionFunction(positions);
  31745. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31746. if (computeNormals) {
  31747. var indices = this.getIndices();
  31748. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31749. if (!normals) {
  31750. return this;
  31751. }
  31752. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31753. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31754. }
  31755. return this;
  31756. };
  31757. /**
  31758. * Creates a un-shared specific occurence of the geometry for the mesh.
  31759. * Returns the Mesh.
  31760. */
  31761. Mesh.prototype.makeGeometryUnique = function () {
  31762. if (!this._geometry) {
  31763. return this;
  31764. }
  31765. var oldGeometry = this._geometry;
  31766. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31767. oldGeometry.releaseForMesh(this, true);
  31768. geometry.applyToMesh(this);
  31769. return this;
  31770. };
  31771. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31772. if (totalVertices === void 0) { totalVertices = null; }
  31773. if (updatable === void 0) { updatable = false; }
  31774. if (!this._geometry) {
  31775. var vertexData = new BABYLON.VertexData();
  31776. vertexData.indices = indices;
  31777. var scene = this.getScene();
  31778. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31779. }
  31780. else {
  31781. this._geometry.setIndices(indices, totalVertices, updatable);
  31782. }
  31783. return this;
  31784. };
  31785. /**
  31786. * Update the current index buffer
  31787. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31788. * Returns the Mesh.
  31789. */
  31790. Mesh.prototype.updateIndices = function (indices, offset) {
  31791. if (!this._geometry) {
  31792. return this;
  31793. }
  31794. this._geometry.updateIndices(indices, offset);
  31795. return this;
  31796. };
  31797. /**
  31798. * Invert the geometry to move from a right handed system to a left handed one.
  31799. * Returns the Mesh.
  31800. */
  31801. Mesh.prototype.toLeftHanded = function () {
  31802. if (!this._geometry) {
  31803. return this;
  31804. }
  31805. this._geometry.toLeftHanded();
  31806. return this;
  31807. };
  31808. /** @hidden */
  31809. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31810. if (!this._geometry) {
  31811. return this;
  31812. }
  31813. var engine = this.getScene().getEngine();
  31814. // Wireframe
  31815. var indexToBind;
  31816. if (this._unIndexed) {
  31817. indexToBind = null;
  31818. }
  31819. else {
  31820. switch (fillMode) {
  31821. case BABYLON.Material.PointFillMode:
  31822. indexToBind = null;
  31823. break;
  31824. case BABYLON.Material.WireFrameFillMode:
  31825. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31826. break;
  31827. default:
  31828. case BABYLON.Material.TriangleFillMode:
  31829. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31830. break;
  31831. }
  31832. }
  31833. // VBOs
  31834. this._geometry._bind(effect, indexToBind);
  31835. return this;
  31836. };
  31837. /** @hidden */
  31838. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31839. if (alternate === void 0) { alternate = false; }
  31840. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31841. return this;
  31842. }
  31843. if (this._onBeforeDrawObservable) {
  31844. this._onBeforeDrawObservable.notifyObservers(this);
  31845. }
  31846. var scene = this.getScene();
  31847. var engine = scene.getEngine();
  31848. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31849. // or triangles as points
  31850. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31851. }
  31852. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31853. // Triangles as wireframe
  31854. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31855. }
  31856. else {
  31857. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31858. }
  31859. if (scene._isAlternateRenderingEnabled && !alternate) {
  31860. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31861. if (!effect || !scene.activeCamera) {
  31862. return this;
  31863. }
  31864. scene._switchToAlternateCameraConfiguration(true);
  31865. this._effectiveMaterial.bindView(effect);
  31866. this._effectiveMaterial.bindViewProjection(effect);
  31867. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31868. this._draw(subMesh, fillMode, instancesCount, true);
  31869. engine.setViewport(scene.activeCamera.viewport);
  31870. scene._switchToAlternateCameraConfiguration(false);
  31871. this._effectiveMaterial.bindView(effect);
  31872. this._effectiveMaterial.bindViewProjection(effect);
  31873. }
  31874. return this;
  31875. };
  31876. /**
  31877. * Registers for this mesh a javascript function called just before the rendering process.
  31878. * This function is passed the current mesh.
  31879. * Return the Mesh.
  31880. */
  31881. Mesh.prototype.registerBeforeRender = function (func) {
  31882. this.onBeforeRenderObservable.add(func);
  31883. return this;
  31884. };
  31885. /**
  31886. * Disposes a previously registered javascript function called before the rendering.
  31887. * This function is passed the current mesh.
  31888. * Returns the Mesh.
  31889. */
  31890. Mesh.prototype.unregisterBeforeRender = function (func) {
  31891. this.onBeforeRenderObservable.removeCallback(func);
  31892. return this;
  31893. };
  31894. /**
  31895. * Registers for this mesh a javascript function called just after the rendering is complete.
  31896. * This function is passed the current mesh.
  31897. * Returns the Mesh.
  31898. */
  31899. Mesh.prototype.registerAfterRender = function (func) {
  31900. this.onAfterRenderObservable.add(func);
  31901. return this;
  31902. };
  31903. /**
  31904. * Disposes a previously registered javascript function called after the rendering.
  31905. * This function is passed the current mesh.
  31906. * Return the Mesh.
  31907. */
  31908. Mesh.prototype.unregisterAfterRender = function (func) {
  31909. this.onAfterRenderObservable.removeCallback(func);
  31910. return this;
  31911. };
  31912. /** @hidden */
  31913. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31914. var scene = this.getScene();
  31915. this._batchCache.mustReturn = false;
  31916. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31917. this._batchCache.visibleInstances[subMeshId] = null;
  31918. if (this._visibleInstances) {
  31919. var currentRenderId = scene.getRenderId();
  31920. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31921. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31922. var selfRenderId = this._renderId;
  31923. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31924. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31925. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31926. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31927. }
  31928. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31929. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31930. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31931. this._batchCache.mustReturn = true;
  31932. return this._batchCache;
  31933. }
  31934. if (currentRenderId !== selfRenderId) {
  31935. this._batchCache.renderSelf[subMeshId] = false;
  31936. }
  31937. }
  31938. this._renderIdForInstances[subMeshId] = currentRenderId;
  31939. }
  31940. return this._batchCache;
  31941. };
  31942. /** @hidden */
  31943. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31944. var visibleInstances = batch.visibleInstances[subMesh._id];
  31945. if (!visibleInstances) {
  31946. return this;
  31947. }
  31948. var matricesCount = visibleInstances.length + 1;
  31949. var bufferSize = matricesCount * 16 * 4;
  31950. var currentInstancesBufferSize = this._instancesBufferSize;
  31951. var instancesBuffer = this._instancesBuffer;
  31952. while (this._instancesBufferSize < bufferSize) {
  31953. this._instancesBufferSize *= 2;
  31954. }
  31955. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31956. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31957. }
  31958. var offset = 0;
  31959. var instancesCount = 0;
  31960. var world = this.getWorldMatrix();
  31961. if (batch.renderSelf[subMesh._id]) {
  31962. world.copyToArray(this._instancesData, offset);
  31963. offset += 16;
  31964. instancesCount++;
  31965. }
  31966. if (visibleInstances) {
  31967. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31968. var instance = visibleInstances[instanceIndex];
  31969. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31970. offset += 16;
  31971. instancesCount++;
  31972. }
  31973. }
  31974. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31975. if (instancesBuffer) {
  31976. instancesBuffer.dispose();
  31977. }
  31978. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31979. this._instancesBuffer = instancesBuffer;
  31980. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31981. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31982. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31983. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31984. }
  31985. else {
  31986. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31987. }
  31988. this._bind(subMesh, effect, fillMode);
  31989. this._draw(subMesh, fillMode, instancesCount);
  31990. engine.unbindInstanceAttributes();
  31991. return this;
  31992. };
  31993. /** @hidden */
  31994. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31995. var scene = this.getScene();
  31996. var engine = scene.getEngine();
  31997. if (hardwareInstancedRendering) {
  31998. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31999. }
  32000. else {
  32001. if (batch.renderSelf[subMesh._id]) {
  32002. // Draw
  32003. if (onBeforeDraw) {
  32004. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32005. }
  32006. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32007. }
  32008. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32009. if (visibleInstancesForSubMesh) {
  32010. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32011. var instance = visibleInstancesForSubMesh[instanceIndex];
  32012. // World
  32013. var world = instance.getWorldMatrix();
  32014. if (onBeforeDraw) {
  32015. onBeforeDraw(true, world, effectiveMaterial);
  32016. }
  32017. // Draw
  32018. this._draw(subMesh, fillMode);
  32019. }
  32020. }
  32021. }
  32022. return this;
  32023. };
  32024. /**
  32025. * 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
  32026. * @param subMesh defines the subMesh to render
  32027. * @param enableAlphaMode defines if alpha mode can be changed
  32028. * @returns the current mesh
  32029. */
  32030. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32031. this._checkOcclusionQuery();
  32032. if (this._isOccluded) {
  32033. return this;
  32034. }
  32035. var scene = this.getScene();
  32036. // Managing instances
  32037. var batch = this._getInstancesRenderList(subMesh._id);
  32038. if (batch.mustReturn) {
  32039. return this;
  32040. }
  32041. // Checking geometry state
  32042. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32043. return this;
  32044. }
  32045. if (this._onBeforeRenderObservable) {
  32046. this._onBeforeRenderObservable.notifyObservers(this);
  32047. }
  32048. var engine = scene.getEngine();
  32049. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32050. // Material
  32051. var material = subMesh.getMaterial();
  32052. if (!material) {
  32053. return this;
  32054. }
  32055. this._effectiveMaterial = material;
  32056. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32057. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32058. return this;
  32059. }
  32060. }
  32061. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32062. return this;
  32063. }
  32064. // Alpha mode
  32065. if (enableAlphaMode) {
  32066. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32067. }
  32068. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32069. var step = _a[_i];
  32070. step.action(this, subMesh, batch);
  32071. }
  32072. var effect;
  32073. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32074. effect = subMesh.effect;
  32075. }
  32076. else {
  32077. effect = this._effectiveMaterial.getEffect();
  32078. }
  32079. if (!effect) {
  32080. return this;
  32081. }
  32082. var sideOrientation = this.overrideMaterialSideOrientation;
  32083. if (sideOrientation == null) {
  32084. sideOrientation = this._effectiveMaterial.sideOrientation;
  32085. if (this._getWorldMatrixDeterminant() < 0) {
  32086. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32087. }
  32088. }
  32089. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32090. if (this._effectiveMaterial.forceDepthWrite) {
  32091. engine.setDepthWrite(true);
  32092. }
  32093. // Bind
  32094. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32095. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32096. this._bind(subMesh, effect, fillMode);
  32097. }
  32098. var world = this.getWorldMatrix();
  32099. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32100. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32101. }
  32102. else {
  32103. this._effectiveMaterial.bind(world, this);
  32104. }
  32105. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32106. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32107. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32108. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32109. }
  32110. // Draw
  32111. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32112. // Unbind
  32113. this._effectiveMaterial.unbind();
  32114. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32115. var step = _c[_b];
  32116. step.action(this, subMesh, batch);
  32117. }
  32118. if (this._onAfterRenderObservable) {
  32119. this._onAfterRenderObservable.notifyObservers(this);
  32120. }
  32121. return this;
  32122. };
  32123. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32124. if (isInstance && effectiveMaterial) {
  32125. effectiveMaterial.bindOnlyWorldMatrix(world);
  32126. }
  32127. };
  32128. /**
  32129. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32130. */
  32131. Mesh.prototype.getEmittedParticleSystems = function () {
  32132. var results = new Array();
  32133. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32134. var particleSystem = this.getScene().particleSystems[index];
  32135. if (particleSystem.emitter === this) {
  32136. results.push(particleSystem);
  32137. }
  32138. }
  32139. return results;
  32140. };
  32141. /**
  32142. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32143. */
  32144. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32145. var results = new Array();
  32146. var descendants = this.getDescendants();
  32147. descendants.push(this);
  32148. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32149. var particleSystem = this.getScene().particleSystems[index];
  32150. var emitter = particleSystem.emitter;
  32151. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32152. results.push(particleSystem);
  32153. }
  32154. }
  32155. return results;
  32156. };
  32157. /**
  32158. * Normalize matrix weights so that all vertices have a total weight set to 1
  32159. */
  32160. Mesh.prototype.cleanMatrixWeights = function () {
  32161. var epsilon = 1e-3;
  32162. var noInfluenceBoneIndex = 0.0;
  32163. if (this.skeleton) {
  32164. noInfluenceBoneIndex = this.skeleton.bones.length;
  32165. }
  32166. else {
  32167. return;
  32168. }
  32169. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32170. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32171. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32172. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32173. var influencers = this.numBoneInfluencers;
  32174. var size = matricesWeights.length;
  32175. for (var i = 0; i < size; i += 4) {
  32176. var weight = 0.0;
  32177. var firstZeroWeight = -1;
  32178. for (var j = 0; j < 4; j++) {
  32179. var w = matricesWeights[i + j];
  32180. weight += w;
  32181. if (w < epsilon && firstZeroWeight < 0) {
  32182. firstZeroWeight = j;
  32183. }
  32184. }
  32185. if (matricesWeightsExtra) {
  32186. for (var j = 0; j < 4; j++) {
  32187. var w = matricesWeightsExtra[i + j];
  32188. weight += w;
  32189. if (w < epsilon && firstZeroWeight < 0) {
  32190. firstZeroWeight = j + 4;
  32191. }
  32192. }
  32193. }
  32194. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32195. firstZeroWeight = influencers - 1;
  32196. }
  32197. if (weight > epsilon) {
  32198. var mweight = 1.0 / weight;
  32199. for (var j = 0; j < 4; j++) {
  32200. matricesWeights[i + j] *= mweight;
  32201. }
  32202. if (matricesWeightsExtra) {
  32203. for (var j = 0; j < 4; j++) {
  32204. matricesWeightsExtra[i + j] *= mweight;
  32205. }
  32206. }
  32207. }
  32208. else {
  32209. if (firstZeroWeight >= 4) {
  32210. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32211. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32212. }
  32213. else {
  32214. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32215. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32216. }
  32217. }
  32218. }
  32219. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32220. if (matricesIndicesExtra) {
  32221. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32222. }
  32223. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32224. if (matricesWeightsExtra) {
  32225. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32226. }
  32227. };
  32228. /** @hidden */
  32229. Mesh.prototype._checkDelayState = function () {
  32230. var scene = this.getScene();
  32231. if (this._geometry) {
  32232. this._geometry.load(scene);
  32233. }
  32234. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32235. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32236. this._queueLoad(scene);
  32237. }
  32238. return this;
  32239. };
  32240. Mesh.prototype._queueLoad = function (scene) {
  32241. var _this = this;
  32242. scene._addPendingData(this);
  32243. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32244. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32245. if (data instanceof ArrayBuffer) {
  32246. _this._delayLoadingFunction(data, _this);
  32247. }
  32248. else {
  32249. _this._delayLoadingFunction(JSON.parse(data), _this);
  32250. }
  32251. _this.instances.forEach(function (instance) {
  32252. instance._syncSubMeshes();
  32253. });
  32254. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32255. scene._removePendingData(_this);
  32256. }, function () { }, scene.database, getBinaryData);
  32257. return this;
  32258. };
  32259. /**
  32260. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32261. * A mesh is in the frustum if its bounding box intersects the frustum
  32262. * @param frustumPlanes defines the frustum to test
  32263. * @returns true if the mesh is in the frustum planes
  32264. */
  32265. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32266. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32267. return false;
  32268. }
  32269. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32270. return false;
  32271. }
  32272. this._checkDelayState();
  32273. return true;
  32274. };
  32275. /**
  32276. * Sets the mesh material by the material or multiMaterial `id` property.
  32277. * The material `id` is a string identifying the material or the multiMaterial.
  32278. * This method returns the Mesh.
  32279. */
  32280. Mesh.prototype.setMaterialByID = function (id) {
  32281. var materials = this.getScene().materials;
  32282. var index;
  32283. for (index = materials.length - 1; index > -1; index--) {
  32284. if (materials[index].id === id) {
  32285. this.material = materials[index];
  32286. return this;
  32287. }
  32288. }
  32289. // Multi
  32290. var multiMaterials = this.getScene().multiMaterials;
  32291. for (index = multiMaterials.length - 1; index > -1; index--) {
  32292. if (multiMaterials[index].id === id) {
  32293. this.material = multiMaterials[index];
  32294. return this;
  32295. }
  32296. }
  32297. return this;
  32298. };
  32299. /**
  32300. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32301. */
  32302. Mesh.prototype.getAnimatables = function () {
  32303. var results = new Array();
  32304. if (this.material) {
  32305. results.push(this.material);
  32306. }
  32307. if (this.skeleton) {
  32308. results.push(this.skeleton);
  32309. }
  32310. return results;
  32311. };
  32312. /**
  32313. * Modifies the mesh geometry according to the passed transformation matrix.
  32314. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32315. * The mesh normals are modified using the same transformation.
  32316. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32317. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32318. * Returns the Mesh.
  32319. */
  32320. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32321. // Position
  32322. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32323. return this;
  32324. }
  32325. var submeshes = this.subMeshes.splice(0);
  32326. this._resetPointsArrayCache();
  32327. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32328. var temp = new Array();
  32329. var index;
  32330. for (index = 0; index < data.length; index += 3) {
  32331. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32332. }
  32333. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32334. // Normals
  32335. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32336. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32337. temp = [];
  32338. for (index = 0; index < data.length; index += 3) {
  32339. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32340. }
  32341. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32342. }
  32343. // flip faces?
  32344. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32345. this.flipFaces();
  32346. }
  32347. // Restore submeshes
  32348. this.releaseSubMeshes();
  32349. this.subMeshes = submeshes;
  32350. return this;
  32351. };
  32352. /**
  32353. * Modifies the mesh geometry according to its own current World Matrix.
  32354. * The mesh World Matrix is then reset.
  32355. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32356. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32357. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32358. * Returns the Mesh.
  32359. */
  32360. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32361. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32362. this.scaling.copyFromFloats(1, 1, 1);
  32363. this.position.copyFromFloats(0, 0, 0);
  32364. this.rotation.copyFromFloats(0, 0, 0);
  32365. //only if quaternion is already set
  32366. if (this.rotationQuaternion) {
  32367. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32368. }
  32369. this._worldMatrix = BABYLON.Matrix.Identity();
  32370. return this;
  32371. };
  32372. Object.defineProperty(Mesh.prototype, "_positions", {
  32373. // Cache
  32374. get: function () {
  32375. if (this._geometry) {
  32376. return this._geometry._positions;
  32377. }
  32378. return null;
  32379. },
  32380. enumerable: true,
  32381. configurable: true
  32382. });
  32383. /** @hidden */
  32384. Mesh.prototype._resetPointsArrayCache = function () {
  32385. if (this._geometry) {
  32386. this._geometry._resetPointsArrayCache();
  32387. }
  32388. return this;
  32389. };
  32390. /** @hidden */
  32391. Mesh.prototype._generatePointsArray = function () {
  32392. if (this._geometry) {
  32393. return this._geometry._generatePointsArray();
  32394. }
  32395. return false;
  32396. };
  32397. /**
  32398. * Returns a new Mesh object generated from the current mesh properties.
  32399. * This method must not get confused with createInstance().
  32400. * The parameter `name` is a string, the name given to the new mesh.
  32401. * The optional parameter `newParent` can be any Node object (default `null`).
  32402. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32403. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  32404. */
  32405. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32406. if (name === void 0) { name = ""; }
  32407. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32408. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32409. };
  32410. /**
  32411. * Releases resources associated with this mesh.
  32412. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32413. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32414. */
  32415. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32416. var _this = this;
  32417. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32418. this.morphTargetManager = null;
  32419. if (this._geometry) {
  32420. this._geometry.releaseForMesh(this, true);
  32421. }
  32422. if (this._onBeforeDrawObservable) {
  32423. this._onBeforeDrawObservable.clear();
  32424. }
  32425. if (this._onBeforeRenderObservable) {
  32426. this._onBeforeRenderObservable.clear();
  32427. }
  32428. if (this._onAfterRenderObservable) {
  32429. this._onAfterRenderObservable.clear();
  32430. }
  32431. // Sources
  32432. var meshes = this.getScene().meshes;
  32433. meshes.forEach(function (abstractMesh) {
  32434. var mesh = abstractMesh;
  32435. if (mesh._source && mesh._source === _this) {
  32436. mesh._source = null;
  32437. }
  32438. });
  32439. this._source = null;
  32440. // Instances
  32441. if (this._instancesBuffer) {
  32442. this._instancesBuffer.dispose();
  32443. this._instancesBuffer = null;
  32444. }
  32445. while (this.instances.length) {
  32446. this.instances[0].dispose();
  32447. }
  32448. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32449. };
  32450. /**
  32451. * Modifies the mesh geometry according to a displacement map.
  32452. * 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.
  32453. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32454. * This method returns nothing.
  32455. * @param url is a string, the URL from the image file is to be downloaded.
  32456. * @param minHeight is the lower limit of the displacement.
  32457. * @param maxHeight is the upper limit of the displacement.
  32458. * @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.
  32459. * @param uvOffset is an optional vector2 used to offset UV.
  32460. * @param uvScale is an optional vector2 used to scale UV.
  32461. * @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.
  32462. * @returns the Mesh.
  32463. */
  32464. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32465. var _this = this;
  32466. if (forceUpdate === void 0) { forceUpdate = false; }
  32467. var scene = this.getScene();
  32468. var onload = function (img) {
  32469. // Getting height map data
  32470. var canvas = document.createElement("canvas");
  32471. var context = canvas.getContext("2d");
  32472. var heightMapWidth = img.width;
  32473. var heightMapHeight = img.height;
  32474. canvas.width = heightMapWidth;
  32475. canvas.height = heightMapHeight;
  32476. context.drawImage(img, 0, 0);
  32477. // Create VertexData from map data
  32478. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32479. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32480. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32481. //execute success callback, if set
  32482. if (onSuccess) {
  32483. onSuccess(_this);
  32484. }
  32485. };
  32486. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32487. return this;
  32488. };
  32489. /**
  32490. * Modifies the mesh geometry according to a displacementMap buffer.
  32491. * 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.
  32492. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32493. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32494. * @param heightMapWidth is the width of the buffer image.
  32495. * @param heightMapHeight is the height of the buffer image.
  32496. * @param minHeight is the lower limit of the displacement.
  32497. * @param maxHeight is the upper limit of the displacement.
  32498. * @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.
  32499. * @param uvOffset is an optional vector2 used to offset UV.
  32500. * @param uvScale is an optional vector2 used to scale UV.
  32501. * @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.
  32502. * @returns the Mesh.
  32503. */
  32504. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32505. if (forceUpdate === void 0) { forceUpdate = false; }
  32506. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32507. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32508. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32509. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32510. return this;
  32511. }
  32512. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32513. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32514. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32515. var position = BABYLON.Vector3.Zero();
  32516. var normal = BABYLON.Vector3.Zero();
  32517. var uv = BABYLON.Vector2.Zero();
  32518. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32519. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32520. for (var index = 0; index < positions.length; index += 3) {
  32521. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32522. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32523. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32524. // Compute height
  32525. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32526. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32527. var pos = (u + v * heightMapWidth) * 4;
  32528. var r = buffer[pos] / 255.0;
  32529. var g = buffer[pos + 1] / 255.0;
  32530. var b = buffer[pos + 2] / 255.0;
  32531. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32532. normal.normalize();
  32533. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32534. position = position.add(normal);
  32535. position.toArray(positions, index);
  32536. }
  32537. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32538. if (forceUpdate) {
  32539. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32540. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32541. }
  32542. else {
  32543. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32544. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32545. }
  32546. return this;
  32547. };
  32548. /**
  32549. * Modify the mesh to get a flat shading rendering.
  32550. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32551. * This method returns the Mesh.
  32552. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32553. */
  32554. Mesh.prototype.convertToFlatShadedMesh = function () {
  32555. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32556. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32557. var kinds = this.getVerticesDataKinds();
  32558. var vbs = {};
  32559. var data = {};
  32560. var newdata = {};
  32561. var updatableNormals = false;
  32562. var kindIndex;
  32563. var kind;
  32564. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32565. kind = kinds[kindIndex];
  32566. var vertexBuffer = this.getVertexBuffer(kind);
  32567. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32568. updatableNormals = vertexBuffer.isUpdatable();
  32569. kinds.splice(kindIndex, 1);
  32570. kindIndex--;
  32571. continue;
  32572. }
  32573. vbs[kind] = vertexBuffer;
  32574. data[kind] = vbs[kind].getData();
  32575. newdata[kind] = [];
  32576. }
  32577. // Save previous submeshes
  32578. var previousSubmeshes = this.subMeshes.slice(0);
  32579. var indices = this.getIndices();
  32580. var totalIndices = this.getTotalIndices();
  32581. // Generating unique vertices per face
  32582. var index;
  32583. for (index = 0; index < totalIndices; index++) {
  32584. var vertexIndex = indices[index];
  32585. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32586. kind = kinds[kindIndex];
  32587. var stride = vbs[kind].getStrideSize();
  32588. for (var offset = 0; offset < stride; offset++) {
  32589. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32590. }
  32591. }
  32592. }
  32593. // Updating faces & normal
  32594. var normals = [];
  32595. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32596. for (index = 0; index < totalIndices; index += 3) {
  32597. indices[index] = index;
  32598. indices[index + 1] = index + 1;
  32599. indices[index + 2] = index + 2;
  32600. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32601. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32602. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32603. var p1p2 = p1.subtract(p2);
  32604. var p3p2 = p3.subtract(p2);
  32605. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32606. // Store same normals for every vertex
  32607. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32608. normals.push(normal.x);
  32609. normals.push(normal.y);
  32610. normals.push(normal.z);
  32611. }
  32612. }
  32613. this.setIndices(indices);
  32614. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32615. // Updating vertex buffers
  32616. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32617. kind = kinds[kindIndex];
  32618. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32619. }
  32620. // Updating submeshes
  32621. this.releaseSubMeshes();
  32622. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32623. var previousOne = previousSubmeshes[submeshIndex];
  32624. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32625. }
  32626. this.synchronizeInstances();
  32627. return this;
  32628. };
  32629. /**
  32630. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32631. * In other words, more vertices, no more indices and a single bigger VBO.
  32632. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32633. * Returns the Mesh.
  32634. */
  32635. Mesh.prototype.convertToUnIndexedMesh = function () {
  32636. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32637. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32638. var kinds = this.getVerticesDataKinds();
  32639. var vbs = {};
  32640. var data = {};
  32641. var newdata = {};
  32642. var kindIndex;
  32643. var kind;
  32644. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32645. kind = kinds[kindIndex];
  32646. var vertexBuffer = this.getVertexBuffer(kind);
  32647. vbs[kind] = vertexBuffer;
  32648. data[kind] = vbs[kind].getData();
  32649. newdata[kind] = [];
  32650. }
  32651. // Save previous submeshes
  32652. var previousSubmeshes = this.subMeshes.slice(0);
  32653. var indices = this.getIndices();
  32654. var totalIndices = this.getTotalIndices();
  32655. // Generating unique vertices per face
  32656. var index;
  32657. for (index = 0; index < totalIndices; index++) {
  32658. var vertexIndex = indices[index];
  32659. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32660. kind = kinds[kindIndex];
  32661. var stride = vbs[kind].getStrideSize();
  32662. for (var offset = 0; offset < stride; offset++) {
  32663. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32664. }
  32665. }
  32666. }
  32667. // Updating indices
  32668. for (index = 0; index < totalIndices; index += 3) {
  32669. indices[index] = index;
  32670. indices[index + 1] = index + 1;
  32671. indices[index + 2] = index + 2;
  32672. }
  32673. this.setIndices(indices);
  32674. // Updating vertex buffers
  32675. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32676. kind = kinds[kindIndex];
  32677. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32678. }
  32679. // Updating submeshes
  32680. this.releaseSubMeshes();
  32681. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32682. var previousOne = previousSubmeshes[submeshIndex];
  32683. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32684. }
  32685. this._unIndexed = true;
  32686. this.synchronizeInstances();
  32687. return this;
  32688. };
  32689. /**
  32690. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32691. * This method returns the Mesh.
  32692. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32693. */
  32694. Mesh.prototype.flipFaces = function (flipNormals) {
  32695. if (flipNormals === void 0) { flipNormals = false; }
  32696. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32697. var i;
  32698. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32699. for (i = 0; i < vertex_data.normals.length; i++) {
  32700. vertex_data.normals[i] *= -1;
  32701. }
  32702. }
  32703. if (vertex_data.indices) {
  32704. var temp;
  32705. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32706. // reassign indices
  32707. temp = vertex_data.indices[i + 1];
  32708. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32709. vertex_data.indices[i + 2] = temp;
  32710. }
  32711. }
  32712. vertex_data.applyToMesh(this);
  32713. return this;
  32714. };
  32715. // Instances
  32716. /**
  32717. * Creates a new InstancedMesh object from the mesh model.
  32718. * An instance shares the same properties and the same material than its model.
  32719. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  32720. * Only these properties of each instance can then be set individually :
  32721. * - position
  32722. * - rotation
  32723. * - rotationQuaternion
  32724. * - setPivotMatrix
  32725. * - scaling
  32726. *
  32727. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32728. * Warning : this method is not supported for Line mesh and LineSystem
  32729. */
  32730. Mesh.prototype.createInstance = function (name) {
  32731. return new BABYLON.InstancedMesh(name, this);
  32732. };
  32733. /**
  32734. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32735. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32736. * This method returns the Mesh.
  32737. */
  32738. Mesh.prototype.synchronizeInstances = function () {
  32739. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32740. var instance = this.instances[instanceIndex];
  32741. instance._syncSubMeshes();
  32742. }
  32743. return this;
  32744. };
  32745. /**
  32746. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32747. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32748. * This should be used together with the simplification to avoid disappearing triangles.
  32749. * Returns the Mesh.
  32750. * @param successCallback an optional success callback to be called after the optimization finished.
  32751. */
  32752. Mesh.prototype.optimizeIndices = function (successCallback) {
  32753. var _this = this;
  32754. var indices = this.getIndices();
  32755. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32756. if (!positions || !indices) {
  32757. return this;
  32758. }
  32759. var vectorPositions = new Array();
  32760. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32761. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32762. }
  32763. var dupes = new Array();
  32764. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32765. var realPos = vectorPositions.length - 1 - iteration;
  32766. var testedPosition = vectorPositions[realPos];
  32767. for (var j = 0; j < realPos; ++j) {
  32768. var againstPosition = vectorPositions[j];
  32769. if (testedPosition.equals(againstPosition)) {
  32770. dupes[realPos] = j;
  32771. break;
  32772. }
  32773. }
  32774. }, function () {
  32775. for (var i = 0; i < indices.length; ++i) {
  32776. indices[i] = dupes[indices[i]] || indices[i];
  32777. }
  32778. //indices are now reordered
  32779. var originalSubMeshes = _this.subMeshes.slice(0);
  32780. _this.setIndices(indices);
  32781. _this.subMeshes = originalSubMeshes;
  32782. if (successCallback) {
  32783. successCallback(_this);
  32784. }
  32785. });
  32786. return this;
  32787. };
  32788. Mesh.prototype.serialize = function (serializationObject) {
  32789. serializationObject.name = this.name;
  32790. serializationObject.id = this.id;
  32791. serializationObject.type = this.getClassName();
  32792. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32793. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32794. }
  32795. serializationObject.position = this.position.asArray();
  32796. if (this.rotationQuaternion) {
  32797. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32798. }
  32799. else if (this.rotation) {
  32800. serializationObject.rotation = this.rotation.asArray();
  32801. }
  32802. serializationObject.scaling = this.scaling.asArray();
  32803. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32804. serializationObject.isEnabled = this.isEnabled(false);
  32805. serializationObject.isVisible = this.isVisible;
  32806. serializationObject.infiniteDistance = this.infiniteDistance;
  32807. serializationObject.pickable = this.isPickable;
  32808. serializationObject.receiveShadows = this.receiveShadows;
  32809. serializationObject.billboardMode = this.billboardMode;
  32810. serializationObject.visibility = this.visibility;
  32811. serializationObject.checkCollisions = this.checkCollisions;
  32812. serializationObject.isBlocker = this.isBlocker;
  32813. // Parent
  32814. if (this.parent) {
  32815. serializationObject.parentId = this.parent.id;
  32816. }
  32817. // Geometry
  32818. serializationObject.isUnIndexed = this.isUnIndexed;
  32819. var geometry = this._geometry;
  32820. if (geometry) {
  32821. var geometryId = geometry.id;
  32822. serializationObject.geometryId = geometryId;
  32823. // SubMeshes
  32824. serializationObject.subMeshes = [];
  32825. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32826. var subMesh = this.subMeshes[subIndex];
  32827. serializationObject.subMeshes.push({
  32828. materialIndex: subMesh.materialIndex,
  32829. verticesStart: subMesh.verticesStart,
  32830. verticesCount: subMesh.verticesCount,
  32831. indexStart: subMesh.indexStart,
  32832. indexCount: subMesh.indexCount
  32833. });
  32834. }
  32835. }
  32836. // Material
  32837. if (this.material) {
  32838. serializationObject.materialId = this.material.id;
  32839. }
  32840. else {
  32841. this.material = null;
  32842. }
  32843. // Morph targets
  32844. if (this.morphTargetManager) {
  32845. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32846. }
  32847. // Skeleton
  32848. if (this.skeleton) {
  32849. serializationObject.skeletonId = this.skeleton.id;
  32850. }
  32851. // Physics
  32852. //TODO implement correct serialization for physics impostors.
  32853. var impostor = this.getPhysicsImpostor();
  32854. if (impostor) {
  32855. serializationObject.physicsMass = impostor.getParam("mass");
  32856. serializationObject.physicsFriction = impostor.getParam("friction");
  32857. serializationObject.physicsRestitution = impostor.getParam("mass");
  32858. serializationObject.physicsImpostor = impostor.type;
  32859. }
  32860. // Metadata
  32861. if (this.metadata) {
  32862. serializationObject.metadata = this.metadata;
  32863. }
  32864. // Instances
  32865. serializationObject.instances = [];
  32866. for (var index = 0; index < this.instances.length; index++) {
  32867. var instance = this.instances[index];
  32868. if (instance.doNotSerialize) {
  32869. continue;
  32870. }
  32871. var serializationInstance = {
  32872. name: instance.name,
  32873. id: instance.id,
  32874. position: instance.position.asArray(),
  32875. scaling: instance.scaling.asArray()
  32876. };
  32877. if (instance.parent) {
  32878. serializationInstance.parentId = instance.parent.id;
  32879. }
  32880. if (instance.rotationQuaternion) {
  32881. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32882. }
  32883. else if (instance.rotation) {
  32884. serializationInstance.rotation = instance.rotation.asArray();
  32885. }
  32886. serializationObject.instances.push(serializationInstance);
  32887. // Animations
  32888. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32889. serializationInstance.ranges = instance.serializeAnimationRanges();
  32890. }
  32891. //
  32892. // Animations
  32893. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32894. serializationObject.ranges = this.serializeAnimationRanges();
  32895. // Layer mask
  32896. serializationObject.layerMask = this.layerMask;
  32897. // Alpha
  32898. serializationObject.alphaIndex = this.alphaIndex;
  32899. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32900. // Overlay
  32901. serializationObject.overlayAlpha = this.overlayAlpha;
  32902. serializationObject.overlayColor = this.overlayColor.asArray();
  32903. serializationObject.renderOverlay = this.renderOverlay;
  32904. // Fog
  32905. serializationObject.applyFog = this.applyFog;
  32906. // Action Manager
  32907. if (this.actionManager) {
  32908. serializationObject.actions = this.actionManager.serialize(this.name);
  32909. }
  32910. };
  32911. /** @hidden */
  32912. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32913. if (!this.geometry) {
  32914. return;
  32915. }
  32916. this._markSubMeshesAsAttributesDirty();
  32917. var morphTargetManager = this._morphTargetManager;
  32918. if (morphTargetManager && morphTargetManager.vertexCount) {
  32919. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32920. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32921. this.morphTargetManager = null;
  32922. return;
  32923. }
  32924. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32925. var morphTarget = morphTargetManager.getActiveTarget(index);
  32926. var positions = morphTarget.getPositions();
  32927. if (!positions) {
  32928. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32929. return;
  32930. }
  32931. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32932. var normals = morphTarget.getNormals();
  32933. if (normals) {
  32934. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32935. }
  32936. var tangents = morphTarget.getTangents();
  32937. if (tangents) {
  32938. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32939. }
  32940. }
  32941. }
  32942. else {
  32943. var index = 0;
  32944. // Positions
  32945. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32946. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32947. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32948. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32949. }
  32950. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32951. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32952. }
  32953. index++;
  32954. }
  32955. }
  32956. };
  32957. // Statics
  32958. /**
  32959. * Returns a new Mesh object parsed from the source provided.
  32960. * The parameter `parsedMesh` is the source.
  32961. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32962. */
  32963. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32964. var mesh;
  32965. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32966. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32967. }
  32968. else {
  32969. mesh = new Mesh(parsedMesh.name, scene);
  32970. }
  32971. mesh.id = parsedMesh.id;
  32972. if (BABYLON.Tags) {
  32973. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32974. }
  32975. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32976. if (parsedMesh.metadata !== undefined) {
  32977. mesh.metadata = parsedMesh.metadata;
  32978. }
  32979. if (parsedMesh.rotationQuaternion) {
  32980. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32981. }
  32982. else if (parsedMesh.rotation) {
  32983. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32984. }
  32985. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32986. if (parsedMesh.localMatrix) {
  32987. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32988. }
  32989. else if (parsedMesh.pivotMatrix) {
  32990. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32991. }
  32992. mesh.setEnabled(parsedMesh.isEnabled);
  32993. mesh.isVisible = parsedMesh.isVisible;
  32994. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32995. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32996. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32997. if (parsedMesh.applyFog !== undefined) {
  32998. mesh.applyFog = parsedMesh.applyFog;
  32999. }
  33000. if (parsedMesh.pickable !== undefined) {
  33001. mesh.isPickable = parsedMesh.pickable;
  33002. }
  33003. if (parsedMesh.alphaIndex !== undefined) {
  33004. mesh.alphaIndex = parsedMesh.alphaIndex;
  33005. }
  33006. mesh.receiveShadows = parsedMesh.receiveShadows;
  33007. mesh.billboardMode = parsedMesh.billboardMode;
  33008. if (parsedMesh.visibility !== undefined) {
  33009. mesh.visibility = parsedMesh.visibility;
  33010. }
  33011. mesh.checkCollisions = parsedMesh.checkCollisions;
  33012. if (parsedMesh.isBlocker !== undefined) {
  33013. mesh.isBlocker = parsedMesh.isBlocker;
  33014. }
  33015. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33016. // freezeWorldMatrix
  33017. if (parsedMesh.freezeWorldMatrix) {
  33018. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33019. }
  33020. // Parent
  33021. if (parsedMesh.parentId) {
  33022. mesh._waitingParentId = parsedMesh.parentId;
  33023. }
  33024. // Actions
  33025. if (parsedMesh.actions !== undefined) {
  33026. mesh._waitingActions = parsedMesh.actions;
  33027. }
  33028. // Overlay
  33029. if (parsedMesh.overlayAlpha !== undefined) {
  33030. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33031. }
  33032. if (parsedMesh.overlayColor !== undefined) {
  33033. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33034. }
  33035. if (parsedMesh.renderOverlay !== undefined) {
  33036. mesh.renderOverlay = parsedMesh.renderOverlay;
  33037. }
  33038. // Geometry
  33039. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33040. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33041. if (parsedMesh.delayLoadingFile) {
  33042. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33043. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33044. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33045. if (parsedMesh._binaryInfo) {
  33046. mesh._binaryInfo = parsedMesh._binaryInfo;
  33047. }
  33048. mesh._delayInfo = [];
  33049. if (parsedMesh.hasUVs) {
  33050. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33051. }
  33052. if (parsedMesh.hasUVs2) {
  33053. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33054. }
  33055. if (parsedMesh.hasUVs3) {
  33056. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33057. }
  33058. if (parsedMesh.hasUVs4) {
  33059. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33060. }
  33061. if (parsedMesh.hasUVs5) {
  33062. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33063. }
  33064. if (parsedMesh.hasUVs6) {
  33065. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33066. }
  33067. if (parsedMesh.hasColors) {
  33068. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33069. }
  33070. if (parsedMesh.hasMatricesIndices) {
  33071. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33072. }
  33073. if (parsedMesh.hasMatricesWeights) {
  33074. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33075. }
  33076. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33077. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33078. mesh._checkDelayState();
  33079. }
  33080. }
  33081. else {
  33082. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33083. }
  33084. // Material
  33085. if (parsedMesh.materialId) {
  33086. mesh.setMaterialByID(parsedMesh.materialId);
  33087. }
  33088. else {
  33089. mesh.material = null;
  33090. }
  33091. // Morph targets
  33092. if (parsedMesh.morphTargetManagerId > -1) {
  33093. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33094. }
  33095. // Skeleton
  33096. if (parsedMesh.skeletonId > -1) {
  33097. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33098. if (parsedMesh.numBoneInfluencers) {
  33099. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33100. }
  33101. }
  33102. // Animations
  33103. if (parsedMesh.animations) {
  33104. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33105. var parsedAnimation = parsedMesh.animations[animationIndex];
  33106. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33107. }
  33108. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33109. }
  33110. if (parsedMesh.autoAnimate) {
  33111. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33112. }
  33113. // Layer Mask
  33114. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33115. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33116. }
  33117. else {
  33118. mesh.layerMask = 0x0FFFFFFF;
  33119. }
  33120. // Physics
  33121. if (parsedMesh.physicsImpostor) {
  33122. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33123. mass: parsedMesh.physicsMass,
  33124. friction: parsedMesh.physicsFriction,
  33125. restitution: parsedMesh.physicsRestitution
  33126. }, scene);
  33127. }
  33128. // Instances
  33129. if (parsedMesh.instances) {
  33130. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33131. var parsedInstance = parsedMesh.instances[index];
  33132. var instance = mesh.createInstance(parsedInstance.name);
  33133. if (parsedInstance.id) {
  33134. instance.id = parsedInstance.id;
  33135. }
  33136. if (BABYLON.Tags) {
  33137. if (parsedInstance.tags) {
  33138. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33139. }
  33140. else {
  33141. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33142. }
  33143. }
  33144. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33145. if (parsedInstance.parentId) {
  33146. instance._waitingParentId = parsedInstance.parentId;
  33147. }
  33148. if (parsedInstance.rotationQuaternion) {
  33149. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33150. }
  33151. else if (parsedInstance.rotation) {
  33152. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33153. }
  33154. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33155. instance.checkCollisions = mesh.checkCollisions;
  33156. if (parsedMesh.animations) {
  33157. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33158. parsedAnimation = parsedMesh.animations[animationIndex];
  33159. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33160. }
  33161. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33162. if (parsedMesh.autoAnimate) {
  33163. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33164. }
  33165. }
  33166. }
  33167. }
  33168. return mesh;
  33169. };
  33170. /**
  33171. * Creates a ribbon mesh.
  33172. * Please consider using the same method from the MeshBuilder class instead.
  33173. * The ribbon is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33174. *
  33175. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33176. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33177. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33178. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33179. * 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.
  33180. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  33181. * 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
  33182. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33183. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33184. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33185. */
  33186. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33187. if (closeArray === void 0) { closeArray = false; }
  33188. if (updatable === void 0) { updatable = false; }
  33189. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33190. pathArray: pathArray,
  33191. closeArray: closeArray,
  33192. closePath: closePath,
  33193. offset: offset,
  33194. updatable: updatable,
  33195. sideOrientation: sideOrientation,
  33196. instance: instance
  33197. }, scene);
  33198. };
  33199. /**
  33200. * Creates a plane polygonal mesh. By default, this is a disc.
  33201. * Please consider using the same method from the MeshBuilder class instead.
  33202. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33203. * 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.
  33204. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33205. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33206. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33207. */
  33208. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33209. if (scene === void 0) { scene = null; }
  33210. var options = {
  33211. radius: radius,
  33212. tessellation: tessellation,
  33213. sideOrientation: sideOrientation,
  33214. updatable: updatable
  33215. };
  33216. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33217. };
  33218. /**
  33219. * Creates a box mesh.
  33220. * Please consider using the same method from the MeshBuilder class instead.
  33221. * The parameter `size` sets the size (float) of each box side (default 1).
  33222. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33223. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33224. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33225. */
  33226. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33227. if (scene === void 0) { scene = null; }
  33228. var options = {
  33229. size: size,
  33230. sideOrientation: sideOrientation,
  33231. updatable: updatable
  33232. };
  33233. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33234. };
  33235. /**
  33236. * Creates a sphere mesh.
  33237. * Please consider using the same method from the MeshBuilder class instead.
  33238. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33239. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33240. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33241. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33242. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33243. */
  33244. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33245. var options = {
  33246. segments: segments,
  33247. diameterX: diameter,
  33248. diameterY: diameter,
  33249. diameterZ: diameter,
  33250. sideOrientation: sideOrientation,
  33251. updatable: updatable
  33252. };
  33253. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33254. };
  33255. /**
  33256. * Creates a cylinder or a cone mesh.
  33257. * Please consider using the same method from the MeshBuilder class instead.
  33258. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33259. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33260. * 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.
  33261. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33262. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33263. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33264. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33265. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33266. */
  33267. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33268. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33269. if (scene !== undefined) {
  33270. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33271. updatable = scene;
  33272. }
  33273. scene = subdivisions;
  33274. subdivisions = 1;
  33275. }
  33276. var options = {
  33277. height: height,
  33278. diameterTop: diameterTop,
  33279. diameterBottom: diameterBottom,
  33280. tessellation: tessellation,
  33281. subdivisions: subdivisions,
  33282. sideOrientation: sideOrientation,
  33283. updatable: updatable
  33284. };
  33285. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33286. };
  33287. // Torus (Code from SharpDX.org)
  33288. /**
  33289. * Creates a torus mesh.
  33290. * Please consider using the same method from the MeshBuilder class instead.
  33291. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33292. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33293. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33294. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33295. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33296. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33297. */
  33298. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33299. var options = {
  33300. diameter: diameter,
  33301. thickness: thickness,
  33302. tessellation: tessellation,
  33303. sideOrientation: sideOrientation,
  33304. updatable: updatable
  33305. };
  33306. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33307. };
  33308. /**
  33309. * Creates a torus knot mesh.
  33310. * Please consider using the same method from the MeshBuilder class instead.
  33311. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33312. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33313. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33314. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33315. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33316. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33317. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33318. */
  33319. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33320. var options = {
  33321. radius: radius,
  33322. tube: tube,
  33323. radialSegments: radialSegments,
  33324. tubularSegments: tubularSegments,
  33325. p: p,
  33326. q: q,
  33327. sideOrientation: sideOrientation,
  33328. updatable: updatable
  33329. };
  33330. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33331. };
  33332. /**
  33333. * Creates a line mesh.
  33334. * Please consider using the same method from the MeshBuilder class instead.
  33335. * 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.
  33336. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33337. * The parameter `points` is an array successive Vector3.
  33338. * 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
  33339. * When updating an instance, remember that only point positions can change, not the number of points.
  33340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33341. */
  33342. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33343. if (scene === void 0) { scene = null; }
  33344. if (updatable === void 0) { updatable = false; }
  33345. if (instance === void 0) { instance = null; }
  33346. var options = {
  33347. points: points,
  33348. updatable: updatable,
  33349. instance: instance
  33350. };
  33351. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33352. };
  33353. /**
  33354. * Creates a dashed line mesh.
  33355. * Please consider using the same method from the MeshBuilder class instead.
  33356. * 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.
  33357. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33358. * The parameter `points` is an array successive Vector3.
  33359. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33360. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33361. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33362. * 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
  33363. * When updating an instance, remember that only point positions can change, not the number of points.
  33364. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33365. */
  33366. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33367. if (scene === void 0) { scene = null; }
  33368. var options = {
  33369. points: points,
  33370. dashSize: dashSize,
  33371. gapSize: gapSize,
  33372. dashNb: dashNb,
  33373. updatable: updatable,
  33374. instance: instance
  33375. };
  33376. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33377. };
  33378. /**
  33379. * Creates a polygon mesh.
  33380. * Please consider using the same method from the MeshBuilder class instead.
  33381. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33382. * 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.
  33383. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33384. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33385. * Remember you can only change the shape positions, not their number when updating a polygon.
  33386. */
  33387. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33388. var options = {
  33389. shape: shape,
  33390. holes: holes,
  33391. updatable: updatable,
  33392. sideOrientation: sideOrientation
  33393. };
  33394. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33395. };
  33396. /**
  33397. * Creates an extruded polygon mesh, with depth in the Y direction.
  33398. * Please consider using the same method from the MeshBuilder class instead.
  33399. */
  33400. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33401. var options = {
  33402. shape: shape,
  33403. holes: holes,
  33404. depth: depth,
  33405. updatable: updatable,
  33406. sideOrientation: sideOrientation
  33407. };
  33408. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33409. };
  33410. /**
  33411. * Creates an extruded shape mesh.
  33412. * The extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33413. * Please consider using the same method from the MeshBuilder class instead.
  33414. *
  33415. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33416. * 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
  33417. * extruded along the Z axis.
  33418. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33419. * 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.
  33420. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33421. * 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
  33422. * 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
  33423. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33424. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33425. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33426. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33427. */
  33428. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33429. if (scene === void 0) { scene = null; }
  33430. var options = {
  33431. shape: shape,
  33432. path: path,
  33433. scale: scale,
  33434. rotation: rotation,
  33435. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33436. sideOrientation: sideOrientation,
  33437. instance: instance,
  33438. updatable: updatable
  33439. };
  33440. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33441. };
  33442. /**
  33443. * Creates an custom extruded shape mesh.
  33444. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33445. * Please consider using the same method from the MeshBuilder class instead.
  33446. *
  33447. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33448. * 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
  33449. * extruded along the Z axis.
  33450. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33451. * 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
  33452. * and the distance of this point from the begining of the path :
  33453. * ```javascript
  33454. * var rotationFunction = function(i, distance) {
  33455. * // do things
  33456. * return rotationValue; }
  33457. * ```
  33458. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33459. * 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
  33460. * and the distance of this point from the begining of the path :
  33461. * ```javascript
  33462. * var scaleFunction = function(i, distance) {
  33463. * // do things
  33464. * return scaleValue;}
  33465. * ```
  33466. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33467. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33468. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33469. * 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
  33470. * 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
  33471. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33472. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33473. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33474. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33475. */
  33476. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33477. var options = {
  33478. shape: shape,
  33479. path: path,
  33480. scaleFunction: scaleFunction,
  33481. rotationFunction: rotationFunction,
  33482. ribbonCloseArray: ribbonCloseArray,
  33483. ribbonClosePath: ribbonClosePath,
  33484. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33485. sideOrientation: sideOrientation,
  33486. instance: instance,
  33487. updatable: updatable
  33488. };
  33489. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33490. };
  33491. /**
  33492. * Creates lathe mesh.
  33493. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33494. * Please consider using the same method from the MeshBuilder class instead.
  33495. * 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
  33496. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33497. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33498. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33499. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33500. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33501. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33502. */
  33503. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33504. var options = {
  33505. shape: shape,
  33506. radius: radius,
  33507. tessellation: tessellation,
  33508. sideOrientation: sideOrientation,
  33509. updatable: updatable
  33510. };
  33511. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33512. };
  33513. /**
  33514. * Creates a plane mesh.
  33515. * Please consider using the same method from the MeshBuilder class instead.
  33516. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33517. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33518. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33519. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33520. */
  33521. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33522. var options = {
  33523. size: size,
  33524. width: size,
  33525. height: size,
  33526. sideOrientation: sideOrientation,
  33527. updatable: updatable
  33528. };
  33529. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33530. };
  33531. /**
  33532. * Creates a ground mesh.
  33533. * Please consider using the same method from the MeshBuilder class instead.
  33534. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33535. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33537. */
  33538. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33539. var options = {
  33540. width: width,
  33541. height: height,
  33542. subdivisions: subdivisions,
  33543. updatable: updatable
  33544. };
  33545. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33546. };
  33547. /**
  33548. * Creates a tiled ground mesh.
  33549. * Please consider using the same method from the MeshBuilder class instead.
  33550. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33551. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33552. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33553. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33554. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33555. * numbers of subdivisions on the ground width and height of each tile.
  33556. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33557. */
  33558. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33559. var options = {
  33560. xmin: xmin,
  33561. zmin: zmin,
  33562. xmax: xmax,
  33563. zmax: zmax,
  33564. subdivisions: subdivisions,
  33565. precision: precision,
  33566. updatable: updatable
  33567. };
  33568. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33569. };
  33570. /**
  33571. * Creates a ground mesh from a height map.
  33572. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33573. * Please consider using the same method from the MeshBuilder class instead.
  33574. * The parameter `url` sets the URL of the height map image resource.
  33575. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33576. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33577. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33578. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33579. * 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).
  33580. * This function is passed the newly built mesh :
  33581. * ```javascript
  33582. * function(mesh) { // do things
  33583. * return; }
  33584. * ```
  33585. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33586. */
  33587. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33588. var options = {
  33589. width: width,
  33590. height: height,
  33591. subdivisions: subdivisions,
  33592. minHeight: minHeight,
  33593. maxHeight: maxHeight,
  33594. updatable: updatable,
  33595. onReady: onReady
  33596. };
  33597. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33598. };
  33599. /**
  33600. * Creates a tube mesh.
  33601. * The tube is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33602. * Please consider using the same method from the MeshBuilder class instead.
  33603. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33604. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33605. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33606. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33607. * 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.
  33608. * It must return a radius value (positive float) :
  33609. * ```javascript
  33610. * var radiusFunction = function(i, distance) {
  33611. * // do things
  33612. * return radius; }
  33613. * ```
  33614. * 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
  33615. * 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
  33616. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33617. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33618. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33619. */
  33620. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33621. var options = {
  33622. path: path,
  33623. radius: radius,
  33624. tessellation: tessellation,
  33625. radiusFunction: radiusFunction,
  33626. arc: 1,
  33627. cap: cap,
  33628. updatable: updatable,
  33629. sideOrientation: sideOrientation,
  33630. instance: instance
  33631. };
  33632. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33633. };
  33634. /**
  33635. * Creates a polyhedron mesh.
  33636. * Please consider using the same method from the MeshBuilder class instead.
  33637. * 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
  33638. * to choose the wanted type.
  33639. * The parameter `size` (positive float, default 1) sets the polygon size.
  33640. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33641. * 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`.
  33642. * 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
  33643. * 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)`).
  33644. * 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
  33645. * 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.
  33646. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33647. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33648. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33649. */
  33650. Mesh.CreatePolyhedron = function (name, options, scene) {
  33651. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33652. };
  33653. /**
  33654. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33655. * Please consider using the same method from the MeshBuilder class instead.
  33656. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33657. * 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`).
  33658. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33659. * 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.
  33660. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33661. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33662. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33663. */
  33664. Mesh.CreateIcoSphere = function (name, options, scene) {
  33665. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33666. };
  33667. /**
  33668. * Creates a decal mesh.
  33669. * Please consider using the same method from the MeshBuilder class instead.
  33670. * 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.
  33671. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33672. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33673. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33674. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33675. */
  33676. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33677. var options = {
  33678. position: position,
  33679. normal: normal,
  33680. size: size,
  33681. angle: angle
  33682. };
  33683. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33684. };
  33685. // Skeletons
  33686. /**
  33687. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33688. */
  33689. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33690. if (!this._sourcePositions) {
  33691. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33692. if (!source) {
  33693. return this._sourcePositions;
  33694. }
  33695. this._sourcePositions = new Float32Array(source);
  33696. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33697. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33698. }
  33699. }
  33700. return this._sourcePositions;
  33701. };
  33702. /**
  33703. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33704. */
  33705. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33706. if (!this._sourceNormals) {
  33707. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33708. if (!source) {
  33709. return this._sourceNormals;
  33710. }
  33711. this._sourceNormals = new Float32Array(source);
  33712. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33713. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33714. }
  33715. }
  33716. return this._sourceNormals;
  33717. };
  33718. /**
  33719. * Updates the vertex buffer by applying transformation from the bones.
  33720. * Returns the Mesh.
  33721. *
  33722. * @param {skeleton} skeleton to apply
  33723. */
  33724. Mesh.prototype.applySkeleton = function (skeleton) {
  33725. if (!this.geometry) {
  33726. return this;
  33727. }
  33728. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33729. return this;
  33730. }
  33731. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33732. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33733. return this;
  33734. }
  33735. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33736. return this;
  33737. }
  33738. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33739. return this;
  33740. }
  33741. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33742. return this;
  33743. }
  33744. if (!this._sourcePositions) {
  33745. var submeshes = this.subMeshes.slice();
  33746. this.setPositionsForCPUSkinning();
  33747. this.subMeshes = submeshes;
  33748. }
  33749. if (!this._sourceNormals) {
  33750. this.setNormalsForCPUSkinning();
  33751. }
  33752. // positionsData checks for not being Float32Array will only pass at most once
  33753. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33754. if (!positionsData) {
  33755. return this;
  33756. }
  33757. if (!(positionsData instanceof Float32Array)) {
  33758. positionsData = new Float32Array(positionsData);
  33759. }
  33760. // normalsData checks for not being Float32Array will only pass at most once
  33761. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33762. if (!normalsData) {
  33763. return this;
  33764. }
  33765. if (!(normalsData instanceof Float32Array)) {
  33766. normalsData = new Float32Array(normalsData);
  33767. }
  33768. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33769. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33770. if (!matricesWeightsData || !matricesIndicesData) {
  33771. return this;
  33772. }
  33773. var needExtras = this.numBoneInfluencers > 4;
  33774. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33775. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33776. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33777. var tempVector3 = BABYLON.Vector3.Zero();
  33778. var finalMatrix = new BABYLON.Matrix();
  33779. var tempMatrix = new BABYLON.Matrix();
  33780. var matWeightIdx = 0;
  33781. var inf;
  33782. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33783. var weight;
  33784. for (inf = 0; inf < 4; inf++) {
  33785. weight = matricesWeightsData[matWeightIdx + inf];
  33786. if (weight > 0) {
  33787. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33788. finalMatrix.addToSelf(tempMatrix);
  33789. }
  33790. }
  33791. if (needExtras) {
  33792. for (inf = 0; inf < 4; inf++) {
  33793. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33794. if (weight > 0) {
  33795. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33796. finalMatrix.addToSelf(tempMatrix);
  33797. }
  33798. }
  33799. }
  33800. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33801. tempVector3.toArray(positionsData, index);
  33802. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33803. tempVector3.toArray(normalsData, index);
  33804. finalMatrix.reset();
  33805. }
  33806. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33807. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33808. return this;
  33809. };
  33810. // Tools
  33811. /**
  33812. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33813. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33814. */
  33815. Mesh.MinMax = function (meshes) {
  33816. var minVector = null;
  33817. var maxVector = null;
  33818. meshes.forEach(function (mesh, index, array) {
  33819. var boundingInfo = mesh.getBoundingInfo();
  33820. var boundingBox = boundingInfo.boundingBox;
  33821. if (!minVector || !maxVector) {
  33822. minVector = boundingBox.minimumWorld;
  33823. maxVector = boundingBox.maximumWorld;
  33824. }
  33825. else {
  33826. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33827. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33828. }
  33829. });
  33830. if (!minVector || !maxVector) {
  33831. return {
  33832. min: BABYLON.Vector3.Zero(),
  33833. max: BABYLON.Vector3.Zero()
  33834. };
  33835. }
  33836. return {
  33837. min: minVector,
  33838. max: maxVector
  33839. };
  33840. };
  33841. /**
  33842. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33843. */
  33844. Mesh.Center = function (meshesOrMinMaxVector) {
  33845. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33846. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33847. };
  33848. /**
  33849. * Merge the array of meshes into a single mesh for performance reasons.
  33850. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  33851. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  33852. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33853. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33854. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33855. */
  33856. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33857. if (disposeSource === void 0) { disposeSource = true; }
  33858. var index;
  33859. if (!allow32BitsIndices) {
  33860. var totalVertices = 0;
  33861. // Counting vertices
  33862. for (index = 0; index < meshes.length; index++) {
  33863. if (meshes[index]) {
  33864. totalVertices += meshes[index].getTotalVertices();
  33865. if (totalVertices > 65536) {
  33866. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33867. return null;
  33868. }
  33869. }
  33870. }
  33871. }
  33872. // Merge
  33873. var vertexData = null;
  33874. var otherVertexData;
  33875. var indiceArray = new Array();
  33876. var source = null;
  33877. for (index = 0; index < meshes.length; index++) {
  33878. if (meshes[index]) {
  33879. var wm = meshes[index].computeWorldMatrix(true);
  33880. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33881. otherVertexData.transform(wm);
  33882. if (vertexData) {
  33883. vertexData.merge(otherVertexData, allow32BitsIndices);
  33884. }
  33885. else {
  33886. vertexData = otherVertexData;
  33887. source = meshes[index];
  33888. }
  33889. if (subdivideWithSubMeshes) {
  33890. indiceArray.push(meshes[index].getTotalIndices());
  33891. }
  33892. }
  33893. }
  33894. source = source;
  33895. if (!meshSubclass) {
  33896. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33897. }
  33898. vertexData.applyToMesh(meshSubclass);
  33899. // Setting properties
  33900. meshSubclass.material = source.material;
  33901. meshSubclass.checkCollisions = source.checkCollisions;
  33902. // Cleaning
  33903. if (disposeSource) {
  33904. for (index = 0; index < meshes.length; index++) {
  33905. if (meshes[index]) {
  33906. meshes[index].dispose();
  33907. }
  33908. }
  33909. }
  33910. // Subdivide
  33911. if (subdivideWithSubMeshes) {
  33912. //-- removal of global submesh
  33913. meshSubclass.releaseSubMeshes();
  33914. index = 0;
  33915. var offset = 0;
  33916. //-- apply subdivision according to index table
  33917. while (index < indiceArray.length) {
  33918. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33919. offset += indiceArray[index];
  33920. index++;
  33921. }
  33922. }
  33923. return meshSubclass;
  33924. };
  33925. // Consts
  33926. Mesh._FRONTSIDE = 0;
  33927. Mesh._BACKSIDE = 1;
  33928. Mesh._DOUBLESIDE = 2;
  33929. Mesh._DEFAULTSIDE = 0;
  33930. Mesh._NO_CAP = 0;
  33931. Mesh._CAP_START = 1;
  33932. Mesh._CAP_END = 2;
  33933. Mesh._CAP_ALL = 3;
  33934. return Mesh;
  33935. }(BABYLON.AbstractMesh));
  33936. BABYLON.Mesh = Mesh;
  33937. })(BABYLON || (BABYLON = {}));
  33938. //# sourceMappingURL=babylon.mesh.js.map
  33939. var BABYLON;
  33940. (function (BABYLON) {
  33941. var BaseSubMesh = /** @class */ (function () {
  33942. function BaseSubMesh() {
  33943. }
  33944. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33945. get: function () {
  33946. return this._materialEffect;
  33947. },
  33948. enumerable: true,
  33949. configurable: true
  33950. });
  33951. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33952. if (defines === void 0) { defines = null; }
  33953. if (this._materialEffect === effect) {
  33954. if (!effect) {
  33955. this._materialDefines = null;
  33956. }
  33957. return;
  33958. }
  33959. this._materialDefines = defines;
  33960. this._materialEffect = effect;
  33961. };
  33962. return BaseSubMesh;
  33963. }());
  33964. BABYLON.BaseSubMesh = BaseSubMesh;
  33965. var SubMesh = /** @class */ (function (_super) {
  33966. __extends(SubMesh, _super);
  33967. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33968. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33969. var _this = _super.call(this) || this;
  33970. _this.materialIndex = materialIndex;
  33971. _this.verticesStart = verticesStart;
  33972. _this.verticesCount = verticesCount;
  33973. _this.indexStart = indexStart;
  33974. _this.indexCount = indexCount;
  33975. /** @hidden */
  33976. _this._renderId = 0;
  33977. _this._mesh = mesh;
  33978. _this._renderingMesh = renderingMesh || mesh;
  33979. mesh.subMeshes.push(_this);
  33980. _this._trianglePlanes = [];
  33981. _this._id = mesh.subMeshes.length - 1;
  33982. if (createBoundingBox) {
  33983. _this.refreshBoundingInfo();
  33984. mesh.computeWorldMatrix(true);
  33985. }
  33986. return _this;
  33987. }
  33988. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33989. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33990. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33991. };
  33992. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33993. get: function () {
  33994. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  33995. },
  33996. enumerable: true,
  33997. configurable: true
  33998. });
  33999. /**
  34000. * Returns the submesh BoudingInfo object.
  34001. */
  34002. SubMesh.prototype.getBoundingInfo = function () {
  34003. if (this.IsGlobal) {
  34004. return this._mesh.getBoundingInfo();
  34005. }
  34006. return this._boundingInfo;
  34007. };
  34008. /**
  34009. * Sets the submesh BoundingInfo.
  34010. * Return the SubMesh.
  34011. */
  34012. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34013. this._boundingInfo = boundingInfo;
  34014. return this;
  34015. };
  34016. /**
  34017. * Returns the mesh of the current submesh.
  34018. */
  34019. SubMesh.prototype.getMesh = function () {
  34020. return this._mesh;
  34021. };
  34022. /**
  34023. * Returns the rendering mesh of the submesh.
  34024. */
  34025. SubMesh.prototype.getRenderingMesh = function () {
  34026. return this._renderingMesh;
  34027. };
  34028. /**
  34029. * Returns the submesh material.
  34030. */
  34031. SubMesh.prototype.getMaterial = function () {
  34032. var rootMaterial = this._renderingMesh.material;
  34033. if (rootMaterial === null || rootMaterial === undefined) {
  34034. return this._mesh.getScene().defaultMaterial;
  34035. }
  34036. else if (rootMaterial.getSubMaterial) {
  34037. var multiMaterial = rootMaterial;
  34038. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34039. if (this._currentMaterial !== effectiveMaterial) {
  34040. this._currentMaterial = effectiveMaterial;
  34041. this._materialDefines = null;
  34042. }
  34043. return effectiveMaterial;
  34044. }
  34045. return rootMaterial;
  34046. };
  34047. // Methods
  34048. /**
  34049. * Sets a new updated BoundingInfo object to the submesh.
  34050. * Returns the SubMesh.
  34051. */
  34052. SubMesh.prototype.refreshBoundingInfo = function () {
  34053. this._lastColliderWorldVertices = null;
  34054. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34055. return this;
  34056. }
  34057. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34058. if (!data) {
  34059. this._boundingInfo = this._mesh.getBoundingInfo();
  34060. return this;
  34061. }
  34062. var indices = this._renderingMesh.getIndices();
  34063. var extend;
  34064. //is this the only submesh?
  34065. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34066. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34067. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34068. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34069. }
  34070. else {
  34071. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34072. }
  34073. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34074. return this;
  34075. };
  34076. /** @hidden */
  34077. SubMesh.prototype._checkCollision = function (collider) {
  34078. var boundingInfo = this.getBoundingInfo();
  34079. return boundingInfo._checkCollision(collider);
  34080. };
  34081. /**
  34082. * Updates the submesh BoundingInfo.
  34083. * Returns the Submesh.
  34084. */
  34085. SubMesh.prototype.updateBoundingInfo = function (world) {
  34086. var boundingInfo = this.getBoundingInfo();
  34087. if (!boundingInfo) {
  34088. this.refreshBoundingInfo();
  34089. boundingInfo = this.getBoundingInfo();
  34090. }
  34091. boundingInfo.update(world);
  34092. return this;
  34093. };
  34094. /**
  34095. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34096. * Boolean returned.
  34097. */
  34098. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34099. var boundingInfo = this.getBoundingInfo();
  34100. if (!boundingInfo) {
  34101. return false;
  34102. }
  34103. return boundingInfo.isInFrustum(frustumPlanes);
  34104. };
  34105. /**
  34106. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34107. * Boolean returned.
  34108. */
  34109. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34110. var boundingInfo = this.getBoundingInfo();
  34111. if (!boundingInfo) {
  34112. return false;
  34113. }
  34114. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34115. };
  34116. /**
  34117. * Renders the submesh.
  34118. * Returns it.
  34119. */
  34120. SubMesh.prototype.render = function (enableAlphaMode) {
  34121. this._renderingMesh.render(this, enableAlphaMode);
  34122. return this;
  34123. };
  34124. /**
  34125. * Returns a new Index Buffer.
  34126. * Type returned : WebGLBuffer.
  34127. */
  34128. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34129. if (!this._linesIndexBuffer) {
  34130. var linesIndices = [];
  34131. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34132. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34133. }
  34134. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34135. this.linesIndexCount = linesIndices.length;
  34136. }
  34137. return this._linesIndexBuffer;
  34138. };
  34139. /**
  34140. * True is the passed Ray intersects the submesh bounding box.
  34141. * Boolean returned.
  34142. */
  34143. SubMesh.prototype.canIntersects = function (ray) {
  34144. var boundingInfo = this.getBoundingInfo();
  34145. if (!boundingInfo) {
  34146. return false;
  34147. }
  34148. return ray.intersectsBox(boundingInfo.boundingBox);
  34149. };
  34150. /**
  34151. * Returns an object IntersectionInfo.
  34152. */
  34153. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34154. var intersectInfo = null;
  34155. var material = this.getMaterial();
  34156. if (!material) {
  34157. return null;
  34158. }
  34159. switch (material.fillMode) {
  34160. case BABYLON.Material.PointListDrawMode:
  34161. case BABYLON.Material.LineListDrawMode:
  34162. case BABYLON.Material.LineLoopDrawMode:
  34163. case BABYLON.Material.LineStripDrawMode:
  34164. case BABYLON.Material.TriangleFanDrawMode:
  34165. case BABYLON.Material.TriangleStripDrawMode:
  34166. return null;
  34167. }
  34168. // LineMesh first as it's also a Mesh...
  34169. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34170. var lineMesh = this._mesh;
  34171. // Line test
  34172. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34173. var p0 = positions[indices[index]];
  34174. var p1 = positions[indices[index + 1]];
  34175. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34176. if (length < 0) {
  34177. continue;
  34178. }
  34179. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34180. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34181. if (fastCheck) {
  34182. break;
  34183. }
  34184. }
  34185. }
  34186. }
  34187. else {
  34188. // Triangles test
  34189. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34190. var p0 = positions[indices[index]];
  34191. var p1 = positions[indices[index + 1]];
  34192. var p2 = positions[indices[index + 2]];
  34193. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34194. if (currentIntersectInfo) {
  34195. if (currentIntersectInfo.distance < 0) {
  34196. continue;
  34197. }
  34198. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34199. intersectInfo = currentIntersectInfo;
  34200. intersectInfo.faceId = index / 3;
  34201. if (fastCheck) {
  34202. break;
  34203. }
  34204. }
  34205. }
  34206. }
  34207. }
  34208. return intersectInfo;
  34209. };
  34210. /** @hidden */
  34211. SubMesh.prototype._rebuild = function () {
  34212. if (this._linesIndexBuffer) {
  34213. this._linesIndexBuffer = null;
  34214. }
  34215. };
  34216. // Clone
  34217. /**
  34218. * Creates a new Submesh from the passed Mesh.
  34219. */
  34220. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34221. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34222. if (!this.IsGlobal) {
  34223. var boundingInfo = this.getBoundingInfo();
  34224. if (!boundingInfo) {
  34225. return result;
  34226. }
  34227. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34228. }
  34229. return result;
  34230. };
  34231. // Dispose
  34232. /**
  34233. * Disposes the Submesh.
  34234. * Returns nothing.
  34235. */
  34236. SubMesh.prototype.dispose = function () {
  34237. if (this._linesIndexBuffer) {
  34238. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34239. this._linesIndexBuffer = null;
  34240. }
  34241. // Remove from mesh
  34242. var index = this._mesh.subMeshes.indexOf(this);
  34243. this._mesh.subMeshes.splice(index, 1);
  34244. };
  34245. // Statics
  34246. /**
  34247. * Creates a new Submesh from the passed parameters :
  34248. * - materialIndex (integer) : the index of the main mesh material.
  34249. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34250. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34251. * - mesh (Mesh) : the main mesh to create the submesh from.
  34252. * - renderingMesh (optional Mesh) : rendering mesh.
  34253. */
  34254. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34255. var minVertexIndex = Number.MAX_VALUE;
  34256. var maxVertexIndex = -Number.MAX_VALUE;
  34257. renderingMesh = (renderingMesh || mesh);
  34258. var indices = renderingMesh.getIndices();
  34259. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34260. var vertexIndex = indices[index];
  34261. if (vertexIndex < minVertexIndex)
  34262. minVertexIndex = vertexIndex;
  34263. if (vertexIndex > maxVertexIndex)
  34264. maxVertexIndex = vertexIndex;
  34265. }
  34266. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34267. };
  34268. return SubMesh;
  34269. }(BaseSubMesh));
  34270. BABYLON.SubMesh = SubMesh;
  34271. })(BABYLON || (BABYLON = {}));
  34272. //# sourceMappingURL=babylon.subMesh.js.map
  34273. var __assign = (this && this.__assign) || function () {
  34274. __assign = Object.assign || function(t) {
  34275. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34276. s = arguments[i];
  34277. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34278. t[p] = s[p];
  34279. }
  34280. return t;
  34281. };
  34282. return __assign.apply(this, arguments);
  34283. };
  34284. var BABYLON;
  34285. (function (BABYLON) {
  34286. /**
  34287. * Manages the defines for the Material
  34288. */
  34289. var MaterialDefines = /** @class */ (function () {
  34290. function MaterialDefines() {
  34291. this._isDirty = true;
  34292. /** @hidden */
  34293. this._areLightsDirty = true;
  34294. /** @hidden */
  34295. this._areAttributesDirty = true;
  34296. /** @hidden */
  34297. this._areTexturesDirty = true;
  34298. /** @hidden */
  34299. this._areFresnelDirty = true;
  34300. /** @hidden */
  34301. this._areMiscDirty = true;
  34302. /** @hidden */
  34303. this._areImageProcessingDirty = true;
  34304. /** @hidden */
  34305. this._normals = false;
  34306. /** @hidden */
  34307. this._uvs = false;
  34308. /** @hidden */
  34309. this._needNormals = false;
  34310. /** @hidden */
  34311. this._needUVs = false;
  34312. }
  34313. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34314. /**
  34315. * Specifies if the material needs to be re-calculated
  34316. */
  34317. get: function () {
  34318. return this._isDirty;
  34319. },
  34320. enumerable: true,
  34321. configurable: true
  34322. });
  34323. /**
  34324. * Marks the material to indicate that it has been re-calculated
  34325. */
  34326. MaterialDefines.prototype.markAsProcessed = function () {
  34327. this._isDirty = false;
  34328. this._areAttributesDirty = false;
  34329. this._areTexturesDirty = false;
  34330. this._areFresnelDirty = false;
  34331. this._areLightsDirty = false;
  34332. this._areMiscDirty = false;
  34333. this._areImageProcessingDirty = false;
  34334. };
  34335. /**
  34336. * Marks the material to indicate that it needs to be re-calculated
  34337. */
  34338. MaterialDefines.prototype.markAsUnprocessed = function () {
  34339. this._isDirty = true;
  34340. };
  34341. /**
  34342. * Marks the material to indicate all of its defines need to be re-calculated
  34343. */
  34344. MaterialDefines.prototype.markAllAsDirty = function () {
  34345. this._areTexturesDirty = true;
  34346. this._areAttributesDirty = true;
  34347. this._areLightsDirty = true;
  34348. this._areFresnelDirty = true;
  34349. this._areMiscDirty = true;
  34350. this._areImageProcessingDirty = true;
  34351. this._isDirty = true;
  34352. };
  34353. /**
  34354. * Marks the material to indicate that image processing needs to be re-calculated
  34355. */
  34356. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34357. this._areImageProcessingDirty = true;
  34358. this._isDirty = true;
  34359. };
  34360. /**
  34361. * Marks the material to indicate the lights need to be re-calculated
  34362. */
  34363. MaterialDefines.prototype.markAsLightDirty = function () {
  34364. this._areLightsDirty = true;
  34365. this._isDirty = true;
  34366. };
  34367. /**
  34368. * Marks the attribute state as changed
  34369. */
  34370. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34371. this._areAttributesDirty = true;
  34372. this._isDirty = true;
  34373. };
  34374. /**
  34375. * Marks the texture state as changed
  34376. */
  34377. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34378. this._areTexturesDirty = true;
  34379. this._isDirty = true;
  34380. };
  34381. /**
  34382. * Marks the fresnel state as changed
  34383. */
  34384. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34385. this._areFresnelDirty = true;
  34386. this._isDirty = true;
  34387. };
  34388. /**
  34389. * Marks the misc state as changed
  34390. */
  34391. MaterialDefines.prototype.markAsMiscDirty = function () {
  34392. this._areMiscDirty = true;
  34393. this._isDirty = true;
  34394. };
  34395. /**
  34396. * Rebuilds the material defines
  34397. */
  34398. MaterialDefines.prototype.rebuild = function () {
  34399. if (this._keys) {
  34400. delete this._keys;
  34401. }
  34402. this._keys = [];
  34403. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34404. var key = _a[_i];
  34405. if (key[0] === "_") {
  34406. continue;
  34407. }
  34408. this._keys.push(key);
  34409. }
  34410. };
  34411. /**
  34412. * Specifies if two material defines are equal
  34413. * @param other - A material define instance to compare to
  34414. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34415. */
  34416. MaterialDefines.prototype.isEqual = function (other) {
  34417. if (this._keys.length !== other._keys.length) {
  34418. return false;
  34419. }
  34420. for (var index = 0; index < this._keys.length; index++) {
  34421. var prop = this._keys[index];
  34422. if (this[prop] !== other[prop]) {
  34423. return false;
  34424. }
  34425. }
  34426. return true;
  34427. };
  34428. /**
  34429. * Clones this instance's defines to another instance
  34430. * @param other - material defines to clone values to
  34431. */
  34432. MaterialDefines.prototype.cloneTo = function (other) {
  34433. if (this._keys.length !== other._keys.length) {
  34434. other._keys = this._keys.slice(0);
  34435. }
  34436. for (var index = 0; index < this._keys.length; index++) {
  34437. var prop = this._keys[index];
  34438. other[prop] = this[prop];
  34439. }
  34440. };
  34441. /**
  34442. * Resets the material define values
  34443. */
  34444. MaterialDefines.prototype.reset = function () {
  34445. for (var index = 0; index < this._keys.length; index++) {
  34446. var prop = this._keys[index];
  34447. var type = typeof this[prop];
  34448. switch (type) {
  34449. case "number":
  34450. this[prop] = 0;
  34451. break;
  34452. case "string":
  34453. this[prop] = "";
  34454. break;
  34455. default:
  34456. this[prop] = false;
  34457. break;
  34458. }
  34459. }
  34460. };
  34461. /**
  34462. * Converts the material define values to a string
  34463. * @returns - String of material define information
  34464. */
  34465. MaterialDefines.prototype.toString = function () {
  34466. var result = "";
  34467. for (var index = 0; index < this._keys.length; index++) {
  34468. var prop = this._keys[index];
  34469. var value = this[prop];
  34470. var type = typeof value;
  34471. switch (type) {
  34472. case "number":
  34473. case "string":
  34474. result += "#define " + prop + " " + value + "\n";
  34475. break;
  34476. default:
  34477. if (value) {
  34478. result += "#define " + prop + "\n";
  34479. }
  34480. break;
  34481. }
  34482. }
  34483. return result;
  34484. };
  34485. return MaterialDefines;
  34486. }());
  34487. BABYLON.MaterialDefines = MaterialDefines;
  34488. /**
  34489. * Base class for the main features of a material in Babylon.js
  34490. */
  34491. var Material = /** @class */ (function () {
  34492. /**
  34493. * Creates a material instance
  34494. * @param name defines the name of the material
  34495. * @param scene defines the scene to reference
  34496. * @param doNotAdd specifies if the material should be added to the scene
  34497. */
  34498. function Material(name, scene, doNotAdd) {
  34499. /**
  34500. * Specifies if the ready state should be checked on each call
  34501. */
  34502. this.checkReadyOnEveryCall = false;
  34503. /**
  34504. * Specifies if the ready state should be checked once
  34505. */
  34506. this.checkReadyOnlyOnce = false;
  34507. /**
  34508. * The state of the material
  34509. */
  34510. this.state = "";
  34511. /**
  34512. * The alpha value of the material
  34513. */
  34514. this._alpha = 1.0;
  34515. /**
  34516. * Specifies if back face culling is enabled
  34517. */
  34518. this._backFaceCulling = true;
  34519. /**
  34520. * Gets a boolean indicating that current material needs to register RTT
  34521. */
  34522. this.hasRenderTargetTextures = false;
  34523. /**
  34524. * Specifies if the material should be serialized
  34525. */
  34526. this.doNotSerialize = false;
  34527. /**
  34528. * Specifies if the effect should be stored on sub meshes
  34529. */
  34530. this.storeEffectOnSubMeshes = false;
  34531. /**
  34532. * An event triggered when the material is disposed
  34533. */
  34534. this.onDisposeObservable = new BABYLON.Observable();
  34535. /**
  34536. * Stores the value of the alpha mode
  34537. */
  34538. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34539. /**
  34540. * Stores the state of the need depth pre-pass value
  34541. */
  34542. this._needDepthPrePass = false;
  34543. /**
  34544. * Specifies if depth writing should be disabled
  34545. */
  34546. this.disableDepthWrite = false;
  34547. /**
  34548. * Specifies if depth writing should be forced
  34549. */
  34550. this.forceDepthWrite = false;
  34551. /**
  34552. * Specifies if there should be a separate pass for culling
  34553. */
  34554. this.separateCullingPass = false;
  34555. /**
  34556. * Stores the state specifing if fog should be enabled
  34557. */
  34558. this._fogEnabled = true;
  34559. /**
  34560. * Stores the size of points
  34561. */
  34562. this.pointSize = 1.0;
  34563. /**
  34564. * Stores the z offset value
  34565. */
  34566. this.zOffset = 0;
  34567. /**
  34568. * @hidden
  34569. * Specifies if the material was previously ready
  34570. */
  34571. this._wasPreviouslyReady = false;
  34572. /**
  34573. * Stores the fill mode state
  34574. */
  34575. this._fillMode = Material.TriangleFillMode;
  34576. this.name = name;
  34577. this.id = name || BABYLON.Tools.RandomId();
  34578. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34579. this.uniqueId = this._scene.getUniqueId();
  34580. if (this._scene.useRightHandedSystem) {
  34581. this.sideOrientation = Material.ClockWiseSideOrientation;
  34582. }
  34583. else {
  34584. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34585. }
  34586. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34587. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34588. if (!doNotAdd) {
  34589. this._scene.materials.push(this);
  34590. }
  34591. }
  34592. Object.defineProperty(Material, "TriangleFillMode", {
  34593. /**
  34594. * Returns the triangle fill mode
  34595. */
  34596. get: function () {
  34597. return Material._TriangleFillMode;
  34598. },
  34599. enumerable: true,
  34600. configurable: true
  34601. });
  34602. Object.defineProperty(Material, "WireFrameFillMode", {
  34603. /**
  34604. * Returns the wireframe mode
  34605. */
  34606. get: function () {
  34607. return Material._WireFrameFillMode;
  34608. },
  34609. enumerable: true,
  34610. configurable: true
  34611. });
  34612. Object.defineProperty(Material, "PointFillMode", {
  34613. /**
  34614. * Returns the point fill mode
  34615. */
  34616. get: function () {
  34617. return Material._PointFillMode;
  34618. },
  34619. enumerable: true,
  34620. configurable: true
  34621. });
  34622. Object.defineProperty(Material, "PointListDrawMode", {
  34623. /**
  34624. * Returns the point list draw mode
  34625. */
  34626. get: function () {
  34627. return Material._PointListDrawMode;
  34628. },
  34629. enumerable: true,
  34630. configurable: true
  34631. });
  34632. Object.defineProperty(Material, "LineListDrawMode", {
  34633. /**
  34634. * Returns the line list draw mode
  34635. */
  34636. get: function () {
  34637. return Material._LineListDrawMode;
  34638. },
  34639. enumerable: true,
  34640. configurable: true
  34641. });
  34642. Object.defineProperty(Material, "LineLoopDrawMode", {
  34643. /**
  34644. * Returns the line loop draw mode
  34645. */
  34646. get: function () {
  34647. return Material._LineLoopDrawMode;
  34648. },
  34649. enumerable: true,
  34650. configurable: true
  34651. });
  34652. Object.defineProperty(Material, "LineStripDrawMode", {
  34653. /**
  34654. * Returns the line strip draw mode
  34655. */
  34656. get: function () {
  34657. return Material._LineStripDrawMode;
  34658. },
  34659. enumerable: true,
  34660. configurable: true
  34661. });
  34662. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34663. /**
  34664. * Returns the triangle strip draw mode
  34665. */
  34666. get: function () {
  34667. return Material._TriangleStripDrawMode;
  34668. },
  34669. enumerable: true,
  34670. configurable: true
  34671. });
  34672. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34673. /**
  34674. * Returns the triangle fan draw mode
  34675. */
  34676. get: function () {
  34677. return Material._TriangleFanDrawMode;
  34678. },
  34679. enumerable: true,
  34680. configurable: true
  34681. });
  34682. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34683. /**
  34684. * Returns the clock-wise side orientation
  34685. */
  34686. get: function () {
  34687. return Material._ClockWiseSideOrientation;
  34688. },
  34689. enumerable: true,
  34690. configurable: true
  34691. });
  34692. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34693. /**
  34694. * Returns the counter clock-wise side orientation
  34695. */
  34696. get: function () {
  34697. return Material._CounterClockWiseSideOrientation;
  34698. },
  34699. enumerable: true,
  34700. configurable: true
  34701. });
  34702. Object.defineProperty(Material, "TextureDirtyFlag", {
  34703. /**
  34704. * Returns the dirty texture flag value
  34705. */
  34706. get: function () {
  34707. return Material._TextureDirtyFlag;
  34708. },
  34709. enumerable: true,
  34710. configurable: true
  34711. });
  34712. Object.defineProperty(Material, "LightDirtyFlag", {
  34713. /**
  34714. * Returns the dirty light flag value
  34715. */
  34716. get: function () {
  34717. return Material._LightDirtyFlag;
  34718. },
  34719. enumerable: true,
  34720. configurable: true
  34721. });
  34722. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34723. /**
  34724. * Returns the dirty fresnel flag value
  34725. */
  34726. get: function () {
  34727. return Material._FresnelDirtyFlag;
  34728. },
  34729. enumerable: true,
  34730. configurable: true
  34731. });
  34732. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34733. /**
  34734. * Returns the dirty attributes flag value
  34735. */
  34736. get: function () {
  34737. return Material._AttributesDirtyFlag;
  34738. },
  34739. enumerable: true,
  34740. configurable: true
  34741. });
  34742. Object.defineProperty(Material, "MiscDirtyFlag", {
  34743. /**
  34744. * Returns the dirty misc flag value
  34745. */
  34746. get: function () {
  34747. return Material._MiscDirtyFlag;
  34748. },
  34749. enumerable: true,
  34750. configurable: true
  34751. });
  34752. Object.defineProperty(Material.prototype, "alpha", {
  34753. /**
  34754. * Gets the alpha value of the material
  34755. */
  34756. get: function () {
  34757. return this._alpha;
  34758. },
  34759. /**
  34760. * Sets the alpha value of the material
  34761. */
  34762. set: function (value) {
  34763. if (this._alpha === value) {
  34764. return;
  34765. }
  34766. this._alpha = value;
  34767. this.markAsDirty(Material.MiscDirtyFlag);
  34768. },
  34769. enumerable: true,
  34770. configurable: true
  34771. });
  34772. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34773. /**
  34774. * Gets the back-face culling state
  34775. */
  34776. get: function () {
  34777. return this._backFaceCulling;
  34778. },
  34779. /**
  34780. * Sets the back-face culling state
  34781. */
  34782. set: function (value) {
  34783. if (this._backFaceCulling === value) {
  34784. return;
  34785. }
  34786. this._backFaceCulling = value;
  34787. this.markAsDirty(Material.TextureDirtyFlag);
  34788. },
  34789. enumerable: true,
  34790. configurable: true
  34791. });
  34792. Object.defineProperty(Material.prototype, "onDispose", {
  34793. /**
  34794. * Called during a dispose event
  34795. */
  34796. set: function (callback) {
  34797. if (this._onDisposeObserver) {
  34798. this.onDisposeObservable.remove(this._onDisposeObserver);
  34799. }
  34800. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34801. },
  34802. enumerable: true,
  34803. configurable: true
  34804. });
  34805. Object.defineProperty(Material.prototype, "onBindObservable", {
  34806. /**
  34807. * An event triggered when the material is bound
  34808. */
  34809. get: function () {
  34810. if (!this._onBindObservable) {
  34811. this._onBindObservable = new BABYLON.Observable();
  34812. }
  34813. return this._onBindObservable;
  34814. },
  34815. enumerable: true,
  34816. configurable: true
  34817. });
  34818. Object.defineProperty(Material.prototype, "onBind", {
  34819. /**
  34820. * Called during a bind event
  34821. */
  34822. set: function (callback) {
  34823. if (this._onBindObserver) {
  34824. this.onBindObservable.remove(this._onBindObserver);
  34825. }
  34826. this._onBindObserver = this.onBindObservable.add(callback);
  34827. },
  34828. enumerable: true,
  34829. configurable: true
  34830. });
  34831. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34832. /**
  34833. * An event triggered when the material is unbound
  34834. */
  34835. get: function () {
  34836. if (!this._onUnBindObservable) {
  34837. this._onUnBindObservable = new BABYLON.Observable();
  34838. }
  34839. return this._onUnBindObservable;
  34840. },
  34841. enumerable: true,
  34842. configurable: true
  34843. });
  34844. Object.defineProperty(Material.prototype, "alphaMode", {
  34845. /**
  34846. * Gets the value of the alpha mode
  34847. */
  34848. get: function () {
  34849. return this._alphaMode;
  34850. },
  34851. /**
  34852. * Sets the value of the alpha mode.
  34853. *
  34854. * | Value | Type | Description |
  34855. * | --- | --- | --- |
  34856. * | 0 | ALPHA_DISABLE | |
  34857. * | 1 | ALPHA_ADD | |
  34858. * | 2 | ALPHA_COMBINE | |
  34859. * | 3 | ALPHA_SUBTRACT | |
  34860. * | 4 | ALPHA_MULTIPLY | |
  34861. * | 5 | ALPHA_MAXIMIZED | |
  34862. * | 6 | ALPHA_ONEONE | |
  34863. * | 7 | ALPHA_PREMULTIPLIED | |
  34864. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34865. * | 9 | ALPHA_INTERPOLATE | |
  34866. * | 10 | ALPHA_SCREENMODE | |
  34867. *
  34868. */
  34869. set: function (value) {
  34870. if (this._alphaMode === value) {
  34871. return;
  34872. }
  34873. this._alphaMode = value;
  34874. this.markAsDirty(Material.TextureDirtyFlag);
  34875. },
  34876. enumerable: true,
  34877. configurable: true
  34878. });
  34879. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34880. /**
  34881. * Gets the depth pre-pass value
  34882. */
  34883. get: function () {
  34884. return this._needDepthPrePass;
  34885. },
  34886. /**
  34887. * Sets the need depth pre-pass value
  34888. */
  34889. set: function (value) {
  34890. if (this._needDepthPrePass === value) {
  34891. return;
  34892. }
  34893. this._needDepthPrePass = value;
  34894. if (this._needDepthPrePass) {
  34895. this.checkReadyOnEveryCall = true;
  34896. }
  34897. },
  34898. enumerable: true,
  34899. configurable: true
  34900. });
  34901. Object.defineProperty(Material.prototype, "fogEnabled", {
  34902. /**
  34903. * Gets the value of the fog enabled state
  34904. */
  34905. get: function () {
  34906. return this._fogEnabled;
  34907. },
  34908. /**
  34909. * Sets the state for enabling fog
  34910. */
  34911. set: function (value) {
  34912. if (this._fogEnabled === value) {
  34913. return;
  34914. }
  34915. this._fogEnabled = value;
  34916. this.markAsDirty(Material.MiscDirtyFlag);
  34917. },
  34918. enumerable: true,
  34919. configurable: true
  34920. });
  34921. Object.defineProperty(Material.prototype, "wireframe", {
  34922. /**
  34923. * Gets a value specifying if wireframe mode is enabled
  34924. */
  34925. get: function () {
  34926. switch (this._fillMode) {
  34927. case Material.WireFrameFillMode:
  34928. case Material.LineListDrawMode:
  34929. case Material.LineLoopDrawMode:
  34930. case Material.LineStripDrawMode:
  34931. return true;
  34932. }
  34933. return this._scene.forceWireframe;
  34934. },
  34935. /**
  34936. * Sets the state of wireframe mode
  34937. */
  34938. set: function (value) {
  34939. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34940. },
  34941. enumerable: true,
  34942. configurable: true
  34943. });
  34944. Object.defineProperty(Material.prototype, "pointsCloud", {
  34945. /**
  34946. * Gets the value specifying if point clouds are enabled
  34947. */
  34948. get: function () {
  34949. switch (this._fillMode) {
  34950. case Material.PointFillMode:
  34951. case Material.PointListDrawMode:
  34952. return true;
  34953. }
  34954. return this._scene.forcePointsCloud;
  34955. },
  34956. /**
  34957. * Sets the state of point cloud mode
  34958. */
  34959. set: function (value) {
  34960. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34961. },
  34962. enumerable: true,
  34963. configurable: true
  34964. });
  34965. Object.defineProperty(Material.prototype, "fillMode", {
  34966. /**
  34967. * Gets the material fill mode
  34968. */
  34969. get: function () {
  34970. return this._fillMode;
  34971. },
  34972. /**
  34973. * Sets the material fill mode
  34974. */
  34975. set: function (value) {
  34976. if (this._fillMode === value) {
  34977. return;
  34978. }
  34979. this._fillMode = value;
  34980. this.markAsDirty(Material.MiscDirtyFlag);
  34981. },
  34982. enumerable: true,
  34983. configurable: true
  34984. });
  34985. /**
  34986. * Returns a string representation of the current material
  34987. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34988. * @returns a string with material information
  34989. */
  34990. Material.prototype.toString = function (fullDetails) {
  34991. var ret = "Name: " + this.name;
  34992. if (fullDetails) {
  34993. }
  34994. return ret;
  34995. };
  34996. /**
  34997. * Gets the class name of the material
  34998. * @returns a string with the class name of the material
  34999. */
  35000. Material.prototype.getClassName = function () {
  35001. return "Material";
  35002. };
  35003. Object.defineProperty(Material.prototype, "isFrozen", {
  35004. /**
  35005. * Specifies if updates for the material been locked
  35006. */
  35007. get: function () {
  35008. return this.checkReadyOnlyOnce;
  35009. },
  35010. enumerable: true,
  35011. configurable: true
  35012. });
  35013. /**
  35014. * Locks updates for the material
  35015. */
  35016. Material.prototype.freeze = function () {
  35017. this.checkReadyOnlyOnce = true;
  35018. };
  35019. /**
  35020. * Unlocks updates for the material
  35021. */
  35022. Material.prototype.unfreeze = function () {
  35023. this.checkReadyOnlyOnce = false;
  35024. };
  35025. /**
  35026. * Specifies if the material is ready to be used
  35027. * @param mesh defines the mesh to check
  35028. * @param useInstances specifies if instances should be used
  35029. * @returns a boolean indicating if the material is ready to be used
  35030. */
  35031. Material.prototype.isReady = function (mesh, useInstances) {
  35032. return true;
  35033. };
  35034. /**
  35035. * Specifies that the submesh is ready to be used
  35036. * @param mesh defines the mesh to check
  35037. * @param subMesh defines which submesh to check
  35038. * @param useInstances specifies that instances should be used
  35039. * @returns a boolean indicating that the submesh is ready or not
  35040. */
  35041. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35042. return false;
  35043. };
  35044. /**
  35045. * Returns the material effect
  35046. * @returns the effect associated with the material
  35047. */
  35048. Material.prototype.getEffect = function () {
  35049. return this._effect;
  35050. };
  35051. /**
  35052. * Returns the current scene
  35053. * @returns a Scene
  35054. */
  35055. Material.prototype.getScene = function () {
  35056. return this._scene;
  35057. };
  35058. /**
  35059. * Specifies if the material will require alpha blending
  35060. * @returns a boolean specifying if alpha blending is needed
  35061. */
  35062. Material.prototype.needAlphaBlending = function () {
  35063. return (this.alpha < 1.0);
  35064. };
  35065. /**
  35066. * Specifies if the mesh will require alpha blending
  35067. * @param mesh defines the mesh to check
  35068. * @returns a boolean specifying if alpha blending is needed for the mesh
  35069. */
  35070. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35071. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35072. };
  35073. /**
  35074. * Specifies if this material should be rendered in alpha test mode
  35075. * @returns a boolean specifying if an alpha test is needed.
  35076. */
  35077. Material.prototype.needAlphaTesting = function () {
  35078. return false;
  35079. };
  35080. /**
  35081. * Gets the texture used for the alpha test
  35082. * @returns the texture to use for alpha testing
  35083. */
  35084. Material.prototype.getAlphaTestTexture = function () {
  35085. return null;
  35086. };
  35087. /**
  35088. * Marks the material to indicate that it needs to be re-calculated
  35089. */
  35090. Material.prototype.markDirty = function () {
  35091. this._wasPreviouslyReady = false;
  35092. };
  35093. /** @hidden */
  35094. Material.prototype._preBind = function (effect, overrideOrientation) {
  35095. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35096. var engine = this._scene.getEngine();
  35097. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35098. var reverse = orientation === Material.ClockWiseSideOrientation;
  35099. engine.enableEffect(effect ? effect : this._effect);
  35100. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35101. return reverse;
  35102. };
  35103. /**
  35104. * Binds the material to the mesh
  35105. * @param world defines the world transformation matrix
  35106. * @param mesh defines the mesh to bind the material to
  35107. */
  35108. Material.prototype.bind = function (world, mesh) {
  35109. };
  35110. /**
  35111. * Binds the submesh to the material
  35112. * @param world defines the world transformation matrix
  35113. * @param mesh defines the mesh containing the submesh
  35114. * @param subMesh defines the submesh to bind the material to
  35115. */
  35116. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35117. };
  35118. /**
  35119. * Binds the world matrix to the material
  35120. * @param world defines the world transformation matrix
  35121. */
  35122. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35123. };
  35124. /**
  35125. * Binds the scene's uniform buffer to the effect.
  35126. * @param effect defines the effect to bind to the scene uniform buffer
  35127. * @param sceneUbo defines the uniform buffer storing scene data
  35128. */
  35129. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35130. sceneUbo.bindToEffect(effect, "Scene");
  35131. };
  35132. /**
  35133. * Binds the view matrix to the effect
  35134. * @param effect defines the effect to bind the view matrix to
  35135. */
  35136. Material.prototype.bindView = function (effect) {
  35137. if (!this._useUBO) {
  35138. effect.setMatrix("view", this.getScene().getViewMatrix());
  35139. }
  35140. else {
  35141. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35142. }
  35143. };
  35144. /**
  35145. * Binds the view projection matrix to the effect
  35146. * @param effect defines the effect to bind the view projection matrix to
  35147. */
  35148. Material.prototype.bindViewProjection = function (effect) {
  35149. if (!this._useUBO) {
  35150. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35151. }
  35152. else {
  35153. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35154. }
  35155. };
  35156. /**
  35157. * Specifies if material alpha testing should be turned on for the mesh
  35158. * @param mesh defines the mesh to check
  35159. */
  35160. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35161. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35162. };
  35163. /**
  35164. * Processes to execute after binding the material to a mesh
  35165. * @param mesh defines the rendered mesh
  35166. */
  35167. Material.prototype._afterBind = function (mesh) {
  35168. this._scene._cachedMaterial = this;
  35169. if (mesh) {
  35170. this._scene._cachedVisibility = mesh.visibility;
  35171. }
  35172. else {
  35173. this._scene._cachedVisibility = 1;
  35174. }
  35175. if (this._onBindObservable && mesh) {
  35176. this._onBindObservable.notifyObservers(mesh);
  35177. }
  35178. if (this.disableDepthWrite) {
  35179. var engine = this._scene.getEngine();
  35180. this._cachedDepthWriteState = engine.getDepthWrite();
  35181. engine.setDepthWrite(false);
  35182. }
  35183. };
  35184. /**
  35185. * Unbinds the material from the mesh
  35186. */
  35187. Material.prototype.unbind = function () {
  35188. if (this._onUnBindObservable) {
  35189. this._onUnBindObservable.notifyObservers(this);
  35190. }
  35191. if (this.disableDepthWrite) {
  35192. var engine = this._scene.getEngine();
  35193. engine.setDepthWrite(this._cachedDepthWriteState);
  35194. }
  35195. };
  35196. /**
  35197. * Gets the active textures from the material
  35198. * @returns an array of textures
  35199. */
  35200. Material.prototype.getActiveTextures = function () {
  35201. return [];
  35202. };
  35203. /**
  35204. * Specifies if the material uses a texture
  35205. * @param texture defines the texture to check against the material
  35206. * @returns a boolean specifying if the material uses the texture
  35207. */
  35208. Material.prototype.hasTexture = function (texture) {
  35209. return false;
  35210. };
  35211. /**
  35212. * Makes a duplicate of the material, and gives it a new name
  35213. * @param name defines the new name for the duplicated material
  35214. * @returns the cloned material
  35215. */
  35216. Material.prototype.clone = function (name) {
  35217. return null;
  35218. };
  35219. /**
  35220. * Gets the meshes bound to the material
  35221. * @returns an array of meshes bound to the material
  35222. */
  35223. Material.prototype.getBindedMeshes = function () {
  35224. var result = new Array();
  35225. for (var index = 0; index < this._scene.meshes.length; index++) {
  35226. var mesh = this._scene.meshes[index];
  35227. if (mesh.material === this) {
  35228. result.push(mesh);
  35229. }
  35230. }
  35231. return result;
  35232. };
  35233. /**
  35234. * Force shader compilation
  35235. * @param mesh defines the mesh associated with this material
  35236. * @param onCompiled defines a function to execute once the material is compiled
  35237. * @param options defines the options to configure the compilation
  35238. */
  35239. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35240. var _this = this;
  35241. var localOptions = __assign({ clipPlane: false }, options);
  35242. var subMesh = new BABYLON.BaseSubMesh();
  35243. var scene = this.getScene();
  35244. var checkReady = function () {
  35245. if (!_this._scene || !_this._scene.getEngine()) {
  35246. return;
  35247. }
  35248. if (subMesh._materialDefines) {
  35249. subMesh._materialDefines._renderId = -1;
  35250. }
  35251. var clipPlaneState = scene.clipPlane;
  35252. if (localOptions.clipPlane) {
  35253. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35254. }
  35255. if (_this.storeEffectOnSubMeshes) {
  35256. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35257. if (onCompiled) {
  35258. onCompiled(_this);
  35259. }
  35260. }
  35261. else {
  35262. setTimeout(checkReady, 16);
  35263. }
  35264. }
  35265. else {
  35266. if (_this.isReady(mesh)) {
  35267. if (onCompiled) {
  35268. onCompiled(_this);
  35269. }
  35270. }
  35271. else {
  35272. setTimeout(checkReady, 16);
  35273. }
  35274. }
  35275. if (localOptions.clipPlane) {
  35276. scene.clipPlane = clipPlaneState;
  35277. }
  35278. };
  35279. checkReady();
  35280. };
  35281. /**
  35282. * Force shader compilation
  35283. * @param mesh defines the mesh that will use this material
  35284. * @param options defines additional options for compiling the shaders
  35285. * @returns a promise that resolves when the compilation completes
  35286. */
  35287. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35288. var _this = this;
  35289. return new Promise(function (resolve) {
  35290. _this.forceCompilation(mesh, function () {
  35291. resolve();
  35292. }, options);
  35293. });
  35294. };
  35295. /**
  35296. * Marks a define in the material to indicate that it needs to be re-computed
  35297. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35298. */
  35299. Material.prototype.markAsDirty = function (flag) {
  35300. if (flag & Material.TextureDirtyFlag) {
  35301. this._markAllSubMeshesAsTexturesDirty();
  35302. }
  35303. if (flag & Material.LightDirtyFlag) {
  35304. this._markAllSubMeshesAsLightsDirty();
  35305. }
  35306. if (flag & Material.FresnelDirtyFlag) {
  35307. this._markAllSubMeshesAsFresnelDirty();
  35308. }
  35309. if (flag & Material.AttributesDirtyFlag) {
  35310. this._markAllSubMeshesAsAttributesDirty();
  35311. }
  35312. if (flag & Material.MiscDirtyFlag) {
  35313. this._markAllSubMeshesAsMiscDirty();
  35314. }
  35315. this.getScene().resetCachedMaterial();
  35316. };
  35317. /**
  35318. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35319. * @param func defines a function which checks material defines against the submeshes
  35320. */
  35321. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35322. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35323. var mesh = _a[_i];
  35324. if (!mesh.subMeshes) {
  35325. continue;
  35326. }
  35327. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35328. var subMesh = _c[_b];
  35329. if (subMesh.getMaterial() !== this) {
  35330. continue;
  35331. }
  35332. if (!subMesh._materialDefines) {
  35333. continue;
  35334. }
  35335. func(subMesh._materialDefines);
  35336. }
  35337. }
  35338. };
  35339. /**
  35340. * Indicates that image processing needs to be re-calculated for all submeshes
  35341. */
  35342. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35343. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35344. };
  35345. /**
  35346. * Indicates that textures need to be re-calculated for all submeshes
  35347. */
  35348. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35349. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35350. };
  35351. /**
  35352. * Indicates that fresnel needs to be re-calculated for all submeshes
  35353. */
  35354. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35355. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35356. };
  35357. /**
  35358. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35359. */
  35360. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35361. this._markAllSubMeshesAsDirty(function (defines) {
  35362. defines.markAsFresnelDirty();
  35363. defines.markAsMiscDirty();
  35364. });
  35365. };
  35366. /**
  35367. * Indicates that lights need to be re-calculated for all submeshes
  35368. */
  35369. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35370. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35371. };
  35372. /**
  35373. * Indicates that attributes need to be re-calculated for all submeshes
  35374. */
  35375. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35376. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35377. };
  35378. /**
  35379. * Indicates that misc needs to be re-calculated for all submeshes
  35380. */
  35381. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35382. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35383. };
  35384. /**
  35385. * Indicates that textures and misc need to be re-calculated for all submeshes
  35386. */
  35387. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35388. this._markAllSubMeshesAsDirty(function (defines) {
  35389. defines.markAsTexturesDirty();
  35390. defines.markAsMiscDirty();
  35391. });
  35392. };
  35393. /**
  35394. * Disposes the material
  35395. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35396. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35397. */
  35398. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35399. // Animations
  35400. this.getScene().stopAnimation(this);
  35401. this.getScene().freeProcessedMaterials();
  35402. // Remove from scene
  35403. var index = this._scene.materials.indexOf(this);
  35404. if (index >= 0) {
  35405. this._scene.materials.splice(index, 1);
  35406. }
  35407. // Remove from meshes
  35408. for (index = 0; index < this._scene.meshes.length; index++) {
  35409. var mesh = this._scene.meshes[index];
  35410. if (mesh.material === this) {
  35411. mesh.material = null;
  35412. if (mesh.geometry) {
  35413. var geometry = (mesh.geometry);
  35414. if (this.storeEffectOnSubMeshes) {
  35415. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35416. var subMesh = _a[_i];
  35417. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35418. if (forceDisposeEffect && subMesh._materialEffect) {
  35419. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35420. }
  35421. }
  35422. }
  35423. else {
  35424. geometry._releaseVertexArrayObject(this._effect);
  35425. }
  35426. }
  35427. }
  35428. }
  35429. this._uniformBuffer.dispose();
  35430. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35431. if (forceDisposeEffect && this._effect) {
  35432. if (!this.storeEffectOnSubMeshes) {
  35433. this._scene.getEngine()._releaseEffect(this._effect);
  35434. }
  35435. this._effect = null;
  35436. }
  35437. // Callback
  35438. this.onDisposeObservable.notifyObservers(this);
  35439. this.onDisposeObservable.clear();
  35440. if (this._onBindObservable) {
  35441. this._onBindObservable.clear();
  35442. }
  35443. if (this._onUnBindObservable) {
  35444. this._onUnBindObservable.clear();
  35445. }
  35446. };
  35447. /**
  35448. * Serializes this material
  35449. * @returns the serialized material object
  35450. */
  35451. Material.prototype.serialize = function () {
  35452. return BABYLON.SerializationHelper.Serialize(this);
  35453. };
  35454. /**
  35455. * Creates a MultiMaterial from parsed MultiMaterial data.
  35456. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35457. * @param scene defines the hosting scene
  35458. * @returns a new MultiMaterial
  35459. */
  35460. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35461. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35462. multiMaterial.id = parsedMultiMaterial.id;
  35463. if (BABYLON.Tags) {
  35464. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35465. }
  35466. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35467. var subMatId = parsedMultiMaterial.materials[matIndex];
  35468. if (subMatId) {
  35469. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35470. }
  35471. else {
  35472. multiMaterial.subMaterials.push(null);
  35473. }
  35474. }
  35475. return multiMaterial;
  35476. };
  35477. /**
  35478. * Creates a material from parsed material data
  35479. * @param parsedMaterial defines parsed material data
  35480. * @param scene defines the hosting scene
  35481. * @param rootUrl defines the root URL to use to load textures
  35482. * @returns a new material
  35483. */
  35484. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35485. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35486. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35487. }
  35488. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35489. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35490. if (!BABYLON.LegacyPBRMaterial) {
  35491. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35492. return;
  35493. }
  35494. }
  35495. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35496. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35497. };
  35498. // Triangle views
  35499. Material._TriangleFillMode = 0;
  35500. Material._WireFrameFillMode = 1;
  35501. Material._PointFillMode = 2;
  35502. // Draw modes
  35503. Material._PointListDrawMode = 3;
  35504. Material._LineListDrawMode = 4;
  35505. Material._LineLoopDrawMode = 5;
  35506. Material._LineStripDrawMode = 6;
  35507. Material._TriangleStripDrawMode = 7;
  35508. Material._TriangleFanDrawMode = 8;
  35509. /**
  35510. * Stores the clock-wise side orientation
  35511. */
  35512. Material._ClockWiseSideOrientation = 0;
  35513. /**
  35514. * Stores the counter clock-wise side orientation
  35515. */
  35516. Material._CounterClockWiseSideOrientation = 1;
  35517. /**
  35518. * The dirty texture flag value
  35519. */
  35520. Material._TextureDirtyFlag = 1;
  35521. /**
  35522. * The dirty light flag value
  35523. */
  35524. Material._LightDirtyFlag = 2;
  35525. /**
  35526. * The dirty fresnel flag value
  35527. */
  35528. Material._FresnelDirtyFlag = 4;
  35529. /**
  35530. * The dirty attribute flag value
  35531. */
  35532. Material._AttributesDirtyFlag = 8;
  35533. /**
  35534. * The dirty misc flag value
  35535. */
  35536. Material._MiscDirtyFlag = 16;
  35537. __decorate([
  35538. BABYLON.serialize()
  35539. ], Material.prototype, "id", void 0);
  35540. __decorate([
  35541. BABYLON.serialize()
  35542. ], Material.prototype, "uniqueId", void 0);
  35543. __decorate([
  35544. BABYLON.serialize()
  35545. ], Material.prototype, "name", void 0);
  35546. __decorate([
  35547. BABYLON.serialize()
  35548. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35549. __decorate([
  35550. BABYLON.serialize()
  35551. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35552. __decorate([
  35553. BABYLON.serialize()
  35554. ], Material.prototype, "state", void 0);
  35555. __decorate([
  35556. BABYLON.serialize("alpha")
  35557. ], Material.prototype, "_alpha", void 0);
  35558. __decorate([
  35559. BABYLON.serialize("backFaceCulling")
  35560. ], Material.prototype, "_backFaceCulling", void 0);
  35561. __decorate([
  35562. BABYLON.serialize()
  35563. ], Material.prototype, "sideOrientation", void 0);
  35564. __decorate([
  35565. BABYLON.serialize("alphaMode")
  35566. ], Material.prototype, "_alphaMode", void 0);
  35567. __decorate([
  35568. BABYLON.serialize()
  35569. ], Material.prototype, "_needDepthPrePass", void 0);
  35570. __decorate([
  35571. BABYLON.serialize()
  35572. ], Material.prototype, "disableDepthWrite", void 0);
  35573. __decorate([
  35574. BABYLON.serialize()
  35575. ], Material.prototype, "forceDepthWrite", void 0);
  35576. __decorate([
  35577. BABYLON.serialize()
  35578. ], Material.prototype, "separateCullingPass", void 0);
  35579. __decorate([
  35580. BABYLON.serialize("fogEnabled")
  35581. ], Material.prototype, "_fogEnabled", void 0);
  35582. __decorate([
  35583. BABYLON.serialize()
  35584. ], Material.prototype, "pointSize", void 0);
  35585. __decorate([
  35586. BABYLON.serialize()
  35587. ], Material.prototype, "zOffset", void 0);
  35588. __decorate([
  35589. BABYLON.serialize()
  35590. ], Material.prototype, "wireframe", null);
  35591. __decorate([
  35592. BABYLON.serialize()
  35593. ], Material.prototype, "pointsCloud", null);
  35594. __decorate([
  35595. BABYLON.serialize()
  35596. ], Material.prototype, "fillMode", null);
  35597. return Material;
  35598. }());
  35599. BABYLON.Material = Material;
  35600. })(BABYLON || (BABYLON = {}));
  35601. //# sourceMappingURL=babylon.material.js.map
  35602. var BABYLON;
  35603. (function (BABYLON) {
  35604. var UniformBuffer = /** @class */ (function () {
  35605. /**
  35606. * Uniform buffer objects.
  35607. *
  35608. * Handles blocks of uniform on the GPU.
  35609. *
  35610. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35611. *
  35612. * For more information, please refer to :
  35613. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35614. */
  35615. function UniformBuffer(engine, data, dynamic) {
  35616. this._engine = engine;
  35617. this._noUBO = !engine.supportsUniformBuffers;
  35618. this._dynamic = dynamic;
  35619. this._data = data || [];
  35620. this._uniformLocations = {};
  35621. this._uniformSizes = {};
  35622. this._uniformLocationPointer = 0;
  35623. this._needSync = false;
  35624. if (this._noUBO) {
  35625. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35626. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35627. this.updateFloat = this._updateFloatForEffect;
  35628. this.updateFloat2 = this._updateFloat2ForEffect;
  35629. this.updateFloat3 = this._updateFloat3ForEffect;
  35630. this.updateFloat4 = this._updateFloat4ForEffect;
  35631. this.updateMatrix = this._updateMatrixForEffect;
  35632. this.updateVector3 = this._updateVector3ForEffect;
  35633. this.updateVector4 = this._updateVector4ForEffect;
  35634. this.updateColor3 = this._updateColor3ForEffect;
  35635. this.updateColor4 = this._updateColor4ForEffect;
  35636. }
  35637. else {
  35638. this._engine._uniformBuffers.push(this);
  35639. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35640. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35641. this.updateFloat = this._updateFloatForUniform;
  35642. this.updateFloat2 = this._updateFloat2ForUniform;
  35643. this.updateFloat3 = this._updateFloat3ForUniform;
  35644. this.updateFloat4 = this._updateFloat4ForUniform;
  35645. this.updateMatrix = this._updateMatrixForUniform;
  35646. this.updateVector3 = this._updateVector3ForUniform;
  35647. this.updateVector4 = this._updateVector4ForUniform;
  35648. this.updateColor3 = this._updateColor3ForUniform;
  35649. this.updateColor4 = this._updateColor4ForUniform;
  35650. }
  35651. }
  35652. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35653. // Properties
  35654. /**
  35655. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35656. * or just falling back on setUniformXXX calls.
  35657. */
  35658. get: function () {
  35659. return !this._noUBO;
  35660. },
  35661. enumerable: true,
  35662. configurable: true
  35663. });
  35664. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35665. /**
  35666. * Indicates if the WebGL underlying uniform buffer is in sync
  35667. * with the javascript cache data.
  35668. */
  35669. get: function () {
  35670. return !this._needSync;
  35671. },
  35672. enumerable: true,
  35673. configurable: true
  35674. });
  35675. /**
  35676. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35677. * Also, a dynamic UniformBuffer will disable cache verification and always
  35678. * update the underlying WebGL uniform buffer to the GPU.
  35679. */
  35680. UniformBuffer.prototype.isDynamic = function () {
  35681. return this._dynamic !== undefined;
  35682. };
  35683. /**
  35684. * The data cache on JS side.
  35685. */
  35686. UniformBuffer.prototype.getData = function () {
  35687. return this._bufferData;
  35688. };
  35689. /**
  35690. * The underlying WebGL Uniform buffer.
  35691. */
  35692. UniformBuffer.prototype.getBuffer = function () {
  35693. return this._buffer;
  35694. };
  35695. /**
  35696. * std140 layout specifies how to align data within an UBO structure.
  35697. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35698. * for specs.
  35699. */
  35700. UniformBuffer.prototype._fillAlignment = function (size) {
  35701. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35702. // and 4x4 matrices
  35703. // TODO : change if other types are used
  35704. var alignment;
  35705. if (size <= 2) {
  35706. alignment = size;
  35707. }
  35708. else {
  35709. alignment = 4;
  35710. }
  35711. if ((this._uniformLocationPointer % alignment) !== 0) {
  35712. var oldPointer = this._uniformLocationPointer;
  35713. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35714. var diff = this._uniformLocationPointer - oldPointer;
  35715. for (var i = 0; i < diff; i++) {
  35716. this._data.push(0);
  35717. }
  35718. }
  35719. };
  35720. /**
  35721. * Adds an uniform in the buffer.
  35722. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35723. * for the layout to be correct !
  35724. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35725. * @param {number|number[]} size Data size, or data directly.
  35726. */
  35727. UniformBuffer.prototype.addUniform = function (name, size) {
  35728. if (this._noUBO) {
  35729. return;
  35730. }
  35731. if (this._uniformLocations[name] !== undefined) {
  35732. // Already existing uniform
  35733. return;
  35734. }
  35735. // This function must be called in the order of the shader layout !
  35736. // size can be the size of the uniform, or data directly
  35737. var data;
  35738. if (size instanceof Array) {
  35739. data = size;
  35740. size = data.length;
  35741. }
  35742. else {
  35743. size = size;
  35744. data = [];
  35745. // Fill with zeros
  35746. for (var i = 0; i < size; i++) {
  35747. data.push(0);
  35748. }
  35749. }
  35750. this._fillAlignment(size);
  35751. this._uniformSizes[name] = size;
  35752. this._uniformLocations[name] = this._uniformLocationPointer;
  35753. this._uniformLocationPointer += size;
  35754. for (var i = 0; i < size; i++) {
  35755. this._data.push(data[i]);
  35756. }
  35757. this._needSync = true;
  35758. };
  35759. /**
  35760. * Wrapper for addUniform.
  35761. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35762. * @param {Matrix} mat A 4x4 matrix.
  35763. */
  35764. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35765. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35766. };
  35767. /**
  35768. * Wrapper for addUniform.
  35769. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35770. * @param {number} x
  35771. * @param {number} y
  35772. */
  35773. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35774. var temp = [x, y];
  35775. this.addUniform(name, temp);
  35776. };
  35777. /**
  35778. * Wrapper for addUniform.
  35779. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35780. * @param {number} x
  35781. * @param {number} y
  35782. * @param {number} z
  35783. */
  35784. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35785. var temp = [x, y, z];
  35786. this.addUniform(name, temp);
  35787. };
  35788. /**
  35789. * Wrapper for addUniform.
  35790. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35791. * @param {Color3} color
  35792. */
  35793. UniformBuffer.prototype.addColor3 = function (name, color) {
  35794. var temp = new Array();
  35795. color.toArray(temp);
  35796. this.addUniform(name, temp);
  35797. };
  35798. /**
  35799. * Wrapper for addUniform.
  35800. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35801. * @param {Color3} color
  35802. * @param {number} alpha
  35803. */
  35804. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35805. var temp = new Array();
  35806. color.toArray(temp);
  35807. temp.push(alpha);
  35808. this.addUniform(name, temp);
  35809. };
  35810. /**
  35811. * Wrapper for addUniform.
  35812. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35813. * @param {Vector3} vector
  35814. */
  35815. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35816. var temp = new Array();
  35817. vector.toArray(temp);
  35818. this.addUniform(name, temp);
  35819. };
  35820. /**
  35821. * Wrapper for addUniform.
  35822. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35823. */
  35824. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35825. this.addUniform(name, 12);
  35826. };
  35827. /**
  35828. * Wrapper for addUniform.
  35829. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35830. */
  35831. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35832. this.addUniform(name, 8);
  35833. };
  35834. /**
  35835. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35836. */
  35837. UniformBuffer.prototype.create = function () {
  35838. if (this._noUBO) {
  35839. return;
  35840. }
  35841. if (this._buffer) {
  35842. return; // nothing to do
  35843. }
  35844. // See spec, alignment must be filled as a vec4
  35845. this._fillAlignment(4);
  35846. this._bufferData = new Float32Array(this._data);
  35847. this._rebuild();
  35848. this._needSync = true;
  35849. };
  35850. /** @hidden */
  35851. UniformBuffer.prototype._rebuild = function () {
  35852. if (this._noUBO) {
  35853. return;
  35854. }
  35855. if (this._dynamic) {
  35856. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35857. }
  35858. else {
  35859. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35860. }
  35861. };
  35862. /**
  35863. * Updates the WebGL Uniform Buffer on the GPU.
  35864. * If the `dynamic` flag is set to true, no cache comparison is done.
  35865. * Otherwise, the buffer will be updated only if the cache differs.
  35866. */
  35867. UniformBuffer.prototype.update = function () {
  35868. if (!this._buffer) {
  35869. this.create();
  35870. return;
  35871. }
  35872. if (!this._dynamic && !this._needSync) {
  35873. return;
  35874. }
  35875. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35876. this._needSync = false;
  35877. };
  35878. /**
  35879. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35880. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35881. * @param {number[]|Float32Array} data Flattened data
  35882. * @param {number} size Size of the data.
  35883. */
  35884. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35885. var location = this._uniformLocations[uniformName];
  35886. if (location === undefined) {
  35887. if (this._buffer) {
  35888. // Cannot add an uniform if the buffer is already created
  35889. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35890. return;
  35891. }
  35892. this.addUniform(uniformName, size);
  35893. location = this._uniformLocations[uniformName];
  35894. }
  35895. if (!this._buffer) {
  35896. this.create();
  35897. }
  35898. if (!this._dynamic) {
  35899. // Cache for static uniform buffers
  35900. var changed = false;
  35901. for (var i = 0; i < size; i++) {
  35902. if (this._bufferData[location + i] !== data[i]) {
  35903. changed = true;
  35904. this._bufferData[location + i] = data[i];
  35905. }
  35906. }
  35907. this._needSync = this._needSync || changed;
  35908. }
  35909. else {
  35910. // No cache for dynamic
  35911. for (var i = 0; i < size; i++) {
  35912. this._bufferData[location + i] = data[i];
  35913. }
  35914. }
  35915. };
  35916. // Update methods
  35917. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35918. // To match std140, matrix must be realigned
  35919. for (var i = 0; i < 3; i++) {
  35920. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35921. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35922. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35923. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35924. }
  35925. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35926. };
  35927. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35928. this._currentEffect.setMatrix3x3(name, matrix);
  35929. };
  35930. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35931. this._currentEffect.setMatrix2x2(name, matrix);
  35932. };
  35933. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35934. // To match std140, matrix must be realigned
  35935. for (var i = 0; i < 2; i++) {
  35936. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35937. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35938. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35939. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35940. }
  35941. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35942. };
  35943. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35944. this._currentEffect.setFloat(name, x);
  35945. };
  35946. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35947. UniformBuffer._tempBuffer[0] = x;
  35948. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35949. };
  35950. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35951. if (suffix === void 0) { suffix = ""; }
  35952. this._currentEffect.setFloat2(name + suffix, x, y);
  35953. };
  35954. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35955. if (suffix === void 0) { suffix = ""; }
  35956. UniformBuffer._tempBuffer[0] = x;
  35957. UniformBuffer._tempBuffer[1] = y;
  35958. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35959. };
  35960. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35961. if (suffix === void 0) { suffix = ""; }
  35962. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35963. };
  35964. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35965. if (suffix === void 0) { suffix = ""; }
  35966. UniformBuffer._tempBuffer[0] = x;
  35967. UniformBuffer._tempBuffer[1] = y;
  35968. UniformBuffer._tempBuffer[2] = z;
  35969. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35970. };
  35971. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35972. if (suffix === void 0) { suffix = ""; }
  35973. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35974. };
  35975. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35976. if (suffix === void 0) { suffix = ""; }
  35977. UniformBuffer._tempBuffer[0] = x;
  35978. UniformBuffer._tempBuffer[1] = y;
  35979. UniformBuffer._tempBuffer[2] = z;
  35980. UniformBuffer._tempBuffer[3] = w;
  35981. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35982. };
  35983. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35984. this._currentEffect.setMatrix(name, mat);
  35985. };
  35986. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35987. this.updateUniform(name, mat.toArray(), 16);
  35988. };
  35989. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35990. this._currentEffect.setVector3(name, vector);
  35991. };
  35992. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35993. vector.toArray(UniformBuffer._tempBuffer);
  35994. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35995. };
  35996. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35997. this._currentEffect.setVector4(name, vector);
  35998. };
  35999. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36000. vector.toArray(UniformBuffer._tempBuffer);
  36001. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36002. };
  36003. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36004. if (suffix === void 0) { suffix = ""; }
  36005. this._currentEffect.setColor3(name + suffix, color);
  36006. };
  36007. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36008. if (suffix === void 0) { suffix = ""; }
  36009. color.toArray(UniformBuffer._tempBuffer);
  36010. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36011. };
  36012. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36013. if (suffix === void 0) { suffix = ""; }
  36014. this._currentEffect.setColor4(name + suffix, color, alpha);
  36015. };
  36016. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36017. if (suffix === void 0) { suffix = ""; }
  36018. color.toArray(UniformBuffer._tempBuffer);
  36019. UniformBuffer._tempBuffer[3] = alpha;
  36020. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36021. };
  36022. /**
  36023. * Sets a sampler uniform on the effect.
  36024. * @param {string} name Name of the sampler.
  36025. * @param {Texture} texture
  36026. */
  36027. UniformBuffer.prototype.setTexture = function (name, texture) {
  36028. this._currentEffect.setTexture(name, texture);
  36029. };
  36030. /**
  36031. * Directly updates the value of the uniform in the cache AND on the GPU.
  36032. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36033. * @param {number[]|Float32Array} data Flattened data
  36034. */
  36035. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36036. this.updateUniform(uniformName, data, data.length);
  36037. this.update();
  36038. };
  36039. /**
  36040. * Binds this uniform buffer to an effect.
  36041. * @param {Effect} effect
  36042. * @param {string} name Name of the uniform block in the shader.
  36043. */
  36044. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36045. this._currentEffect = effect;
  36046. if (this._noUBO || !this._buffer) {
  36047. return;
  36048. }
  36049. effect.bindUniformBuffer(this._buffer, name);
  36050. };
  36051. /**
  36052. * Disposes the uniform buffer.
  36053. */
  36054. UniformBuffer.prototype.dispose = function () {
  36055. if (this._noUBO) {
  36056. return;
  36057. }
  36058. var index = this._engine._uniformBuffers.indexOf(this);
  36059. if (index !== -1) {
  36060. this._engine._uniformBuffers.splice(index, 1);
  36061. }
  36062. if (!this._buffer) {
  36063. return;
  36064. }
  36065. if (this._engine._releaseBuffer(this._buffer)) {
  36066. this._buffer = null;
  36067. }
  36068. };
  36069. // Pool for avoiding memory leaks
  36070. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36071. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36072. return UniformBuffer;
  36073. }());
  36074. BABYLON.UniformBuffer = UniformBuffer;
  36075. })(BABYLON || (BABYLON = {}));
  36076. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36077. var BABYLON;
  36078. (function (BABYLON) {
  36079. /**
  36080. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36081. */
  36082. var VertexData = /** @class */ (function () {
  36083. function VertexData() {
  36084. }
  36085. /**
  36086. * Uses the passed data array to set the set the values for the specified kind of data
  36087. * @param data a linear array of floating numbers
  36088. * @param kind the type of data that is being set, eg positions, colors etc
  36089. */
  36090. VertexData.prototype.set = function (data, kind) {
  36091. switch (kind) {
  36092. case BABYLON.VertexBuffer.PositionKind:
  36093. this.positions = data;
  36094. break;
  36095. case BABYLON.VertexBuffer.NormalKind:
  36096. this.normals = data;
  36097. break;
  36098. case BABYLON.VertexBuffer.TangentKind:
  36099. this.tangents = data;
  36100. break;
  36101. case BABYLON.VertexBuffer.UVKind:
  36102. this.uvs = data;
  36103. break;
  36104. case BABYLON.VertexBuffer.UV2Kind:
  36105. this.uvs2 = data;
  36106. break;
  36107. case BABYLON.VertexBuffer.UV3Kind:
  36108. this.uvs3 = data;
  36109. break;
  36110. case BABYLON.VertexBuffer.UV4Kind:
  36111. this.uvs4 = data;
  36112. break;
  36113. case BABYLON.VertexBuffer.UV5Kind:
  36114. this.uvs5 = data;
  36115. break;
  36116. case BABYLON.VertexBuffer.UV6Kind:
  36117. this.uvs6 = data;
  36118. break;
  36119. case BABYLON.VertexBuffer.ColorKind:
  36120. this.colors = data;
  36121. break;
  36122. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36123. this.matricesIndices = data;
  36124. break;
  36125. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36126. this.matricesWeights = data;
  36127. break;
  36128. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36129. this.matricesIndicesExtra = data;
  36130. break;
  36131. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36132. this.matricesWeightsExtra = data;
  36133. break;
  36134. }
  36135. };
  36136. /**
  36137. * Associates the vertexData to the passed Mesh.
  36138. * Sets it as updatable or not (default `false`)
  36139. * @param mesh the mesh the vertexData is applied to
  36140. * @param updatable when used and having the value true allows new data to update the vertexData
  36141. * @returns the VertexData
  36142. */
  36143. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36144. this._applyTo(mesh, updatable);
  36145. return this;
  36146. };
  36147. /**
  36148. * Associates the vertexData to the passed Geometry.
  36149. * Sets it as updatable or not (default `false`)
  36150. * @param geometry the geometry the vertexData is applied to
  36151. * @param updatable when used and having the value true allows new data to update the vertexData
  36152. * @returns VertexData
  36153. */
  36154. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36155. this._applyTo(geometry, updatable);
  36156. return this;
  36157. };
  36158. /**
  36159. * Updates the associated mesh
  36160. * @param mesh the mesh to be updated
  36161. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36162. * @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
  36163. * @returns VertexData
  36164. */
  36165. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36166. this._update(mesh);
  36167. return this;
  36168. };
  36169. /**
  36170. * Updates the associated geometry
  36171. * @param geometry the geometry to be updated
  36172. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36173. * @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
  36174. * @returns VertexData.
  36175. */
  36176. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36177. this._update(geometry);
  36178. return this;
  36179. };
  36180. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36181. if (updatable === void 0) { updatable = false; }
  36182. if (this.positions) {
  36183. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36184. }
  36185. if (this.normals) {
  36186. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36187. }
  36188. if (this.tangents) {
  36189. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36190. }
  36191. if (this.uvs) {
  36192. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36193. }
  36194. if (this.uvs2) {
  36195. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36196. }
  36197. if (this.uvs3) {
  36198. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36199. }
  36200. if (this.uvs4) {
  36201. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36202. }
  36203. if (this.uvs5) {
  36204. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36205. }
  36206. if (this.uvs6) {
  36207. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36208. }
  36209. if (this.colors) {
  36210. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36211. }
  36212. if (this.matricesIndices) {
  36213. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36214. }
  36215. if (this.matricesWeights) {
  36216. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36217. }
  36218. if (this.matricesIndicesExtra) {
  36219. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36220. }
  36221. if (this.matricesWeightsExtra) {
  36222. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36223. }
  36224. if (this.indices) {
  36225. meshOrGeometry.setIndices(this.indices, null, updatable);
  36226. }
  36227. else {
  36228. meshOrGeometry.setIndices([], null);
  36229. }
  36230. return this;
  36231. };
  36232. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36233. if (this.positions) {
  36234. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36235. }
  36236. if (this.normals) {
  36237. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36238. }
  36239. if (this.tangents) {
  36240. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36241. }
  36242. if (this.uvs) {
  36243. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36244. }
  36245. if (this.uvs2) {
  36246. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36247. }
  36248. if (this.uvs3) {
  36249. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36250. }
  36251. if (this.uvs4) {
  36252. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36253. }
  36254. if (this.uvs5) {
  36255. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36256. }
  36257. if (this.uvs6) {
  36258. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36259. }
  36260. if (this.colors) {
  36261. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36262. }
  36263. if (this.matricesIndices) {
  36264. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36265. }
  36266. if (this.matricesWeights) {
  36267. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36268. }
  36269. if (this.matricesIndicesExtra) {
  36270. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36271. }
  36272. if (this.matricesWeightsExtra) {
  36273. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36274. }
  36275. if (this.indices) {
  36276. meshOrGeometry.setIndices(this.indices, null);
  36277. }
  36278. return this;
  36279. };
  36280. /**
  36281. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36282. * @param matrix the transforming matrix
  36283. * @returns the VertexData
  36284. */
  36285. VertexData.prototype.transform = function (matrix) {
  36286. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36287. var transformed = BABYLON.Vector3.Zero();
  36288. var index;
  36289. if (this.positions) {
  36290. var position = BABYLON.Vector3.Zero();
  36291. for (index = 0; index < this.positions.length; index += 3) {
  36292. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36293. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36294. this.positions[index] = transformed.x;
  36295. this.positions[index + 1] = transformed.y;
  36296. this.positions[index + 2] = transformed.z;
  36297. }
  36298. }
  36299. if (this.normals) {
  36300. var normal = BABYLON.Vector3.Zero();
  36301. for (index = 0; index < this.normals.length; index += 3) {
  36302. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36303. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36304. this.normals[index] = transformed.x;
  36305. this.normals[index + 1] = transformed.y;
  36306. this.normals[index + 2] = transformed.z;
  36307. }
  36308. }
  36309. if (this.tangents) {
  36310. var tangent = BABYLON.Vector4.Zero();
  36311. var tangentTransformed = BABYLON.Vector4.Zero();
  36312. for (index = 0; index < this.tangents.length; index += 4) {
  36313. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36314. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36315. this.tangents[index] = tangentTransformed.x;
  36316. this.tangents[index + 1] = tangentTransformed.y;
  36317. this.tangents[index + 2] = tangentTransformed.z;
  36318. this.tangents[index + 3] = tangentTransformed.w;
  36319. }
  36320. }
  36321. if (flip && this.indices) {
  36322. for (index = 0; index < this.indices.length; index += 3) {
  36323. var tmp = this.indices[index + 1];
  36324. this.indices[index + 1] = this.indices[index + 2];
  36325. this.indices[index + 2] = tmp;
  36326. }
  36327. }
  36328. return this;
  36329. };
  36330. /**
  36331. * Merges the passed VertexData into the current one
  36332. * @param other the VertexData to be merged into the current one
  36333. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36334. * @returns the modified VertexData
  36335. */
  36336. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36337. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36338. this._validate();
  36339. other._validate();
  36340. if (!this.normals !== !other.normals ||
  36341. !this.tangents !== !other.tangents ||
  36342. !this.uvs !== !other.uvs ||
  36343. !this.uvs2 !== !other.uvs2 ||
  36344. !this.uvs3 !== !other.uvs3 ||
  36345. !this.uvs4 !== !other.uvs4 ||
  36346. !this.uvs5 !== !other.uvs5 ||
  36347. !this.uvs6 !== !other.uvs6 ||
  36348. !this.colors !== !other.colors ||
  36349. !this.matricesIndices !== !other.matricesIndices ||
  36350. !this.matricesWeights !== !other.matricesWeights ||
  36351. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36352. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36353. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36354. }
  36355. if (other.indices) {
  36356. if (!this.indices) {
  36357. this.indices = [];
  36358. }
  36359. var offset = this.positions ? this.positions.length / 3 : 0;
  36360. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36361. if (isSrcTypedArray) {
  36362. var len = this.indices.length + other.indices.length;
  36363. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36364. temp.set(this.indices);
  36365. var decal = this.indices.length;
  36366. for (var index = 0; index < other.indices.length; index++) {
  36367. temp[decal + index] = other.indices[index] + offset;
  36368. }
  36369. this.indices = temp;
  36370. }
  36371. else {
  36372. for (var index = 0; index < other.indices.length; index++) {
  36373. this.indices.push(other.indices[index] + offset);
  36374. }
  36375. }
  36376. }
  36377. this.positions = this._mergeElement(this.positions, other.positions);
  36378. this.normals = this._mergeElement(this.normals, other.normals);
  36379. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36380. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36381. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36382. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36383. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36384. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36385. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36386. this.colors = this._mergeElement(this.colors, other.colors);
  36387. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36388. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36389. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36390. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36391. return this;
  36392. };
  36393. VertexData.prototype._mergeElement = function (source, other) {
  36394. if (!source) {
  36395. return other;
  36396. }
  36397. if (!other) {
  36398. return source;
  36399. }
  36400. var len = other.length + source.length;
  36401. var isSrcTypedArray = source instanceof Float32Array;
  36402. var isOthTypedArray = other instanceof Float32Array;
  36403. // use non-loop method when the source is Float32Array
  36404. if (isSrcTypedArray) {
  36405. var ret32 = new Float32Array(len);
  36406. ret32.set(source);
  36407. ret32.set(other, source.length);
  36408. return ret32;
  36409. // source is number[], when other is also use concat
  36410. }
  36411. else if (!isOthTypedArray) {
  36412. return source.concat(other);
  36413. // source is a number[], but other is a Float32Array, loop required
  36414. }
  36415. else {
  36416. var ret = source.slice(0); // copy source to a separate array
  36417. for (var i = 0, len = other.length; i < len; i++) {
  36418. ret.push(other[i]);
  36419. }
  36420. return ret;
  36421. }
  36422. };
  36423. VertexData.prototype._validate = function () {
  36424. if (!this.positions) {
  36425. throw new Error("Positions are required");
  36426. }
  36427. var getElementCount = function (kind, values) {
  36428. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36429. if ((values.length % stride) !== 0) {
  36430. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36431. }
  36432. return values.length / stride;
  36433. };
  36434. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36435. var validateElementCount = function (kind, values) {
  36436. var elementCount = getElementCount(kind, values);
  36437. if (elementCount !== positionsElementCount) {
  36438. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36439. }
  36440. };
  36441. if (this.normals)
  36442. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36443. if (this.tangents)
  36444. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36445. if (this.uvs)
  36446. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36447. if (this.uvs2)
  36448. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36449. if (this.uvs3)
  36450. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36451. if (this.uvs4)
  36452. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36453. if (this.uvs5)
  36454. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36455. if (this.uvs6)
  36456. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36457. if (this.colors)
  36458. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36459. if (this.matricesIndices)
  36460. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36461. if (this.matricesWeights)
  36462. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36463. if (this.matricesIndicesExtra)
  36464. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36465. if (this.matricesWeightsExtra)
  36466. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36467. };
  36468. /**
  36469. * Serializes the VertexData
  36470. * @returns a serialized object
  36471. */
  36472. VertexData.prototype.serialize = function () {
  36473. var serializationObject = this.serialize();
  36474. if (this.positions) {
  36475. serializationObject.positions = this.positions;
  36476. }
  36477. if (this.normals) {
  36478. serializationObject.normals = this.normals;
  36479. }
  36480. if (this.tangents) {
  36481. serializationObject.tangents = this.tangents;
  36482. }
  36483. if (this.uvs) {
  36484. serializationObject.uvs = this.uvs;
  36485. }
  36486. if (this.uvs2) {
  36487. serializationObject.uvs2 = this.uvs2;
  36488. }
  36489. if (this.uvs3) {
  36490. serializationObject.uvs3 = this.uvs3;
  36491. }
  36492. if (this.uvs4) {
  36493. serializationObject.uvs4 = this.uvs4;
  36494. }
  36495. if (this.uvs5) {
  36496. serializationObject.uvs5 = this.uvs5;
  36497. }
  36498. if (this.uvs6) {
  36499. serializationObject.uvs6 = this.uvs6;
  36500. }
  36501. if (this.colors) {
  36502. serializationObject.colors = this.colors;
  36503. }
  36504. if (this.matricesIndices) {
  36505. serializationObject.matricesIndices = this.matricesIndices;
  36506. serializationObject.matricesIndices._isExpanded = true;
  36507. }
  36508. if (this.matricesWeights) {
  36509. serializationObject.matricesWeights = this.matricesWeights;
  36510. }
  36511. if (this.matricesIndicesExtra) {
  36512. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36513. serializationObject.matricesIndicesExtra._isExpanded = true;
  36514. }
  36515. if (this.matricesWeightsExtra) {
  36516. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36517. }
  36518. serializationObject.indices = this.indices;
  36519. return serializationObject;
  36520. };
  36521. // Statics
  36522. /**
  36523. * Extracts the vertexData from a mesh
  36524. * @param mesh the mesh from which to extract the VertexData
  36525. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36526. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36527. * @returns the object VertexData associated to the passed mesh
  36528. */
  36529. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36530. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36531. };
  36532. /**
  36533. * Extracts the vertexData from the geometry
  36534. * @param geometry the geometry from which to extract the VertexData
  36535. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36536. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36537. * @returns the object VertexData associated to the passed mesh
  36538. */
  36539. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36540. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36541. };
  36542. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36543. var result = new VertexData();
  36544. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36545. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36546. }
  36547. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36548. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36549. }
  36550. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36551. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36552. }
  36553. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36554. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36555. }
  36556. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36557. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36558. }
  36559. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36560. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36561. }
  36562. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36563. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36564. }
  36565. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36566. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36567. }
  36568. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36569. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36570. }
  36571. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36572. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36573. }
  36574. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36575. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36576. }
  36577. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36578. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36579. }
  36580. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36581. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36582. }
  36583. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36584. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36585. }
  36586. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36587. return result;
  36588. };
  36589. /**
  36590. * Creates the VertexData for a Ribbon
  36591. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36592. * * pathArray array of paths, each of which an array of successive Vector3
  36593. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36594. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36595. * * 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
  36596. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36597. * * 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)
  36598. * * 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)
  36599. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36600. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36601. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36602. * @returns the VertexData of the ribbon
  36603. */
  36604. VertexData.CreateRibbon = function (options) {
  36605. var pathArray = options.pathArray;
  36606. var closeArray = options.closeArray || false;
  36607. var closePath = options.closePath || false;
  36608. var invertUV = options.invertUV || false;
  36609. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36610. var offset = options.offset || defaultOffset;
  36611. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36612. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36613. var customUV = options.uvs;
  36614. var customColors = options.colors;
  36615. var positions = [];
  36616. var indices = [];
  36617. var normals = [];
  36618. var uvs = [];
  36619. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36620. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36621. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36622. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36623. var minlg; // minimal length among all paths from pathArray
  36624. var lg = []; // array of path lengths : nb of vertex per path
  36625. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36626. var p; // path iterator
  36627. var i; // point iterator
  36628. var j; // point iterator
  36629. // if single path in pathArray
  36630. if (pathArray.length < 2) {
  36631. var ar1 = [];
  36632. var ar2 = [];
  36633. for (i = 0; i < pathArray[0].length - offset; i++) {
  36634. ar1.push(pathArray[0][i]);
  36635. ar2.push(pathArray[0][i + offset]);
  36636. }
  36637. pathArray = [ar1, ar2];
  36638. }
  36639. // positions and horizontal distances (u)
  36640. var idc = 0;
  36641. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36642. var path;
  36643. var l;
  36644. minlg = pathArray[0].length;
  36645. var vectlg;
  36646. var dist;
  36647. for (p = 0; p < pathArray.length; p++) {
  36648. uTotalDistance[p] = 0;
  36649. us[p] = [0];
  36650. path = pathArray[p];
  36651. l = path.length;
  36652. minlg = (minlg < l) ? minlg : l;
  36653. j = 0;
  36654. while (j < l) {
  36655. positions.push(path[j].x, path[j].y, path[j].z);
  36656. if (j > 0) {
  36657. vectlg = path[j].subtract(path[j - 1]).length();
  36658. dist = vectlg + uTotalDistance[p];
  36659. us[p].push(dist);
  36660. uTotalDistance[p] = dist;
  36661. }
  36662. j++;
  36663. }
  36664. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36665. j--;
  36666. positions.push(path[0].x, path[0].y, path[0].z);
  36667. vectlg = path[j].subtract(path[0]).length();
  36668. dist = vectlg + uTotalDistance[p];
  36669. us[p].push(dist);
  36670. uTotalDistance[p] = dist;
  36671. }
  36672. lg[p] = l + closePathCorr;
  36673. idx[p] = idc;
  36674. idc += (l + closePathCorr);
  36675. }
  36676. // vertical distances (v)
  36677. var path1;
  36678. var path2;
  36679. var vertex1 = null;
  36680. var vertex2 = null;
  36681. for (i = 0; i < minlg + closePathCorr; i++) {
  36682. vTotalDistance[i] = 0;
  36683. vs[i] = [0];
  36684. for (p = 0; p < pathArray.length - 1; p++) {
  36685. path1 = pathArray[p];
  36686. path2 = pathArray[p + 1];
  36687. if (i === minlg) { // closePath
  36688. vertex1 = path1[0];
  36689. vertex2 = path2[0];
  36690. }
  36691. else {
  36692. vertex1 = path1[i];
  36693. vertex2 = path2[i];
  36694. }
  36695. vectlg = vertex2.subtract(vertex1).length();
  36696. dist = vectlg + vTotalDistance[i];
  36697. vs[i].push(dist);
  36698. vTotalDistance[i] = dist;
  36699. }
  36700. if (closeArray && vertex2 && vertex1) {
  36701. path1 = pathArray[p];
  36702. path2 = pathArray[0];
  36703. if (i === minlg) { // closePath
  36704. vertex2 = path2[0];
  36705. }
  36706. vectlg = vertex2.subtract(vertex1).length();
  36707. dist = vectlg + vTotalDistance[i];
  36708. vTotalDistance[i] = dist;
  36709. }
  36710. }
  36711. // uvs
  36712. var u;
  36713. var v;
  36714. if (customUV) {
  36715. for (p = 0; p < customUV.length; p++) {
  36716. uvs.push(customUV[p].x, customUV[p].y);
  36717. }
  36718. }
  36719. else {
  36720. for (p = 0; p < pathArray.length; p++) {
  36721. for (i = 0; i < minlg + closePathCorr; i++) {
  36722. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36723. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36724. if (invertUV) {
  36725. uvs.push(v, u);
  36726. }
  36727. else {
  36728. uvs.push(u, v);
  36729. }
  36730. }
  36731. }
  36732. }
  36733. // indices
  36734. p = 0; // path index
  36735. var pi = 0; // positions array index
  36736. var l1 = lg[p] - 1; // path1 length
  36737. var l2 = lg[p + 1] - 1; // path2 length
  36738. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36739. var shft = idx[1] - idx[0]; // shift
  36740. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36741. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36742. // 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
  36743. indices.push(pi, pi + shft, pi + 1);
  36744. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36745. pi += 1;
  36746. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36747. p++;
  36748. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36749. shft = idx[0] - idx[p];
  36750. l1 = lg[p] - 1;
  36751. l2 = lg[0] - 1;
  36752. }
  36753. else {
  36754. shft = idx[p + 1] - idx[p];
  36755. l1 = lg[p] - 1;
  36756. l2 = lg[p + 1] - 1;
  36757. }
  36758. pi = idx[p];
  36759. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36760. }
  36761. }
  36762. // normals
  36763. VertexData.ComputeNormals(positions, indices, normals);
  36764. if (closePath) { // update both the first and last vertex normals to their average value
  36765. var indexFirst = 0;
  36766. var indexLast = 0;
  36767. for (p = 0; p < pathArray.length; p++) {
  36768. indexFirst = idx[p] * 3;
  36769. if (p + 1 < pathArray.length) {
  36770. indexLast = (idx[p + 1] - 1) * 3;
  36771. }
  36772. else {
  36773. indexLast = normals.length - 3;
  36774. }
  36775. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36776. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36777. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36778. normals[indexLast] = normals[indexFirst];
  36779. normals[indexLast + 1] = normals[indexFirst + 1];
  36780. normals[indexLast + 2] = normals[indexFirst + 2];
  36781. }
  36782. }
  36783. // sides
  36784. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36785. // Colors
  36786. var colors = null;
  36787. if (customColors) {
  36788. colors = new Float32Array(customColors.length * 4);
  36789. for (var c = 0; c < customColors.length; c++) {
  36790. colors[c * 4] = customColors[c].r;
  36791. colors[c * 4 + 1] = customColors[c].g;
  36792. colors[c * 4 + 2] = customColors[c].b;
  36793. colors[c * 4 + 3] = customColors[c].a;
  36794. }
  36795. }
  36796. // Result
  36797. var vertexData = new VertexData();
  36798. var positions32 = new Float32Array(positions);
  36799. var normals32 = new Float32Array(normals);
  36800. var uvs32 = new Float32Array(uvs);
  36801. vertexData.indices = indices;
  36802. vertexData.positions = positions32;
  36803. vertexData.normals = normals32;
  36804. vertexData.uvs = uvs32;
  36805. if (colors) {
  36806. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36807. }
  36808. if (closePath) {
  36809. vertexData._idx = idx;
  36810. }
  36811. return vertexData;
  36812. };
  36813. /**
  36814. * Creates the VertexData for a box
  36815. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36816. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36817. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36818. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36819. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36820. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36821. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36822. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36823. * * 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)
  36824. * * 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)
  36825. * @returns the VertexData of the box
  36826. */
  36827. VertexData.CreateBox = function (options) {
  36828. var normalsSource = [
  36829. new BABYLON.Vector3(0, 0, 1),
  36830. new BABYLON.Vector3(0, 0, -1),
  36831. new BABYLON.Vector3(1, 0, 0),
  36832. new BABYLON.Vector3(-1, 0, 0),
  36833. new BABYLON.Vector3(0, 1, 0),
  36834. new BABYLON.Vector3(0, -1, 0)
  36835. ];
  36836. var indices = [];
  36837. var positions = [];
  36838. var normals = [];
  36839. var uvs = [];
  36840. var width = options.width || options.size || 1;
  36841. var height = options.height || options.size || 1;
  36842. var depth = options.depth || options.size || 1;
  36843. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36844. var faceUV = options.faceUV || new Array(6);
  36845. var faceColors = options.faceColors;
  36846. var colors = [];
  36847. // default face colors and UV if undefined
  36848. for (var f = 0; f < 6; f++) {
  36849. if (faceUV[f] === undefined) {
  36850. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36851. }
  36852. if (faceColors && faceColors[f] === undefined) {
  36853. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36854. }
  36855. }
  36856. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36857. // Create each face in turn.
  36858. for (var index = 0; index < normalsSource.length; index++) {
  36859. var normal = normalsSource[index];
  36860. // Get two vectors perpendicular to the face normal and to each other.
  36861. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36862. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36863. // Six indices (two triangles) per face.
  36864. var verticesLength = positions.length / 3;
  36865. indices.push(verticesLength);
  36866. indices.push(verticesLength + 1);
  36867. indices.push(verticesLength + 2);
  36868. indices.push(verticesLength);
  36869. indices.push(verticesLength + 2);
  36870. indices.push(verticesLength + 3);
  36871. // Four vertices per face.
  36872. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36873. positions.push(vertex.x, vertex.y, vertex.z);
  36874. normals.push(normal.x, normal.y, normal.z);
  36875. uvs.push(faceUV[index].z, faceUV[index].w);
  36876. if (faceColors) {
  36877. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36878. }
  36879. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36880. positions.push(vertex.x, vertex.y, vertex.z);
  36881. normals.push(normal.x, normal.y, normal.z);
  36882. uvs.push(faceUV[index].x, faceUV[index].w);
  36883. if (faceColors) {
  36884. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36885. }
  36886. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36887. positions.push(vertex.x, vertex.y, vertex.z);
  36888. normals.push(normal.x, normal.y, normal.z);
  36889. uvs.push(faceUV[index].x, faceUV[index].y);
  36890. if (faceColors) {
  36891. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36892. }
  36893. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36894. positions.push(vertex.x, vertex.y, vertex.z);
  36895. normals.push(normal.x, normal.y, normal.z);
  36896. uvs.push(faceUV[index].z, faceUV[index].y);
  36897. if (faceColors) {
  36898. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36899. }
  36900. }
  36901. // sides
  36902. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36903. // Result
  36904. var vertexData = new VertexData();
  36905. vertexData.indices = indices;
  36906. vertexData.positions = positions;
  36907. vertexData.normals = normals;
  36908. vertexData.uvs = uvs;
  36909. if (faceColors) {
  36910. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36911. vertexData.colors = totalColors;
  36912. }
  36913. return vertexData;
  36914. };
  36915. /**
  36916. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36917. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36918. * * segments sets the number of horizontal strips optional, default 32
  36919. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36920. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36921. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36922. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36923. * * 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
  36924. * * 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
  36925. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36926. * * 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)
  36927. * * 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)
  36928. * @returns the VertexData of the ellipsoid
  36929. */
  36930. VertexData.CreateSphere = function (options) {
  36931. var segments = options.segments || 32;
  36932. var diameterX = options.diameterX || options.diameter || 1;
  36933. var diameterY = options.diameterY || options.diameter || 1;
  36934. var diameterZ = options.diameterZ || options.diameter || 1;
  36935. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36936. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36937. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36938. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36939. var totalZRotationSteps = 2 + segments;
  36940. var totalYRotationSteps = 2 * totalZRotationSteps;
  36941. var indices = [];
  36942. var positions = [];
  36943. var normals = [];
  36944. var uvs = [];
  36945. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36946. var normalizedZ = zRotationStep / totalZRotationSteps;
  36947. var angleZ = normalizedZ * Math.PI * slice;
  36948. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36949. var normalizedY = yRotationStep / totalYRotationSteps;
  36950. var angleY = normalizedY * Math.PI * 2 * arc;
  36951. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36952. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36953. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36954. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36955. var vertex = complete.multiply(radius);
  36956. var normal = complete.divide(radius).normalize();
  36957. positions.push(vertex.x, vertex.y, vertex.z);
  36958. normals.push(normal.x, normal.y, normal.z);
  36959. uvs.push(normalizedY, normalizedZ);
  36960. }
  36961. if (zRotationStep > 0) {
  36962. var verticesCount = positions.length / 3;
  36963. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36964. indices.push((firstIndex));
  36965. indices.push((firstIndex + 1));
  36966. indices.push(firstIndex + totalYRotationSteps + 1);
  36967. indices.push((firstIndex + totalYRotationSteps + 1));
  36968. indices.push((firstIndex + 1));
  36969. indices.push((firstIndex + totalYRotationSteps + 2));
  36970. }
  36971. }
  36972. }
  36973. // Sides
  36974. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36975. // Result
  36976. var vertexData = new VertexData();
  36977. vertexData.indices = indices;
  36978. vertexData.positions = positions;
  36979. vertexData.normals = normals;
  36980. vertexData.uvs = uvs;
  36981. return vertexData;
  36982. };
  36983. /**
  36984. * Creates the VertexData for a cylinder, cone or prism
  36985. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36986. * * height sets the height (y direction) of the cylinder, optional, default 2
  36987. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36988. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36989. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36990. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36991. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36992. * * 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
  36993. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36994. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36995. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36996. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36997. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36998. * * 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)
  36999. * * 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)
  37000. * @returns the VertexData of the cylinder, cone or prism
  37001. */
  37002. VertexData.CreateCylinder = function (options) {
  37003. var height = options.height || 2;
  37004. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37005. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37006. var tessellation = options.tessellation || 24;
  37007. var subdivisions = options.subdivisions || 1;
  37008. var hasRings = options.hasRings ? true : false;
  37009. var enclose = options.enclose ? true : false;
  37010. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37011. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37012. var faceUV = options.faceUV || new Array(3);
  37013. var faceColors = options.faceColors;
  37014. // default face colors and UV if undefined
  37015. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37016. var ringNb = (hasRings) ? subdivisions : 1;
  37017. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37018. var f;
  37019. for (f = 0; f < surfaceNb; f++) {
  37020. if (faceColors && faceColors[f] === undefined) {
  37021. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37022. }
  37023. }
  37024. for (f = 0; f < surfaceNb; f++) {
  37025. if (faceUV && faceUV[f] === undefined) {
  37026. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37027. }
  37028. }
  37029. var indices = new Array();
  37030. var positions = new Array();
  37031. var normals = new Array();
  37032. var uvs = new Array();
  37033. var colors = new Array();
  37034. var angle_step = Math.PI * 2 * arc / tessellation;
  37035. var angle;
  37036. var h;
  37037. var radius;
  37038. var tan = (diameterBottom - diameterTop) / 2 / height;
  37039. var ringVertex = BABYLON.Vector3.Zero();
  37040. var ringNormal = BABYLON.Vector3.Zero();
  37041. var ringFirstVertex = BABYLON.Vector3.Zero();
  37042. var ringFirstNormal = BABYLON.Vector3.Zero();
  37043. var quadNormal = BABYLON.Vector3.Zero();
  37044. var Y = BABYLON.Axis.Y;
  37045. // positions, normals, uvs
  37046. var i;
  37047. var j;
  37048. var r;
  37049. var ringIdx = 1;
  37050. var s = 1; // surface index
  37051. var cs = 0;
  37052. var v = 0;
  37053. for (i = 0; i <= subdivisions; i++) {
  37054. h = i / subdivisions;
  37055. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37056. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37057. for (r = 0; r < ringIdx; r++) {
  37058. if (hasRings) {
  37059. s += r;
  37060. }
  37061. if (enclose) {
  37062. s += 2 * r;
  37063. }
  37064. for (j = 0; j <= tessellation; j++) {
  37065. angle = j * angle_step;
  37066. // position
  37067. ringVertex.x = Math.cos(-angle) * radius;
  37068. ringVertex.y = -height / 2 + h * height;
  37069. ringVertex.z = Math.sin(-angle) * radius;
  37070. // normal
  37071. if (diameterTop === 0 && i === subdivisions) {
  37072. // if no top cap, reuse former normals
  37073. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37074. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37075. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37076. }
  37077. else {
  37078. ringNormal.x = ringVertex.x;
  37079. ringNormal.z = ringVertex.z;
  37080. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37081. ringNormal.normalize();
  37082. }
  37083. // keep first ring vertex values for enclose
  37084. if (j === 0) {
  37085. ringFirstVertex.copyFrom(ringVertex);
  37086. ringFirstNormal.copyFrom(ringNormal);
  37087. }
  37088. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37089. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37090. if (hasRings) {
  37091. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37092. }
  37093. else {
  37094. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37095. }
  37096. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37097. if (faceColors) {
  37098. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37099. }
  37100. }
  37101. // if enclose, add four vertices and their dedicated normals
  37102. if (arc !== 1 && enclose) {
  37103. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37104. positions.push(0, ringVertex.y, 0);
  37105. positions.push(0, ringVertex.y, 0);
  37106. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37107. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37108. quadNormal.normalize();
  37109. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37110. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37111. quadNormal.normalize();
  37112. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37113. if (hasRings) {
  37114. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37115. }
  37116. else {
  37117. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37118. }
  37119. uvs.push(faceUV[s + 1].x, v);
  37120. uvs.push(faceUV[s + 1].z, v);
  37121. if (hasRings) {
  37122. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37123. }
  37124. else {
  37125. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37126. }
  37127. uvs.push(faceUV[s + 2].x, v);
  37128. uvs.push(faceUV[s + 2].z, v);
  37129. if (faceColors) {
  37130. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37131. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37132. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37133. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37134. }
  37135. }
  37136. if (cs !== s) {
  37137. cs = s;
  37138. }
  37139. }
  37140. }
  37141. // indices
  37142. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37143. var s;
  37144. i = 0;
  37145. for (s = 0; s < subdivisions; s++) {
  37146. var i0 = 0;
  37147. var i1 = 0;
  37148. var i2 = 0;
  37149. var i3 = 0;
  37150. for (j = 0; j < tessellation; j++) {
  37151. i0 = i * (e + 1) + j;
  37152. i1 = (i + 1) * (e + 1) + j;
  37153. i2 = i * (e + 1) + (j + 1);
  37154. i3 = (i + 1) * (e + 1) + (j + 1);
  37155. indices.push(i0, i1, i2);
  37156. indices.push(i3, i2, i1);
  37157. }
  37158. if (arc !== 1 && enclose) { // if enclose, add two quads
  37159. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37160. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37161. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37162. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37163. }
  37164. i = (hasRings) ? (i + 2) : (i + 1);
  37165. }
  37166. // Caps
  37167. var createCylinderCap = function (isTop) {
  37168. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37169. if (radius === 0) {
  37170. return;
  37171. }
  37172. // Cap positions, normals & uvs
  37173. var angle;
  37174. var circleVector;
  37175. var i;
  37176. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37177. var c = null;
  37178. if (faceColors) {
  37179. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37180. }
  37181. // cap center
  37182. var vbase = positions.length / 3;
  37183. var offset = isTop ? height / 2 : -height / 2;
  37184. var center = new BABYLON.Vector3(0, offset, 0);
  37185. positions.push(center.x, center.y, center.z);
  37186. normals.push(0, isTop ? 1 : -1, 0);
  37187. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37188. if (c) {
  37189. colors.push(c.r, c.g, c.b, c.a);
  37190. }
  37191. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37192. for (i = 0; i <= tessellation; i++) {
  37193. angle = Math.PI * 2 * i * arc / tessellation;
  37194. var cos = Math.cos(-angle);
  37195. var sin = Math.sin(-angle);
  37196. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37197. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37198. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37199. normals.push(0, isTop ? 1 : -1, 0);
  37200. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37201. if (c) {
  37202. colors.push(c.r, c.g, c.b, c.a);
  37203. }
  37204. }
  37205. // Cap indices
  37206. for (i = 0; i < tessellation; i++) {
  37207. if (!isTop) {
  37208. indices.push(vbase);
  37209. indices.push(vbase + (i + 1));
  37210. indices.push(vbase + (i + 2));
  37211. }
  37212. else {
  37213. indices.push(vbase);
  37214. indices.push(vbase + (i + 2));
  37215. indices.push(vbase + (i + 1));
  37216. }
  37217. }
  37218. };
  37219. // add caps to geometry
  37220. createCylinderCap(false);
  37221. createCylinderCap(true);
  37222. // Sides
  37223. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37224. var vertexData = new VertexData();
  37225. vertexData.indices = indices;
  37226. vertexData.positions = positions;
  37227. vertexData.normals = normals;
  37228. vertexData.uvs = uvs;
  37229. if (faceColors) {
  37230. vertexData.colors = colors;
  37231. }
  37232. return vertexData;
  37233. };
  37234. /**
  37235. * Creates the VertexData for a torus
  37236. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37237. * * diameter the diameter of the torus, optional default 1
  37238. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37239. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37240. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37241. * * 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)
  37242. * * 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)
  37243. * @returns the VertexData of the torus
  37244. */
  37245. VertexData.CreateTorus = function (options) {
  37246. var indices = [];
  37247. var positions = [];
  37248. var normals = [];
  37249. var uvs = [];
  37250. var diameter = options.diameter || 1;
  37251. var thickness = options.thickness || 0.5;
  37252. var tessellation = options.tessellation || 16;
  37253. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37254. var stride = tessellation + 1;
  37255. for (var i = 0; i <= tessellation; i++) {
  37256. var u = i / tessellation;
  37257. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37258. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37259. for (var j = 0; j <= tessellation; j++) {
  37260. var v = 1 - j / tessellation;
  37261. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37262. var dx = Math.cos(innerAngle);
  37263. var dy = Math.sin(innerAngle);
  37264. // Create a vertex.
  37265. var normal = new BABYLON.Vector3(dx, dy, 0);
  37266. var position = normal.scale(thickness / 2);
  37267. var textureCoordinate = new BABYLON.Vector2(u, v);
  37268. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37269. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37270. positions.push(position.x, position.y, position.z);
  37271. normals.push(normal.x, normal.y, normal.z);
  37272. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37273. // And create indices for two triangles.
  37274. var nextI = (i + 1) % stride;
  37275. var nextJ = (j + 1) % stride;
  37276. indices.push(i * stride + j);
  37277. indices.push(i * stride + nextJ);
  37278. indices.push(nextI * stride + j);
  37279. indices.push(i * stride + nextJ);
  37280. indices.push(nextI * stride + nextJ);
  37281. indices.push(nextI * stride + j);
  37282. }
  37283. }
  37284. // Sides
  37285. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37286. // Result
  37287. var vertexData = new VertexData();
  37288. vertexData.indices = indices;
  37289. vertexData.positions = positions;
  37290. vertexData.normals = normals;
  37291. vertexData.uvs = uvs;
  37292. return vertexData;
  37293. };
  37294. /**
  37295. * Creates the VertexData of the LineSystem
  37296. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37297. * - lines an array of lines, each line being an array of successive Vector3
  37298. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37299. * @returns the VertexData of the LineSystem
  37300. */
  37301. VertexData.CreateLineSystem = function (options) {
  37302. var indices = [];
  37303. var positions = [];
  37304. var lines = options.lines;
  37305. var colors = options.colors;
  37306. var vertexColors = [];
  37307. var idx = 0;
  37308. for (var l = 0; l < lines.length; l++) {
  37309. var points = lines[l];
  37310. for (var index = 0; index < points.length; index++) {
  37311. positions.push(points[index].x, points[index].y, points[index].z);
  37312. if (colors) {
  37313. var color = colors[l];
  37314. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37315. }
  37316. if (index > 0) {
  37317. indices.push(idx - 1);
  37318. indices.push(idx);
  37319. }
  37320. idx++;
  37321. }
  37322. }
  37323. var vertexData = new VertexData();
  37324. vertexData.indices = indices;
  37325. vertexData.positions = positions;
  37326. if (colors) {
  37327. vertexData.colors = vertexColors;
  37328. }
  37329. return vertexData;
  37330. };
  37331. /**
  37332. * Create the VertexData for a DashedLines
  37333. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37334. * - points an array successive Vector3
  37335. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37336. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37337. * - dashNb the intended total number of dashes, optional, default 200
  37338. * @returns the VertexData for the DashedLines
  37339. */
  37340. VertexData.CreateDashedLines = function (options) {
  37341. var dashSize = options.dashSize || 3;
  37342. var gapSize = options.gapSize || 1;
  37343. var dashNb = options.dashNb || 200;
  37344. var points = options.points;
  37345. var positions = new Array();
  37346. var indices = new Array();
  37347. var curvect = BABYLON.Vector3.Zero();
  37348. var lg = 0;
  37349. var nb = 0;
  37350. var shft = 0;
  37351. var dashshft = 0;
  37352. var curshft = 0;
  37353. var idx = 0;
  37354. var i = 0;
  37355. for (i = 0; i < points.length - 1; i++) {
  37356. points[i + 1].subtractToRef(points[i], curvect);
  37357. lg += curvect.length();
  37358. }
  37359. shft = lg / dashNb;
  37360. dashshft = dashSize * shft / (dashSize + gapSize);
  37361. for (i = 0; i < points.length - 1; i++) {
  37362. points[i + 1].subtractToRef(points[i], curvect);
  37363. nb = Math.floor(curvect.length() / shft);
  37364. curvect.normalize();
  37365. for (var j = 0; j < nb; j++) {
  37366. curshft = shft * j;
  37367. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37368. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37369. indices.push(idx, idx + 1);
  37370. idx += 2;
  37371. }
  37372. }
  37373. // Result
  37374. var vertexData = new VertexData();
  37375. vertexData.positions = positions;
  37376. vertexData.indices = indices;
  37377. return vertexData;
  37378. };
  37379. /**
  37380. * Creates the VertexData for a Ground
  37381. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37382. * - width the width (x direction) of the ground, optional, default 1
  37383. * - height the height (z direction) of the ground, optional, default 1
  37384. * - subdivisions the number of subdivisions per side, optional, default 1
  37385. * @returns the VertexData of the Ground
  37386. */
  37387. VertexData.CreateGround = function (options) {
  37388. var indices = [];
  37389. var positions = [];
  37390. var normals = [];
  37391. var uvs = [];
  37392. var row, col;
  37393. var width = options.width || 1;
  37394. var height = options.height || 1;
  37395. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37396. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37397. for (row = 0; row <= subdivisionsY; row++) {
  37398. for (col = 0; col <= subdivisionsX; col++) {
  37399. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37400. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37401. positions.push(position.x, position.y, position.z);
  37402. normals.push(normal.x, normal.y, normal.z);
  37403. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37404. }
  37405. }
  37406. for (row = 0; row < subdivisionsY; row++) {
  37407. for (col = 0; col < subdivisionsX; col++) {
  37408. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37409. indices.push(col + 1 + row * (subdivisionsX + 1));
  37410. indices.push(col + row * (subdivisionsX + 1));
  37411. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37412. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37413. indices.push(col + row * (subdivisionsX + 1));
  37414. }
  37415. }
  37416. // Result
  37417. var vertexData = new VertexData();
  37418. vertexData.indices = indices;
  37419. vertexData.positions = positions;
  37420. vertexData.normals = normals;
  37421. vertexData.uvs = uvs;
  37422. return vertexData;
  37423. };
  37424. /**
  37425. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37426. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37427. * * xmin the ground minimum X coordinate, optional, default -1
  37428. * * zmin the ground minimum Z coordinate, optional, default -1
  37429. * * xmax the ground maximum X coordinate, optional, default 1
  37430. * * zmax the ground maximum Z coordinate, optional, default 1
  37431. * * 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}
  37432. * * 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}
  37433. * @returns the VertexData of the TiledGround
  37434. */
  37435. VertexData.CreateTiledGround = function (options) {
  37436. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37437. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37438. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37439. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37440. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37441. var precision = options.precision || { w: 1, h: 1 };
  37442. var indices = new Array();
  37443. var positions = new Array();
  37444. var normals = new Array();
  37445. var uvs = new Array();
  37446. var row, col, tileRow, tileCol;
  37447. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37448. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37449. precision.w = (precision.w < 1) ? 1 : precision.w;
  37450. precision.h = (precision.h < 1) ? 1 : precision.h;
  37451. var tileSize = {
  37452. 'w': (xmax - xmin) / subdivisions.w,
  37453. 'h': (zmax - zmin) / subdivisions.h
  37454. };
  37455. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37456. // Indices
  37457. var base = positions.length / 3;
  37458. var rowLength = precision.w + 1;
  37459. for (row = 0; row < precision.h; row++) {
  37460. for (col = 0; col < precision.w; col++) {
  37461. var square = [
  37462. base + col + row * rowLength,
  37463. base + (col + 1) + row * rowLength,
  37464. base + (col + 1) + (row + 1) * rowLength,
  37465. base + col + (row + 1) * rowLength
  37466. ];
  37467. indices.push(square[1]);
  37468. indices.push(square[2]);
  37469. indices.push(square[3]);
  37470. indices.push(square[0]);
  37471. indices.push(square[1]);
  37472. indices.push(square[3]);
  37473. }
  37474. }
  37475. // Position, normals and uvs
  37476. var position = BABYLON.Vector3.Zero();
  37477. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37478. for (row = 0; row <= precision.h; row++) {
  37479. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37480. for (col = 0; col <= precision.w; col++) {
  37481. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37482. position.y = 0;
  37483. positions.push(position.x, position.y, position.z);
  37484. normals.push(normal.x, normal.y, normal.z);
  37485. uvs.push(col / precision.w, row / precision.h);
  37486. }
  37487. }
  37488. }
  37489. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37490. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37491. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37492. }
  37493. }
  37494. // Result
  37495. var vertexData = new VertexData();
  37496. vertexData.indices = indices;
  37497. vertexData.positions = positions;
  37498. vertexData.normals = normals;
  37499. vertexData.uvs = uvs;
  37500. return vertexData;
  37501. };
  37502. /**
  37503. * Creates the VertexData of the Ground designed from a heightmap
  37504. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37505. * * width the width (x direction) of the ground
  37506. * * height the height (z direction) of the ground
  37507. * * subdivisions the number of subdivisions per side
  37508. * * minHeight the minimum altitude on the ground, optional, default 0
  37509. * * maxHeight the maximum altitude on the ground, optional default 1
  37510. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37511. * * buffer the array holding the image color data
  37512. * * bufferWidth the width of image
  37513. * * bufferHeight the height of image
  37514. * @returns the VertexData of the Ground designed from a heightmap
  37515. */
  37516. VertexData.CreateGroundFromHeightMap = function (options) {
  37517. var indices = [];
  37518. var positions = [];
  37519. var normals = [];
  37520. var uvs = [];
  37521. var row, col;
  37522. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37523. // Vertices
  37524. for (row = 0; row <= options.subdivisions; row++) {
  37525. for (col = 0; col <= options.subdivisions; col++) {
  37526. 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));
  37527. // Compute height
  37528. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37529. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37530. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37531. var r = options.buffer[pos] / 255.0;
  37532. var g = options.buffer[pos + 1] / 255.0;
  37533. var b = options.buffer[pos + 2] / 255.0;
  37534. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37535. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37536. // Add vertex
  37537. positions.push(position.x, position.y, position.z);
  37538. normals.push(0, 0, 0);
  37539. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37540. }
  37541. }
  37542. // Indices
  37543. for (row = 0; row < options.subdivisions; row++) {
  37544. for (col = 0; col < options.subdivisions; col++) {
  37545. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37546. indices.push(col + 1 + row * (options.subdivisions + 1));
  37547. indices.push(col + row * (options.subdivisions + 1));
  37548. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37549. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37550. indices.push(col + row * (options.subdivisions + 1));
  37551. }
  37552. }
  37553. // Normals
  37554. VertexData.ComputeNormals(positions, indices, normals);
  37555. // Result
  37556. var vertexData = new VertexData();
  37557. vertexData.indices = indices;
  37558. vertexData.positions = positions;
  37559. vertexData.normals = normals;
  37560. vertexData.uvs = uvs;
  37561. return vertexData;
  37562. };
  37563. /**
  37564. * Creates the VertexData for a Plane
  37565. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37566. * * size sets the width and height of the plane to the value of size, optional default 1
  37567. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37568. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37569. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37570. * * 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)
  37571. * * 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)
  37572. * @returns the VertexData of the box
  37573. */
  37574. VertexData.CreatePlane = function (options) {
  37575. var indices = [];
  37576. var positions = [];
  37577. var normals = [];
  37578. var uvs = [];
  37579. var width = options.width || options.size || 1;
  37580. var height = options.height || options.size || 1;
  37581. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37582. // Vertices
  37583. var halfWidth = width / 2.0;
  37584. var halfHeight = height / 2.0;
  37585. positions.push(-halfWidth, -halfHeight, 0);
  37586. normals.push(0, 0, -1.0);
  37587. uvs.push(0.0, 0.0);
  37588. positions.push(halfWidth, -halfHeight, 0);
  37589. normals.push(0, 0, -1.0);
  37590. uvs.push(1.0, 0.0);
  37591. positions.push(halfWidth, halfHeight, 0);
  37592. normals.push(0, 0, -1.0);
  37593. uvs.push(1.0, 1.0);
  37594. positions.push(-halfWidth, halfHeight, 0);
  37595. normals.push(0, 0, -1.0);
  37596. uvs.push(0.0, 1.0);
  37597. // Indices
  37598. indices.push(0);
  37599. indices.push(1);
  37600. indices.push(2);
  37601. indices.push(0);
  37602. indices.push(2);
  37603. indices.push(3);
  37604. // Sides
  37605. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37606. // Result
  37607. var vertexData = new VertexData();
  37608. vertexData.indices = indices;
  37609. vertexData.positions = positions;
  37610. vertexData.normals = normals;
  37611. vertexData.uvs = uvs;
  37612. return vertexData;
  37613. };
  37614. /**
  37615. * Creates the VertexData of the Disc or regular Polygon
  37616. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37617. * * radius the radius of the disc, optional default 0.5
  37618. * * tessellation the number of polygon sides, optional, default 64
  37619. * * 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
  37620. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37621. * * 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)
  37622. * * 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)
  37623. * @returns the VertexData of the box
  37624. */
  37625. VertexData.CreateDisc = function (options) {
  37626. var positions = new Array();
  37627. var indices = new Array();
  37628. var normals = new Array();
  37629. var uvs = new Array();
  37630. var radius = options.radius || 0.5;
  37631. var tessellation = options.tessellation || 64;
  37632. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37633. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37634. // positions and uvs
  37635. positions.push(0, 0, 0); // disc center first
  37636. uvs.push(0.5, 0.5);
  37637. var theta = Math.PI * 2 * arc;
  37638. var step = theta / tessellation;
  37639. for (var a = 0; a < theta; a += step) {
  37640. var x = Math.cos(a);
  37641. var y = Math.sin(a);
  37642. var u = (x + 1) / 2;
  37643. var v = (1 - y) / 2;
  37644. positions.push(radius * x, radius * y, 0);
  37645. uvs.push(u, v);
  37646. }
  37647. if (arc === 1) {
  37648. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37649. uvs.push(uvs[2], uvs[3]);
  37650. }
  37651. //indices
  37652. var vertexNb = positions.length / 3;
  37653. for (var i = 1; i < vertexNb - 1; i++) {
  37654. indices.push(i + 1, 0, i);
  37655. }
  37656. // result
  37657. VertexData.ComputeNormals(positions, indices, normals);
  37658. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37659. var vertexData = new VertexData();
  37660. vertexData.indices = indices;
  37661. vertexData.positions = positions;
  37662. vertexData.normals = normals;
  37663. vertexData.uvs = uvs;
  37664. return vertexData;
  37665. };
  37666. /**
  37667. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37668. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37669. * @param polygon a mesh built from polygonTriangulation.build()
  37670. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37671. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37672. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37673. * @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)
  37674. * @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)
  37675. * @returns the VertexData of the Polygon
  37676. */
  37677. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37678. var faceUV = fUV || new Array(3);
  37679. var faceColors = fColors;
  37680. var colors = [];
  37681. // default face colors and UV if undefined
  37682. for (var f = 0; f < 3; f++) {
  37683. if (faceUV[f] === undefined) {
  37684. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37685. }
  37686. if (faceColors && faceColors[f] === undefined) {
  37687. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37688. }
  37689. }
  37690. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37691. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37692. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37693. var indices = polygon.getIndices();
  37694. // set face colours and textures
  37695. var idx = 0;
  37696. var face = 0;
  37697. for (var index = 0; index < normals.length; index += 3) {
  37698. //Edge Face no. 1
  37699. if (Math.abs(normals[index + 1]) < 0.001) {
  37700. face = 1;
  37701. }
  37702. //Top Face no. 0
  37703. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37704. face = 0;
  37705. }
  37706. //Bottom Face no. 2
  37707. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37708. face = 2;
  37709. }
  37710. idx = index / 3;
  37711. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37712. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37713. if (faceColors) {
  37714. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37715. }
  37716. }
  37717. // sides
  37718. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37719. // Result
  37720. var vertexData = new VertexData();
  37721. vertexData.indices = indices;
  37722. vertexData.positions = positions;
  37723. vertexData.normals = normals;
  37724. vertexData.uvs = uvs;
  37725. if (faceColors) {
  37726. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37727. vertexData.colors = totalColors;
  37728. }
  37729. return vertexData;
  37730. };
  37731. /**
  37732. * Creates the VertexData of the IcoSphere
  37733. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37734. * * radius the radius of the IcoSphere, optional default 1
  37735. * * radiusX allows stretching in the x direction, optional, default radius
  37736. * * radiusY allows stretching in the y direction, optional, default radius
  37737. * * radiusZ allows stretching in the z direction, optional, default radius
  37738. * * flat when true creates a flat shaded mesh, optional, default true
  37739. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37740. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37741. * * 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)
  37742. * * 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)
  37743. * @returns the VertexData of the IcoSphere
  37744. */
  37745. VertexData.CreateIcoSphere = function (options) {
  37746. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37747. var radius = options.radius || 1;
  37748. var flat = (options.flat === undefined) ? true : options.flat;
  37749. var subdivisions = options.subdivisions || 4;
  37750. var radiusX = options.radiusX || radius;
  37751. var radiusY = options.radiusY || radius;
  37752. var radiusZ = options.radiusZ || radius;
  37753. var t = (1 + Math.sqrt(5)) / 2;
  37754. // 12 vertex x,y,z
  37755. var ico_vertices = [
  37756. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37757. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37758. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37759. ];
  37760. // index of 3 vertex makes a face of icopshere
  37761. var ico_indices = [
  37762. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37763. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37764. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37765. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37766. ];
  37767. // vertex for uv have aliased position, not for UV
  37768. var vertices_unalias_id = [
  37769. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37770. // vertex alias
  37771. 0,
  37772. 2,
  37773. 3,
  37774. 3,
  37775. 3,
  37776. 4,
  37777. 7,
  37778. 8,
  37779. 9,
  37780. 9,
  37781. 10,
  37782. 11 // 23: B + 12
  37783. ];
  37784. // uv as integer step (not pixels !)
  37785. var ico_vertexuv = [
  37786. 5, 1, 3, 1, 6, 4, 0, 0,
  37787. 5, 3, 4, 2, 2, 2, 4, 0,
  37788. 2, 0, 1, 1, 6, 0, 6, 2,
  37789. // vertex alias (for same vertex on different faces)
  37790. 0, 4,
  37791. 3, 3,
  37792. 4, 4,
  37793. 3, 1,
  37794. 4, 2,
  37795. 4, 4,
  37796. 0, 2,
  37797. 1, 1,
  37798. 2, 2,
  37799. 3, 3,
  37800. 1, 3,
  37801. 2, 4 // 23: B + 12
  37802. ];
  37803. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37804. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37805. // First island of uv mapping
  37806. // v = 4h 3+ 2
  37807. // v = 3h 9+ 4
  37808. // v = 2h 9+ 5 B
  37809. // v = 1h 9 1 0
  37810. // v = 0h 3 8 7 A
  37811. // u = 0 1 2 3 4 5 6 *a
  37812. // Second island of uv mapping
  37813. // v = 4h 0+ B+ 4+
  37814. // v = 3h A+ 2+
  37815. // v = 2h 7+ 6 3+
  37816. // v = 1h 8+ 3+
  37817. // v = 0h
  37818. // u = 0 1 2 3 4 5 6 *a
  37819. // Face layout on texture UV mapping
  37820. // ============
  37821. // \ 4 /\ 16 / ======
  37822. // \ / \ / /\ 11 /
  37823. // \/ 7 \/ / \ /
  37824. // ======= / 10 \/
  37825. // /\ 17 /\ =======
  37826. // / \ / \ \ 15 /\
  37827. // / 8 \/ 12 \ \ / \
  37828. // ============ \/ 6 \
  37829. // \ 18 /\ ============
  37830. // \ / \ \ 5 /\ 0 /
  37831. // \/ 13 \ \ / \ /
  37832. // ======= \/ 1 \/
  37833. // =============
  37834. // /\ 19 /\ 2 /\
  37835. // / \ / \ / \
  37836. // / 14 \/ 9 \/ 3 \
  37837. // ===================
  37838. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37839. var ustep = 138 / 1024;
  37840. var vstep = 239 / 1024;
  37841. var uoffset = 60 / 1024;
  37842. var voffset = 26 / 1024;
  37843. // Second island should have margin, not to touch the first island
  37844. // avoid any borderline artefact in pixel rounding
  37845. var island_u_offset = -40 / 1024;
  37846. var island_v_offset = +20 / 1024;
  37847. // face is either island 0 or 1 :
  37848. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37849. var island = [
  37850. 0, 0, 0, 0, 1,
  37851. 0, 0, 1, 1, 0,
  37852. 0, 0, 1, 1, 0,
  37853. 0, 1, 1, 1, 0 // 15 - 19
  37854. ];
  37855. var indices = new Array();
  37856. var positions = new Array();
  37857. var normals = new Array();
  37858. var uvs = new Array();
  37859. var current_indice = 0;
  37860. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37861. var face_vertex_pos = new Array(3);
  37862. var face_vertex_uv = new Array(3);
  37863. var v012;
  37864. for (v012 = 0; v012 < 3; v012++) {
  37865. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37866. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37867. }
  37868. // create all with normals
  37869. for (var face = 0; face < 20; face++) {
  37870. // 3 vertex per face
  37871. for (v012 = 0; v012 < 3; v012++) {
  37872. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37873. var v_id = ico_indices[3 * face + v012];
  37874. // vertex have 3D position (x,y,z)
  37875. 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]);
  37876. // Normalize to get normal, then scale to radius
  37877. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37878. // uv Coordinates from vertex ID
  37879. 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);
  37880. }
  37881. // Subdivide the face (interpolate pos, norm, uv)
  37882. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37883. // - norm is linear interpolation of vertex corner normal
  37884. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37885. // - uv is linear interpolation
  37886. //
  37887. // Topology is as below for sub-divide by 2
  37888. // vertex shown as v0,v1,v2
  37889. // interp index is i1 to progress in range [v0,v1[
  37890. // interp index is i2 to progress in range [v0,v2[
  37891. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37892. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37893. //
  37894. //
  37895. // i2 v2
  37896. // ^ ^
  37897. // / / \
  37898. // / / \
  37899. // / / \
  37900. // / / (0,1) \
  37901. // / #---------\
  37902. // / / \ (0,0)'/ \
  37903. // / / \ / \
  37904. // / / \ / \
  37905. // / / (0,0) \ / (1,0) \
  37906. // / #---------#---------\
  37907. // v0 v1
  37908. //
  37909. // --------------------> i1
  37910. //
  37911. // interp of (i1,i2):
  37912. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37913. // along i1 : lerp(x0,x1, i1/(S-i2))
  37914. //
  37915. // centroid of triangle is needed to get help normal computation
  37916. // (c1,c2) are used for centroid location
  37917. var interp_vertex = function (i1, i2, c1, c2) {
  37918. // vertex is interpolated from
  37919. // - face_vertex_pos[0..2]
  37920. // - face_vertex_uv[0..2]
  37921. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37922. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37923. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37924. pos_interp.normalize();
  37925. var vertex_normal;
  37926. if (flat) {
  37927. // in flat mode, recalculate normal as face centroid normal
  37928. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37929. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37930. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37931. }
  37932. else {
  37933. // in smooth mode, recalculate normal from each single vertex position
  37934. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37935. }
  37936. // Vertex normal need correction due to X,Y,Z radius scaling
  37937. vertex_normal.x /= radiusX;
  37938. vertex_normal.y /= radiusY;
  37939. vertex_normal.z /= radiusZ;
  37940. vertex_normal.normalize();
  37941. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37942. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37943. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37944. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37945. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37946. uvs.push(uv_interp.x, uv_interp.y);
  37947. // push each vertex has member of a face
  37948. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37949. indices.push(current_indice);
  37950. current_indice++;
  37951. };
  37952. for (var i2 = 0; i2 < subdivisions; i2++) {
  37953. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37954. // face : (i1,i2) for /\ :
  37955. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37956. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37957. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37958. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37959. if (i1 + i2 + 1 < subdivisions) {
  37960. // face : (i1,i2)' for \/ :
  37961. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37962. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37963. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37964. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37965. }
  37966. }
  37967. }
  37968. }
  37969. // Sides
  37970. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37971. // Result
  37972. var vertexData = new VertexData();
  37973. vertexData.indices = indices;
  37974. vertexData.positions = positions;
  37975. vertexData.normals = normals;
  37976. vertexData.uvs = uvs;
  37977. return vertexData;
  37978. };
  37979. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37980. /**
  37981. * Creates the VertexData for a Polyhedron
  37982. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37983. * * type provided types are:
  37984. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37985. * * 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)
  37986. * * size the size of the IcoSphere, optional default 1
  37987. * * sizeX allows stretching in the x direction, optional, default size
  37988. * * sizeY allows stretching in the y direction, optional, default size
  37989. * * sizeZ allows stretching in the z direction, optional, default size
  37990. * * 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
  37991. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37992. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37993. * * flat when true creates a flat shaded mesh, optional, default true
  37994. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37995. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37996. * * 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)
  37997. * * 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)
  37998. * @returns the VertexData of the Polyhedron
  37999. */
  38000. VertexData.CreatePolyhedron = function (options) {
  38001. // provided polyhedron types :
  38002. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38003. // 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)
  38004. var polyhedra = [];
  38005. 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]] };
  38006. 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]] };
  38007. polyhedra[2] = {
  38008. 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]],
  38009. 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]]
  38010. };
  38011. polyhedra[3] = {
  38012. 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]],
  38013. 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]]
  38014. };
  38015. polyhedra[4] = {
  38016. 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]],
  38017. 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]]
  38018. };
  38019. 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]] };
  38020. 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]] };
  38021. 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]] };
  38022. 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]] };
  38023. 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]] };
  38024. 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]] };
  38025. 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]] };
  38026. 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]] };
  38027. 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]] };
  38028. polyhedra[14] = {
  38029. 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]],
  38030. 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]]
  38031. };
  38032. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38033. var size = options.size;
  38034. var sizeX = options.sizeX || size || 1;
  38035. var sizeY = options.sizeY || size || 1;
  38036. var sizeZ = options.sizeZ || size || 1;
  38037. var data = options.custom || polyhedra[type];
  38038. var nbfaces = data.face.length;
  38039. var faceUV = options.faceUV || new Array(nbfaces);
  38040. var faceColors = options.faceColors;
  38041. var flat = (options.flat === undefined) ? true : options.flat;
  38042. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38043. var positions = new Array();
  38044. var indices = new Array();
  38045. var normals = new Array();
  38046. var uvs = new Array();
  38047. var colors = new Array();
  38048. var index = 0;
  38049. var faceIdx = 0; // face cursor in the array "indexes"
  38050. var indexes = new Array();
  38051. var i = 0;
  38052. var f = 0;
  38053. var u, v, ang, x, y, tmp;
  38054. // default face colors and UV if undefined
  38055. if (flat) {
  38056. for (f = 0; f < nbfaces; f++) {
  38057. if (faceColors && faceColors[f] === undefined) {
  38058. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38059. }
  38060. if (faceUV && faceUV[f] === undefined) {
  38061. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38062. }
  38063. }
  38064. }
  38065. if (!flat) {
  38066. for (i = 0; i < data.vertex.length; i++) {
  38067. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38068. uvs.push(0, 0);
  38069. }
  38070. for (f = 0; f < nbfaces; f++) {
  38071. for (i = 0; i < data.face[f].length - 2; i++) {
  38072. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38073. }
  38074. }
  38075. }
  38076. else {
  38077. for (f = 0; f < nbfaces; f++) {
  38078. var fl = data.face[f].length; // number of vertices of the current face
  38079. ang = 2 * Math.PI / fl;
  38080. x = 0.5 * Math.tan(ang / 2);
  38081. y = 0.5;
  38082. // positions, uvs, colors
  38083. for (i = 0; i < fl; i++) {
  38084. // positions
  38085. 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);
  38086. indexes.push(index);
  38087. index++;
  38088. // uvs
  38089. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38090. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38091. uvs.push(u, v);
  38092. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38093. y = x * Math.sin(ang) + y * Math.cos(ang);
  38094. x = tmp;
  38095. // colors
  38096. if (faceColors) {
  38097. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38098. }
  38099. }
  38100. // indices from indexes
  38101. for (i = 0; i < fl - 2; i++) {
  38102. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38103. }
  38104. faceIdx += fl;
  38105. }
  38106. }
  38107. VertexData.ComputeNormals(positions, indices, normals);
  38108. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38109. var vertexData = new VertexData();
  38110. vertexData.positions = positions;
  38111. vertexData.indices = indices;
  38112. vertexData.normals = normals;
  38113. vertexData.uvs = uvs;
  38114. if (faceColors && flat) {
  38115. vertexData.colors = colors;
  38116. }
  38117. return vertexData;
  38118. };
  38119. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38120. /**
  38121. * Creates the VertexData for a TorusKnot
  38122. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38123. * * radius the radius of the torus knot, optional, default 2
  38124. * * tube the thickness of the tube, optional, default 0.5
  38125. * * radialSegments the number of sides on each tube segments, optional, default 32
  38126. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38127. * * p the number of windings around the z axis, optional, default 2
  38128. * * q the number of windings around the x axis, optional, default 3
  38129. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38130. * * 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)
  38131. * * 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)
  38132. * @returns the VertexData of the Torus Knot
  38133. */
  38134. VertexData.CreateTorusKnot = function (options) {
  38135. var indices = new Array();
  38136. var positions = new Array();
  38137. var normals = new Array();
  38138. var uvs = new Array();
  38139. var radius = options.radius || 2;
  38140. var tube = options.tube || 0.5;
  38141. var radialSegments = options.radialSegments || 32;
  38142. var tubularSegments = options.tubularSegments || 32;
  38143. var p = options.p || 2;
  38144. var q = options.q || 3;
  38145. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38146. // Helper
  38147. var getPos = function (angle) {
  38148. var cu = Math.cos(angle);
  38149. var su = Math.sin(angle);
  38150. var quOverP = q / p * angle;
  38151. var cs = Math.cos(quOverP);
  38152. var tx = radius * (2 + cs) * 0.5 * cu;
  38153. var ty = radius * (2 + cs) * su * 0.5;
  38154. var tz = radius * Math.sin(quOverP) * 0.5;
  38155. return new BABYLON.Vector3(tx, ty, tz);
  38156. };
  38157. // Vertices
  38158. var i;
  38159. var j;
  38160. for (i = 0; i <= radialSegments; i++) {
  38161. var modI = i % radialSegments;
  38162. var u = modI / radialSegments * 2 * p * Math.PI;
  38163. var p1 = getPos(u);
  38164. var p2 = getPos(u + 0.01);
  38165. var tang = p2.subtract(p1);
  38166. var n = p2.add(p1);
  38167. var bitan = BABYLON.Vector3.Cross(tang, n);
  38168. n = BABYLON.Vector3.Cross(bitan, tang);
  38169. bitan.normalize();
  38170. n.normalize();
  38171. for (j = 0; j < tubularSegments; j++) {
  38172. var modJ = j % tubularSegments;
  38173. var v = modJ / tubularSegments * 2 * Math.PI;
  38174. var cx = -tube * Math.cos(v);
  38175. var cy = tube * Math.sin(v);
  38176. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38177. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38178. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38179. uvs.push(i / radialSegments);
  38180. uvs.push(j / tubularSegments);
  38181. }
  38182. }
  38183. for (i = 0; i < radialSegments; i++) {
  38184. for (j = 0; j < tubularSegments; j++) {
  38185. var jNext = (j + 1) % tubularSegments;
  38186. var a = i * tubularSegments + j;
  38187. var b = (i + 1) * tubularSegments + j;
  38188. var c = (i + 1) * tubularSegments + jNext;
  38189. var d = i * tubularSegments + jNext;
  38190. indices.push(d);
  38191. indices.push(b);
  38192. indices.push(a);
  38193. indices.push(d);
  38194. indices.push(c);
  38195. indices.push(b);
  38196. }
  38197. }
  38198. // Normals
  38199. VertexData.ComputeNormals(positions, indices, normals);
  38200. // Sides
  38201. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38202. // Result
  38203. var vertexData = new VertexData();
  38204. vertexData.indices = indices;
  38205. vertexData.positions = positions;
  38206. vertexData.normals = normals;
  38207. vertexData.uvs = uvs;
  38208. return vertexData;
  38209. };
  38210. // Tools
  38211. /**
  38212. * Compute normals for given positions and indices
  38213. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38214. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38215. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38216. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38217. * * facetNormals : optional array of facet normals (vector3)
  38218. * * facetPositions : optional array of facet positions (vector3)
  38219. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38220. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38221. * * bInfo : optional bounding info, required for facetPartitioning computation
  38222. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38223. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38224. * * useRightHandedSystem: optional boolean to for right handed system computation
  38225. * * depthSort : optional boolean to enable the facet depth sort computation
  38226. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38227. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38228. */
  38229. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38230. // temporary scalar variables
  38231. var index = 0; // facet index
  38232. var p1p2x = 0.0; // p1p2 vector x coordinate
  38233. var p1p2y = 0.0; // p1p2 vector y coordinate
  38234. var p1p2z = 0.0; // p1p2 vector z coordinate
  38235. var p3p2x = 0.0; // p3p2 vector x coordinate
  38236. var p3p2y = 0.0; // p3p2 vector y coordinate
  38237. var p3p2z = 0.0; // p3p2 vector z coordinate
  38238. var faceNormalx = 0.0; // facet normal x coordinate
  38239. var faceNormaly = 0.0; // facet normal y coordinate
  38240. var faceNormalz = 0.0; // facet normal z coordinate
  38241. var length = 0.0; // facet normal length before normalization
  38242. var v1x = 0; // vector1 x index in the positions array
  38243. var v1y = 0; // vector1 y index in the positions array
  38244. var v1z = 0; // vector1 z index in the positions array
  38245. var v2x = 0; // vector2 x index in the positions array
  38246. var v2y = 0; // vector2 y index in the positions array
  38247. var v2z = 0; // vector2 z index in the positions array
  38248. var v3x = 0; // vector3 x index in the positions array
  38249. var v3y = 0; // vector3 y index in the positions array
  38250. var v3z = 0; // vector3 z index in the positions array
  38251. var computeFacetNormals = false;
  38252. var computeFacetPositions = false;
  38253. var computeFacetPartitioning = false;
  38254. var computeDepthSort = false;
  38255. var faceNormalSign = 1;
  38256. var ratio = 0;
  38257. var distanceTo = null;
  38258. if (options) {
  38259. computeFacetNormals = (options.facetNormals) ? true : false;
  38260. computeFacetPositions = (options.facetPositions) ? true : false;
  38261. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38262. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38263. ratio = options.ratio || 0;
  38264. computeDepthSort = (options.depthSort) ? true : false;
  38265. distanceTo = (options.distanceTo);
  38266. if (computeDepthSort) {
  38267. if (distanceTo === undefined) {
  38268. distanceTo = BABYLON.Vector3.Zero();
  38269. }
  38270. var depthSortedFacets = options.depthSortedFacets;
  38271. }
  38272. }
  38273. // facetPartitioning reinit if needed
  38274. var xSubRatio = 0;
  38275. var ySubRatio = 0;
  38276. var zSubRatio = 0;
  38277. var subSq = 0;
  38278. if (computeFacetPartitioning && options && options.bbSize) {
  38279. var ox = 0; // X partitioning index for facet position
  38280. var oy = 0; // Y partinioning index for facet position
  38281. var oz = 0; // Z partinioning index for facet position
  38282. var b1x = 0; // X partitioning index for facet v1 vertex
  38283. var b1y = 0; // Y partitioning index for facet v1 vertex
  38284. var b1z = 0; // z partitioning index for facet v1 vertex
  38285. var b2x = 0; // X partitioning index for facet v2 vertex
  38286. var b2y = 0; // Y partitioning index for facet v2 vertex
  38287. var b2z = 0; // Z partitioning index for facet v2 vertex
  38288. var b3x = 0; // X partitioning index for facet v3 vertex
  38289. var b3y = 0; // Y partitioning index for facet v3 vertex
  38290. var b3z = 0; // Z partitioning index for facet v3 vertex
  38291. var block_idx_o = 0; // facet barycenter block index
  38292. var block_idx_v1 = 0; // v1 vertex block index
  38293. var block_idx_v2 = 0; // v2 vertex block index
  38294. var block_idx_v3 = 0; // v3 vertex block index
  38295. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38296. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38297. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38298. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38299. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38300. subSq = options.subDiv.max * options.subDiv.max;
  38301. options.facetPartitioning.length = 0;
  38302. }
  38303. // reset the normals
  38304. for (index = 0; index < positions.length; index++) {
  38305. normals[index] = 0.0;
  38306. }
  38307. // Loop : 1 indice triplet = 1 facet
  38308. var nbFaces = (indices.length / 3) | 0;
  38309. for (index = 0; index < nbFaces; index++) {
  38310. // get the indexes of the coordinates of each vertex of the facet
  38311. v1x = indices[index * 3] * 3;
  38312. v1y = v1x + 1;
  38313. v1z = v1x + 2;
  38314. v2x = indices[index * 3 + 1] * 3;
  38315. v2y = v2x + 1;
  38316. v2z = v2x + 2;
  38317. v3x = indices[index * 3 + 2] * 3;
  38318. v3y = v3x + 1;
  38319. v3z = v3x + 2;
  38320. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38321. p1p2y = positions[v1y] - positions[v2y];
  38322. p1p2z = positions[v1z] - positions[v2z];
  38323. p3p2x = positions[v3x] - positions[v2x];
  38324. p3p2y = positions[v3y] - positions[v2y];
  38325. p3p2z = positions[v3z] - positions[v2z];
  38326. // compute the face normal with the cross product
  38327. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38328. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38329. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38330. // normalize this normal and store it in the array facetData
  38331. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38332. length = (length === 0) ? 1.0 : length;
  38333. faceNormalx /= length;
  38334. faceNormaly /= length;
  38335. faceNormalz /= length;
  38336. if (computeFacetNormals && options) {
  38337. options.facetNormals[index].x = faceNormalx;
  38338. options.facetNormals[index].y = faceNormaly;
  38339. options.facetNormals[index].z = faceNormalz;
  38340. }
  38341. if (computeFacetPositions && options) {
  38342. // compute and the facet barycenter coordinates in the array facetPositions
  38343. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38344. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38345. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38346. }
  38347. if (computeFacetPartitioning && options) {
  38348. // store the facet indexes in arrays in the main facetPartitioning array :
  38349. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38350. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38351. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38352. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38353. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38354. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38355. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38356. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38357. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38358. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38359. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38360. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38361. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38362. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38363. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38364. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38365. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38366. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38367. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38368. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38369. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38370. // push each facet index in each block containing the vertex
  38371. options.facetPartitioning[block_idx_v1].push(index);
  38372. if (block_idx_v2 != block_idx_v1) {
  38373. options.facetPartitioning[block_idx_v2].push(index);
  38374. }
  38375. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38376. options.facetPartitioning[block_idx_v3].push(index);
  38377. }
  38378. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38379. options.facetPartitioning[block_idx_o].push(index);
  38380. }
  38381. }
  38382. if (computeDepthSort && options && options.facetPositions) {
  38383. var dsf = depthSortedFacets[index];
  38384. dsf.ind = index * 3;
  38385. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38386. }
  38387. // compute the normals anyway
  38388. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38389. normals[v1y] += faceNormaly;
  38390. normals[v1z] += faceNormalz;
  38391. normals[v2x] += faceNormalx;
  38392. normals[v2y] += faceNormaly;
  38393. normals[v2z] += faceNormalz;
  38394. normals[v3x] += faceNormalx;
  38395. normals[v3y] += faceNormaly;
  38396. normals[v3z] += faceNormalz;
  38397. }
  38398. // last normalization of each normal
  38399. for (index = 0; index < normals.length / 3; index++) {
  38400. faceNormalx = normals[index * 3];
  38401. faceNormaly = normals[index * 3 + 1];
  38402. faceNormalz = normals[index * 3 + 2];
  38403. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38404. length = (length === 0) ? 1.0 : length;
  38405. faceNormalx /= length;
  38406. faceNormaly /= length;
  38407. faceNormalz /= length;
  38408. normals[index * 3] = faceNormalx;
  38409. normals[index * 3 + 1] = faceNormaly;
  38410. normals[index * 3 + 2] = faceNormalz;
  38411. }
  38412. };
  38413. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38414. var li = indices.length;
  38415. var ln = normals.length;
  38416. var i;
  38417. var n;
  38418. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38419. switch (sideOrientation) {
  38420. case BABYLON.Mesh.FRONTSIDE:
  38421. // nothing changed
  38422. break;
  38423. case BABYLON.Mesh.BACKSIDE:
  38424. var tmp;
  38425. // indices
  38426. for (i = 0; i < li; i += 3) {
  38427. tmp = indices[i];
  38428. indices[i] = indices[i + 2];
  38429. indices[i + 2] = tmp;
  38430. }
  38431. // normals
  38432. for (n = 0; n < ln; n++) {
  38433. normals[n] = -normals[n];
  38434. }
  38435. break;
  38436. case BABYLON.Mesh.DOUBLESIDE:
  38437. // positions
  38438. var lp = positions.length;
  38439. var l = lp / 3;
  38440. for (var p = 0; p < lp; p++) {
  38441. positions[lp + p] = positions[p];
  38442. }
  38443. // indices
  38444. for (i = 0; i < li; i += 3) {
  38445. indices[i + li] = indices[i + 2] + l;
  38446. indices[i + 1 + li] = indices[i + 1] + l;
  38447. indices[i + 2 + li] = indices[i] + l;
  38448. }
  38449. // normals
  38450. for (n = 0; n < ln; n++) {
  38451. normals[ln + n] = -normals[n];
  38452. }
  38453. // uvs
  38454. var lu = uvs.length;
  38455. var u = 0;
  38456. for (u = 0; u < lu; u++) {
  38457. uvs[u + lu] = uvs[u];
  38458. }
  38459. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38460. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38461. u = 0;
  38462. for (i = 0; i < lu / 2; i++) {
  38463. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38464. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38465. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38466. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38467. u += 2;
  38468. }
  38469. break;
  38470. }
  38471. };
  38472. /**
  38473. * Applies VertexData created from the imported parameters to the geometry
  38474. * @param parsedVertexData the parsed data from an imported file
  38475. * @param geometry the geometry to apply the VertexData to
  38476. */
  38477. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38478. var vertexData = new VertexData();
  38479. // positions
  38480. var positions = parsedVertexData.positions;
  38481. if (positions) {
  38482. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38483. }
  38484. // normals
  38485. var normals = parsedVertexData.normals;
  38486. if (normals) {
  38487. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38488. }
  38489. // tangents
  38490. var tangents = parsedVertexData.tangents;
  38491. if (tangents) {
  38492. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38493. }
  38494. // uvs
  38495. var uvs = parsedVertexData.uvs;
  38496. if (uvs) {
  38497. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38498. }
  38499. // uv2s
  38500. var uv2s = parsedVertexData.uv2s;
  38501. if (uv2s) {
  38502. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38503. }
  38504. // uv3s
  38505. var uv3s = parsedVertexData.uv3s;
  38506. if (uv3s) {
  38507. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38508. }
  38509. // uv4s
  38510. var uv4s = parsedVertexData.uv4s;
  38511. if (uv4s) {
  38512. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38513. }
  38514. // uv5s
  38515. var uv5s = parsedVertexData.uv5s;
  38516. if (uv5s) {
  38517. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38518. }
  38519. // uv6s
  38520. var uv6s = parsedVertexData.uv6s;
  38521. if (uv6s) {
  38522. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38523. }
  38524. // colors
  38525. var colors = parsedVertexData.colors;
  38526. if (colors) {
  38527. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38528. }
  38529. // matricesIndices
  38530. var matricesIndices = parsedVertexData.matricesIndices;
  38531. if (matricesIndices) {
  38532. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38533. }
  38534. // matricesWeights
  38535. var matricesWeights = parsedVertexData.matricesWeights;
  38536. if (matricesWeights) {
  38537. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38538. }
  38539. // indices
  38540. var indices = parsedVertexData.indices;
  38541. if (indices) {
  38542. vertexData.indices = indices;
  38543. }
  38544. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38545. };
  38546. return VertexData;
  38547. }());
  38548. BABYLON.VertexData = VertexData;
  38549. })(BABYLON || (BABYLON = {}));
  38550. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38551. var BABYLON;
  38552. (function (BABYLON) {
  38553. /**
  38554. * Class used to store geometry data (vertex buffers + index buffer)
  38555. */
  38556. var Geometry = /** @class */ (function () {
  38557. /**
  38558. * Creates a new geometry
  38559. * @param id defines the unique ID
  38560. * @param scene defines the hosting scene
  38561. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38562. * @param updatable defines if geometry must be updatable (false by default)
  38563. * @param mesh defines the mesh that will be associated with the geometry
  38564. */
  38565. function Geometry(id, scene, vertexData, updatable, mesh) {
  38566. if (updatable === void 0) { updatable = false; }
  38567. if (mesh === void 0) { mesh = null; }
  38568. /**
  38569. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38570. */
  38571. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38572. this._totalVertices = 0;
  38573. this._isDisposed = false;
  38574. this._indexBufferIsUpdatable = false;
  38575. this.id = id;
  38576. this._engine = scene.getEngine();
  38577. this._meshes = [];
  38578. this._scene = scene;
  38579. //Init vertex buffer cache
  38580. this._vertexBuffers = {};
  38581. this._indices = [];
  38582. this._updatable = updatable;
  38583. // vertexData
  38584. if (vertexData) {
  38585. this.setAllVerticesData(vertexData, updatable);
  38586. }
  38587. else {
  38588. this._totalVertices = 0;
  38589. this._indices = [];
  38590. }
  38591. if (this._engine.getCaps().vertexArrayObject) {
  38592. this._vertexArrayObjects = {};
  38593. }
  38594. // applyToMesh
  38595. if (mesh) {
  38596. if (mesh.getClassName() === "LinesMesh") {
  38597. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38598. this._updateExtend();
  38599. }
  38600. this.applyToMesh(mesh);
  38601. mesh.computeWorldMatrix(true);
  38602. }
  38603. }
  38604. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38605. /**
  38606. * 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
  38607. */
  38608. get: function () {
  38609. return this._boundingBias;
  38610. },
  38611. /**
  38612. * 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
  38613. */
  38614. set: function (value) {
  38615. if (this._boundingBias && this._boundingBias.equals(value)) {
  38616. return;
  38617. }
  38618. this._boundingBias = value.clone();
  38619. this._updateBoundingInfo(true, null);
  38620. },
  38621. enumerable: true,
  38622. configurable: true
  38623. });
  38624. /**
  38625. * Static function used to attach a new empty geometry to a mesh
  38626. * @param mesh defines the mesh to attach the geometry to
  38627. * @returns the new {BABYLON.Geometry}
  38628. */
  38629. Geometry.CreateGeometryForMesh = function (mesh) {
  38630. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38631. geometry.applyToMesh(mesh);
  38632. return geometry;
  38633. };
  38634. Object.defineProperty(Geometry.prototype, "extend", {
  38635. /**
  38636. * Gets the current extend of the geometry
  38637. */
  38638. get: function () {
  38639. return this._extend;
  38640. },
  38641. enumerable: true,
  38642. configurable: true
  38643. });
  38644. /**
  38645. * Gets the hosting scene
  38646. * @returns the hosting {BABYLON.Scene}
  38647. */
  38648. Geometry.prototype.getScene = function () {
  38649. return this._scene;
  38650. };
  38651. /**
  38652. * Gets the hosting engine
  38653. * @returns the hosting {BABYLON.Engine}
  38654. */
  38655. Geometry.prototype.getEngine = function () {
  38656. return this._engine;
  38657. };
  38658. /**
  38659. * Defines if the geometry is ready to use
  38660. * @returns true if the geometry is ready to be used
  38661. */
  38662. Geometry.prototype.isReady = function () {
  38663. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38664. };
  38665. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38666. /**
  38667. * Gets a value indicating that the geometry should not be serialized
  38668. */
  38669. get: function () {
  38670. for (var index = 0; index < this._meshes.length; index++) {
  38671. if (!this._meshes[index].doNotSerialize) {
  38672. return false;
  38673. }
  38674. }
  38675. return true;
  38676. },
  38677. enumerable: true,
  38678. configurable: true
  38679. });
  38680. /** @hidden */
  38681. Geometry.prototype._rebuild = function () {
  38682. if (this._vertexArrayObjects) {
  38683. this._vertexArrayObjects = {};
  38684. }
  38685. // Index buffer
  38686. if (this._meshes.length !== 0 && this._indices) {
  38687. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38688. }
  38689. // Vertex buffers
  38690. for (var key in this._vertexBuffers) {
  38691. var vertexBuffer = this._vertexBuffers[key];
  38692. vertexBuffer._rebuild();
  38693. }
  38694. };
  38695. /**
  38696. * Affects all geometry data in one call
  38697. * @param vertexData defines the geometry data
  38698. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38699. */
  38700. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38701. vertexData.applyToGeometry(this, updatable);
  38702. this.notifyUpdate();
  38703. };
  38704. /**
  38705. * Set specific vertex data
  38706. * @param kind defines the data kind (Position, normal, etc...)
  38707. * @param data defines the vertex data to use
  38708. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38709. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38710. */
  38711. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38712. if (updatable === void 0) { updatable = false; }
  38713. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38714. this.setVerticesBuffer(buffer);
  38715. };
  38716. /**
  38717. * Removes a specific vertex data
  38718. * @param kind defines the data kind (Position, normal, etc...)
  38719. */
  38720. Geometry.prototype.removeVerticesData = function (kind) {
  38721. if (this._vertexBuffers[kind]) {
  38722. this._vertexBuffers[kind].dispose();
  38723. delete this._vertexBuffers[kind];
  38724. }
  38725. };
  38726. /**
  38727. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38728. * @param buffer defines the vertex buffer to use
  38729. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38730. */
  38731. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38732. if (totalVertices === void 0) { totalVertices = null; }
  38733. var kind = buffer.getKind();
  38734. if (this._vertexBuffers[kind]) {
  38735. this._vertexBuffers[kind].dispose();
  38736. }
  38737. this._vertexBuffers[kind] = buffer;
  38738. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38739. var data = buffer.getData();
  38740. if (totalVertices != null) {
  38741. this._totalVertices = totalVertices;
  38742. }
  38743. else {
  38744. if (data != null) {
  38745. this._totalVertices = data.length / (buffer.byteStride / 4);
  38746. }
  38747. }
  38748. this._updateExtend(data);
  38749. this._resetPointsArrayCache();
  38750. var meshes = this._meshes;
  38751. var numOfMeshes = meshes.length;
  38752. for (var index = 0; index < numOfMeshes; index++) {
  38753. var mesh = meshes[index];
  38754. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38755. mesh._createGlobalSubMesh(false);
  38756. mesh.computeWorldMatrix(true);
  38757. }
  38758. }
  38759. this.notifyUpdate(kind);
  38760. if (this._vertexArrayObjects) {
  38761. this._disposeVertexArrayObjects();
  38762. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38763. }
  38764. };
  38765. /**
  38766. * Update a specific vertex buffer
  38767. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38768. * It will do nothing if the buffer is not updatable
  38769. * @param kind defines the data kind (Position, normal, etc...)
  38770. * @param data defines the data to use
  38771. * @param offset defines the offset in the target buffer where to store the data
  38772. * @param useBytes set to true if the offset is in bytes
  38773. */
  38774. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38775. if (useBytes === void 0) { useBytes = false; }
  38776. var vertexBuffer = this.getVertexBuffer(kind);
  38777. if (!vertexBuffer) {
  38778. return;
  38779. }
  38780. vertexBuffer.updateDirectly(data, offset, useBytes);
  38781. this.notifyUpdate(kind);
  38782. };
  38783. /**
  38784. * Update a specific vertex buffer
  38785. * This function will create a new buffer if the current one is not updatable
  38786. * @param kind defines the data kind (Position, normal, etc...)
  38787. * @param data defines the data to use
  38788. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38789. */
  38790. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38791. if (updateExtends === void 0) { updateExtends = false; }
  38792. var vertexBuffer = this.getVertexBuffer(kind);
  38793. if (!vertexBuffer) {
  38794. return;
  38795. }
  38796. vertexBuffer.update(data);
  38797. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38798. this._updateBoundingInfo(updateExtends, data);
  38799. }
  38800. this.notifyUpdate(kind);
  38801. };
  38802. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38803. if (updateExtends) {
  38804. this._updateExtend(data);
  38805. }
  38806. var meshes = this._meshes;
  38807. var numOfMeshes = meshes.length;
  38808. this._resetPointsArrayCache();
  38809. for (var index = 0; index < numOfMeshes; index++) {
  38810. var mesh = meshes[index];
  38811. if (updateExtends) {
  38812. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38813. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38814. var subMesh = mesh.subMeshes[subIndex];
  38815. subMesh.refreshBoundingInfo();
  38816. }
  38817. }
  38818. }
  38819. };
  38820. /** @hidden */
  38821. Geometry.prototype._bind = function (effect, indexToBind) {
  38822. if (!effect) {
  38823. return;
  38824. }
  38825. if (indexToBind === undefined) {
  38826. indexToBind = this._indexBuffer;
  38827. }
  38828. var vbs = this.getVertexBuffers();
  38829. if (!vbs) {
  38830. return;
  38831. }
  38832. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38833. this._engine.bindBuffers(vbs, indexToBind, effect);
  38834. return;
  38835. }
  38836. // Using VAO
  38837. if (!this._vertexArrayObjects[effect.key]) {
  38838. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38839. }
  38840. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38841. };
  38842. /**
  38843. * Gets total number of vertices
  38844. * @returns the total number of vertices
  38845. */
  38846. Geometry.prototype.getTotalVertices = function () {
  38847. if (!this.isReady()) {
  38848. return 0;
  38849. }
  38850. return this._totalVertices;
  38851. };
  38852. /**
  38853. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38854. * @param kind defines the data kind (Position, normal, etc...)
  38855. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38856. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38857. * @returns a float array containing vertex data
  38858. */
  38859. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38860. var vertexBuffer = this.getVertexBuffer(kind);
  38861. if (!vertexBuffer) {
  38862. return null;
  38863. }
  38864. var data = vertexBuffer.getData();
  38865. if (!data) {
  38866. return null;
  38867. }
  38868. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38869. var count = this._totalVertices * vertexBuffer.getSize();
  38870. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38871. var copy_1 = new Array(count);
  38872. vertexBuffer.forEach(count, function (value, index) {
  38873. copy_1[index] = value;
  38874. });
  38875. return copy_1;
  38876. }
  38877. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38878. if (data instanceof Array) {
  38879. var offset = vertexBuffer.byteOffset / 4;
  38880. return BABYLON.Tools.Slice(data, offset, offset + count);
  38881. }
  38882. else if (data instanceof ArrayBuffer) {
  38883. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38884. }
  38885. else {
  38886. var offset = data.byteOffset + vertexBuffer.byteOffset;
  38887. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38888. var result = new Float32Array(count);
  38889. var source = new Float32Array(data.buffer, offset, count);
  38890. result.set(source);
  38891. return result;
  38892. }
  38893. return new Float32Array(data.buffer, offset, count);
  38894. }
  38895. }
  38896. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38897. return BABYLON.Tools.Slice(data);
  38898. }
  38899. return data;
  38900. };
  38901. /**
  38902. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38903. * @param kind defines the data kind (Position, normal, etc...)
  38904. * @returns true if the vertex buffer with the specified kind is updatable
  38905. */
  38906. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38907. var vb = this._vertexBuffers[kind];
  38908. if (!vb) {
  38909. return false;
  38910. }
  38911. return vb.isUpdatable();
  38912. };
  38913. /**
  38914. * Gets a specific vertex buffer
  38915. * @param kind defines the data kind (Position, normal, etc...)
  38916. * @returns a {BABYLON.VertexBuffer}
  38917. */
  38918. Geometry.prototype.getVertexBuffer = function (kind) {
  38919. if (!this.isReady()) {
  38920. return null;
  38921. }
  38922. return this._vertexBuffers[kind];
  38923. };
  38924. /**
  38925. * Returns all vertex buffers
  38926. * @return an object holding all vertex buffers indexed by kind
  38927. */
  38928. Geometry.prototype.getVertexBuffers = function () {
  38929. if (!this.isReady()) {
  38930. return null;
  38931. }
  38932. return this._vertexBuffers;
  38933. };
  38934. /**
  38935. * Gets a boolean indicating if specific vertex buffer is present
  38936. * @param kind defines the data kind (Position, normal, etc...)
  38937. * @returns true if data is present
  38938. */
  38939. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38940. if (!this._vertexBuffers) {
  38941. if (this._delayInfo) {
  38942. return this._delayInfo.indexOf(kind) !== -1;
  38943. }
  38944. return false;
  38945. }
  38946. return this._vertexBuffers[kind] !== undefined;
  38947. };
  38948. /**
  38949. * Gets a list of all attached data kinds (Position, normal, etc...)
  38950. * @returns a list of string containing all kinds
  38951. */
  38952. Geometry.prototype.getVerticesDataKinds = function () {
  38953. var result = [];
  38954. var kind;
  38955. if (!this._vertexBuffers && this._delayInfo) {
  38956. for (kind in this._delayInfo) {
  38957. result.push(kind);
  38958. }
  38959. }
  38960. else {
  38961. for (kind in this._vertexBuffers) {
  38962. result.push(kind);
  38963. }
  38964. }
  38965. return result;
  38966. };
  38967. /**
  38968. * Update index buffer
  38969. * @param indices defines the indices to store in the index buffer
  38970. * @param offset defines the offset in the target buffer where to store the data
  38971. */
  38972. Geometry.prototype.updateIndices = function (indices, offset) {
  38973. if (!this._indexBuffer) {
  38974. return;
  38975. }
  38976. if (!this._indexBufferIsUpdatable) {
  38977. this.setIndices(indices, null, true);
  38978. }
  38979. else {
  38980. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38981. }
  38982. };
  38983. /**
  38984. * Creates a new index buffer
  38985. * @param indices defines the indices to store in the index buffer
  38986. * @param totalVertices defines the total number of vertices (could be null)
  38987. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38988. */
  38989. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38990. if (totalVertices === void 0) { totalVertices = null; }
  38991. if (updatable === void 0) { updatable = false; }
  38992. if (this._indexBuffer) {
  38993. this._engine._releaseBuffer(this._indexBuffer);
  38994. }
  38995. this._disposeVertexArrayObjects();
  38996. this._indices = indices;
  38997. this._indexBufferIsUpdatable = updatable;
  38998. if (this._meshes.length !== 0 && this._indices) {
  38999. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39000. }
  39001. if (totalVertices != undefined) { // including null and undefined
  39002. this._totalVertices = totalVertices;
  39003. }
  39004. var meshes = this._meshes;
  39005. var numOfMeshes = meshes.length;
  39006. for (var index = 0; index < numOfMeshes; index++) {
  39007. meshes[index]._createGlobalSubMesh(true);
  39008. }
  39009. this.notifyUpdate();
  39010. };
  39011. /**
  39012. * Return the total number of indices
  39013. * @returns the total number of indices
  39014. */
  39015. Geometry.prototype.getTotalIndices = function () {
  39016. if (!this.isReady()) {
  39017. return 0;
  39018. }
  39019. return this._indices.length;
  39020. };
  39021. /**
  39022. * Gets the index buffer array
  39023. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39024. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39025. * @returns the index buffer array
  39026. */
  39027. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39028. if (!this.isReady()) {
  39029. return null;
  39030. }
  39031. var orig = this._indices;
  39032. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39033. return orig;
  39034. }
  39035. else {
  39036. var len = orig.length;
  39037. var copy = [];
  39038. for (var i = 0; i < len; i++) {
  39039. copy.push(orig[i]);
  39040. }
  39041. return copy;
  39042. }
  39043. };
  39044. /**
  39045. * Gets the index buffer
  39046. * @return the index buffer
  39047. */
  39048. Geometry.prototype.getIndexBuffer = function () {
  39049. if (!this.isReady()) {
  39050. return null;
  39051. }
  39052. return this._indexBuffer;
  39053. };
  39054. /** @hidden */
  39055. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39056. if (effect === void 0) { effect = null; }
  39057. if (!effect || !this._vertexArrayObjects) {
  39058. return;
  39059. }
  39060. if (this._vertexArrayObjects[effect.key]) {
  39061. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39062. delete this._vertexArrayObjects[effect.key];
  39063. }
  39064. };
  39065. /**
  39066. * Release the associated resources for a specific mesh
  39067. * @param mesh defines the source mesh
  39068. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39069. */
  39070. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39071. var meshes = this._meshes;
  39072. var index = meshes.indexOf(mesh);
  39073. if (index === -1) {
  39074. return;
  39075. }
  39076. meshes.splice(index, 1);
  39077. mesh._geometry = null;
  39078. if (meshes.length === 0 && shouldDispose) {
  39079. this.dispose();
  39080. }
  39081. };
  39082. /**
  39083. * Apply current geometry to a given mesh
  39084. * @param mesh defines the mesh to apply geometry to
  39085. */
  39086. Geometry.prototype.applyToMesh = function (mesh) {
  39087. if (mesh._geometry === this) {
  39088. return;
  39089. }
  39090. var previousGeometry = mesh._geometry;
  39091. if (previousGeometry) {
  39092. previousGeometry.releaseForMesh(mesh);
  39093. }
  39094. var meshes = this._meshes;
  39095. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39096. mesh._geometry = this;
  39097. this._scene.pushGeometry(this);
  39098. meshes.push(mesh);
  39099. if (this.isReady()) {
  39100. this._applyToMesh(mesh);
  39101. }
  39102. else {
  39103. mesh._boundingInfo = this._boundingInfo;
  39104. }
  39105. };
  39106. Geometry.prototype._updateExtend = function (data) {
  39107. if (data === void 0) { data = null; }
  39108. if (!data) {
  39109. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39110. }
  39111. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39112. };
  39113. Geometry.prototype._applyToMesh = function (mesh) {
  39114. var numOfMeshes = this._meshes.length;
  39115. // vertexBuffers
  39116. for (var kind in this._vertexBuffers) {
  39117. if (numOfMeshes === 1) {
  39118. this._vertexBuffers[kind].create();
  39119. }
  39120. var buffer = this._vertexBuffers[kind].getBuffer();
  39121. if (buffer)
  39122. buffer.references = numOfMeshes;
  39123. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39124. if (!this._extend) {
  39125. this._updateExtend();
  39126. }
  39127. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39128. mesh._createGlobalSubMesh(false);
  39129. //bounding info was just created again, world matrix should be applied again.
  39130. mesh._updateBoundingInfo();
  39131. }
  39132. }
  39133. // indexBuffer
  39134. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39135. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39136. }
  39137. if (this._indexBuffer) {
  39138. this._indexBuffer.references = numOfMeshes;
  39139. }
  39140. };
  39141. Geometry.prototype.notifyUpdate = function (kind) {
  39142. if (this.onGeometryUpdated) {
  39143. this.onGeometryUpdated(this, kind);
  39144. }
  39145. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39146. var mesh = _a[_i];
  39147. mesh._markSubMeshesAsAttributesDirty();
  39148. }
  39149. };
  39150. /**
  39151. * Load the geometry if it was flagged as delay loaded
  39152. * @param scene defines the hosting scene
  39153. * @param onLoaded defines a callback called when the geometry is loaded
  39154. */
  39155. Geometry.prototype.load = function (scene, onLoaded) {
  39156. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39157. return;
  39158. }
  39159. if (this.isReady()) {
  39160. if (onLoaded) {
  39161. onLoaded();
  39162. }
  39163. return;
  39164. }
  39165. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39166. this._queueLoad(scene, onLoaded);
  39167. };
  39168. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39169. var _this = this;
  39170. if (!this.delayLoadingFile) {
  39171. return;
  39172. }
  39173. scene._addPendingData(this);
  39174. scene._loadFile(this.delayLoadingFile, function (data) {
  39175. if (!_this._delayLoadingFunction) {
  39176. return;
  39177. }
  39178. _this._delayLoadingFunction(JSON.parse(data), _this);
  39179. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39180. _this._delayInfo = [];
  39181. scene._removePendingData(_this);
  39182. var meshes = _this._meshes;
  39183. var numOfMeshes = meshes.length;
  39184. for (var index = 0; index < numOfMeshes; index++) {
  39185. _this._applyToMesh(meshes[index]);
  39186. }
  39187. if (onLoaded) {
  39188. onLoaded();
  39189. }
  39190. }, undefined, true);
  39191. };
  39192. /**
  39193. * Invert the geometry to move from a right handed system to a left handed one.
  39194. */
  39195. Geometry.prototype.toLeftHanded = function () {
  39196. // Flip faces
  39197. var tIndices = this.getIndices(false);
  39198. if (tIndices != null && tIndices.length > 0) {
  39199. for (var i = 0; i < tIndices.length; i += 3) {
  39200. var tTemp = tIndices[i + 0];
  39201. tIndices[i + 0] = tIndices[i + 2];
  39202. tIndices[i + 2] = tTemp;
  39203. }
  39204. this.setIndices(tIndices);
  39205. }
  39206. // Negate position.z
  39207. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39208. if (tPositions != null && tPositions.length > 0) {
  39209. for (var i = 0; i < tPositions.length; i += 3) {
  39210. tPositions[i + 2] = -tPositions[i + 2];
  39211. }
  39212. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39213. }
  39214. // Negate normal.z
  39215. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39216. if (tNormals != null && tNormals.length > 0) {
  39217. for (var i = 0; i < tNormals.length; i += 3) {
  39218. tNormals[i + 2] = -tNormals[i + 2];
  39219. }
  39220. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39221. }
  39222. };
  39223. // Cache
  39224. /** @hidden */
  39225. Geometry.prototype._resetPointsArrayCache = function () {
  39226. this._positions = null;
  39227. };
  39228. /** @hidden */
  39229. Geometry.prototype._generatePointsArray = function () {
  39230. if (this._positions)
  39231. return true;
  39232. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39233. if (!data || data.length === 0) {
  39234. return false;
  39235. }
  39236. this._positions = [];
  39237. for (var index = 0; index < data.length; index += 3) {
  39238. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39239. }
  39240. return true;
  39241. };
  39242. /**
  39243. * Gets a value indicating if the geometry is disposed
  39244. * @returns true if the geometry was disposed
  39245. */
  39246. Geometry.prototype.isDisposed = function () {
  39247. return this._isDisposed;
  39248. };
  39249. Geometry.prototype._disposeVertexArrayObjects = function () {
  39250. if (this._vertexArrayObjects) {
  39251. for (var kind in this._vertexArrayObjects) {
  39252. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39253. }
  39254. this._vertexArrayObjects = {};
  39255. }
  39256. };
  39257. /**
  39258. * Free all associated resources
  39259. */
  39260. Geometry.prototype.dispose = function () {
  39261. var meshes = this._meshes;
  39262. var numOfMeshes = meshes.length;
  39263. var index;
  39264. for (index = 0; index < numOfMeshes; index++) {
  39265. this.releaseForMesh(meshes[index]);
  39266. }
  39267. this._meshes = [];
  39268. this._disposeVertexArrayObjects();
  39269. for (var kind in this._vertexBuffers) {
  39270. this._vertexBuffers[kind].dispose();
  39271. }
  39272. this._vertexBuffers = {};
  39273. this._totalVertices = 0;
  39274. if (this._indexBuffer) {
  39275. this._engine._releaseBuffer(this._indexBuffer);
  39276. }
  39277. this._indexBuffer = null;
  39278. this._indices = [];
  39279. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39280. this.delayLoadingFile = null;
  39281. this._delayLoadingFunction = null;
  39282. this._delayInfo = [];
  39283. this._boundingInfo = null;
  39284. this._scene.removeGeometry(this);
  39285. this._isDisposed = true;
  39286. };
  39287. /**
  39288. * Clone the current geometry into a new geometry
  39289. * @param id defines the unique ID of the new geometry
  39290. * @returns a new geometry object
  39291. */
  39292. Geometry.prototype.copy = function (id) {
  39293. var vertexData = new BABYLON.VertexData();
  39294. vertexData.indices = [];
  39295. var indices = this.getIndices();
  39296. if (indices) {
  39297. for (var index = 0; index < indices.length; index++) {
  39298. vertexData.indices.push(indices[index]);
  39299. }
  39300. }
  39301. var updatable = false;
  39302. var stopChecking = false;
  39303. var kind;
  39304. for (kind in this._vertexBuffers) {
  39305. // using slice() to make a copy of the array and not just reference it
  39306. var data = this.getVerticesData(kind);
  39307. if (data instanceof Float32Array) {
  39308. vertexData.set(new Float32Array(data), kind);
  39309. }
  39310. else {
  39311. vertexData.set(data.slice(0), kind);
  39312. }
  39313. if (!stopChecking) {
  39314. var vb = this.getVertexBuffer(kind);
  39315. if (vb) {
  39316. updatable = vb.isUpdatable();
  39317. stopChecking = !updatable;
  39318. }
  39319. }
  39320. }
  39321. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39322. geometry.delayLoadState = this.delayLoadState;
  39323. geometry.delayLoadingFile = this.delayLoadingFile;
  39324. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39325. for (kind in this._delayInfo) {
  39326. geometry._delayInfo = geometry._delayInfo || [];
  39327. geometry._delayInfo.push(kind);
  39328. }
  39329. // Bounding info
  39330. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39331. return geometry;
  39332. };
  39333. /**
  39334. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39335. * @return a JSON representation of the current geometry data (without the vertices data)
  39336. */
  39337. Geometry.prototype.serialize = function () {
  39338. var serializationObject = {};
  39339. serializationObject.id = this.id;
  39340. serializationObject.updatable = this._updatable;
  39341. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39342. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39343. }
  39344. return serializationObject;
  39345. };
  39346. Geometry.prototype.toNumberArray = function (origin) {
  39347. if (Array.isArray(origin)) {
  39348. return origin;
  39349. }
  39350. else {
  39351. return Array.prototype.slice.call(origin);
  39352. }
  39353. };
  39354. /**
  39355. * Serialize all vertices data into a JSON oject
  39356. * @returns a JSON representation of the current geometry data
  39357. */
  39358. Geometry.prototype.serializeVerticeData = function () {
  39359. var serializationObject = this.serialize();
  39360. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39361. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39362. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39363. serializationObject.positions._updatable = true;
  39364. }
  39365. }
  39366. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39367. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39368. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39369. serializationObject.normals._updatable = true;
  39370. }
  39371. }
  39372. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39373. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39374. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39375. serializationObject.tangets._updatable = true;
  39376. }
  39377. }
  39378. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39379. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39380. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39381. serializationObject.uvs._updatable = true;
  39382. }
  39383. }
  39384. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39385. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39386. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39387. serializationObject.uv2s._updatable = true;
  39388. }
  39389. }
  39390. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39391. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39392. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39393. serializationObject.uv3s._updatable = true;
  39394. }
  39395. }
  39396. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39397. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39398. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39399. serializationObject.uv4s._updatable = true;
  39400. }
  39401. }
  39402. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39403. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39404. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39405. serializationObject.uv5s._updatable = true;
  39406. }
  39407. }
  39408. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39409. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39410. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39411. serializationObject.uv6s._updatable = true;
  39412. }
  39413. }
  39414. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39415. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39416. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39417. serializationObject.colors._updatable = true;
  39418. }
  39419. }
  39420. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39421. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39422. serializationObject.matricesIndices._isExpanded = true;
  39423. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39424. serializationObject.matricesIndices._updatable = true;
  39425. }
  39426. }
  39427. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39428. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39429. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39430. serializationObject.matricesWeights._updatable = true;
  39431. }
  39432. }
  39433. serializationObject.indices = this.toNumberArray(this.getIndices());
  39434. return serializationObject;
  39435. };
  39436. // Statics
  39437. /**
  39438. * Extracts a clone of a mesh geometry
  39439. * @param mesh defines the source mesh
  39440. * @param id defines the unique ID of the new geometry object
  39441. * @returns the new geometry object
  39442. */
  39443. Geometry.ExtractFromMesh = function (mesh, id) {
  39444. var geometry = mesh._geometry;
  39445. if (!geometry) {
  39446. return null;
  39447. }
  39448. return geometry.copy(id);
  39449. };
  39450. /**
  39451. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39452. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39453. * Be aware Math.random() could cause collisions, but:
  39454. * "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"
  39455. * @returns a string containing a new GUID
  39456. */
  39457. Geometry.RandomId = function () {
  39458. return BABYLON.Tools.RandomId();
  39459. };
  39460. /** @hidden */
  39461. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39462. var scene = mesh.getScene();
  39463. // Geometry
  39464. var geometryId = parsedGeometry.geometryId;
  39465. if (geometryId) {
  39466. var geometry = scene.getGeometryByID(geometryId);
  39467. if (geometry) {
  39468. geometry.applyToMesh(mesh);
  39469. }
  39470. }
  39471. else if (parsedGeometry instanceof ArrayBuffer) {
  39472. var binaryInfo = mesh._binaryInfo;
  39473. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39474. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39475. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39476. }
  39477. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39478. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39479. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39480. }
  39481. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39482. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39483. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39484. }
  39485. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39486. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39487. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39488. }
  39489. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39490. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39491. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39492. }
  39493. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39494. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39495. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39496. }
  39497. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39498. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39499. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39500. }
  39501. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39502. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39503. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39504. }
  39505. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39506. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39507. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39508. }
  39509. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39510. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39511. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39512. }
  39513. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39514. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39515. var floatIndices = [];
  39516. for (var i = 0; i < matricesIndicesData.length; i++) {
  39517. var index = matricesIndicesData[i];
  39518. floatIndices.push(index & 0x000000FF);
  39519. floatIndices.push((index & 0x0000FF00) >> 8);
  39520. floatIndices.push((index & 0x00FF0000) >> 16);
  39521. floatIndices.push(index >> 24);
  39522. }
  39523. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39524. }
  39525. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39526. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39527. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39528. }
  39529. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39530. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39531. mesh.setIndices(indicesData, null);
  39532. }
  39533. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39534. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39535. mesh.subMeshes = [];
  39536. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39537. var materialIndex = subMeshesData[(i * 5) + 0];
  39538. var verticesStart = subMeshesData[(i * 5) + 1];
  39539. var verticesCount = subMeshesData[(i * 5) + 2];
  39540. var indexStart = subMeshesData[(i * 5) + 3];
  39541. var indexCount = subMeshesData[(i * 5) + 4];
  39542. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39543. }
  39544. }
  39545. }
  39546. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39547. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39548. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39549. if (parsedGeometry.tangents) {
  39550. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39551. }
  39552. if (parsedGeometry.uvs) {
  39553. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39554. }
  39555. if (parsedGeometry.uvs2) {
  39556. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39557. }
  39558. if (parsedGeometry.uvs3) {
  39559. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39560. }
  39561. if (parsedGeometry.uvs4) {
  39562. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39563. }
  39564. if (parsedGeometry.uvs5) {
  39565. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39566. }
  39567. if (parsedGeometry.uvs6) {
  39568. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39569. }
  39570. if (parsedGeometry.colors) {
  39571. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39572. }
  39573. if (parsedGeometry.matricesIndices) {
  39574. if (!parsedGeometry.matricesIndices._isExpanded) {
  39575. var floatIndices = [];
  39576. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39577. var matricesIndex = parsedGeometry.matricesIndices[i];
  39578. floatIndices.push(matricesIndex & 0x000000FF);
  39579. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39580. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39581. floatIndices.push(matricesIndex >> 24);
  39582. }
  39583. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39584. }
  39585. else {
  39586. delete parsedGeometry.matricesIndices._isExpanded;
  39587. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39588. }
  39589. }
  39590. if (parsedGeometry.matricesIndicesExtra) {
  39591. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39592. var floatIndices = [];
  39593. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39594. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39595. floatIndices.push(matricesIndex & 0x000000FF);
  39596. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39597. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39598. floatIndices.push(matricesIndex >> 24);
  39599. }
  39600. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39601. }
  39602. else {
  39603. delete parsedGeometry.matricesIndices._isExpanded;
  39604. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39605. }
  39606. }
  39607. if (parsedGeometry.matricesWeights) {
  39608. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39609. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39610. }
  39611. if (parsedGeometry.matricesWeightsExtra) {
  39612. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39613. }
  39614. mesh.setIndices(parsedGeometry.indices, null);
  39615. }
  39616. // SubMeshes
  39617. if (parsedGeometry.subMeshes) {
  39618. mesh.subMeshes = [];
  39619. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39620. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39621. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39622. }
  39623. }
  39624. // Flat shading
  39625. if (mesh._shouldGenerateFlatShading) {
  39626. mesh.convertToFlatShadedMesh();
  39627. delete mesh._shouldGenerateFlatShading;
  39628. }
  39629. // Update
  39630. mesh.computeWorldMatrix(true);
  39631. scene.onMeshImportedObservable.notifyObservers(mesh);
  39632. };
  39633. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39634. var epsilon = 1e-3;
  39635. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39636. return;
  39637. }
  39638. var noInfluenceBoneIndex = 0.0;
  39639. if (parsedGeometry.skeletonId > -1) {
  39640. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39641. if (!skeleton) {
  39642. return;
  39643. }
  39644. noInfluenceBoneIndex = skeleton.bones.length;
  39645. }
  39646. else {
  39647. return;
  39648. }
  39649. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39650. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39651. var matricesWeights = parsedGeometry.matricesWeights;
  39652. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39653. var influencers = parsedGeometry.numBoneInfluencer;
  39654. var size = matricesWeights.length;
  39655. for (var i = 0; i < size; i += 4) {
  39656. var weight = 0.0;
  39657. var firstZeroWeight = -1;
  39658. for (var j = 0; j < 4; j++) {
  39659. var w = matricesWeights[i + j];
  39660. weight += w;
  39661. if (w < epsilon && firstZeroWeight < 0) {
  39662. firstZeroWeight = j;
  39663. }
  39664. }
  39665. if (matricesWeightsExtra) {
  39666. for (var j = 0; j < 4; j++) {
  39667. var w = matricesWeightsExtra[i + j];
  39668. weight += w;
  39669. if (w < epsilon && firstZeroWeight < 0) {
  39670. firstZeroWeight = j + 4;
  39671. }
  39672. }
  39673. }
  39674. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39675. firstZeroWeight = influencers - 1;
  39676. }
  39677. if (weight > epsilon) {
  39678. var mweight = 1.0 / weight;
  39679. for (var j = 0; j < 4; j++) {
  39680. matricesWeights[i + j] *= mweight;
  39681. }
  39682. if (matricesWeightsExtra) {
  39683. for (var j = 0; j < 4; j++) {
  39684. matricesWeightsExtra[i + j] *= mweight;
  39685. }
  39686. }
  39687. }
  39688. else {
  39689. if (firstZeroWeight >= 4) {
  39690. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39691. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39692. }
  39693. else {
  39694. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39695. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39696. }
  39697. }
  39698. }
  39699. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39700. if (parsedGeometry.matricesWeightsExtra) {
  39701. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39702. }
  39703. };
  39704. /**
  39705. * Create a new geometry from persisted data (Using .babylon file format)
  39706. * @param parsedVertexData defines the persisted data
  39707. * @param scene defines the hosting scene
  39708. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39709. * @returns the new geometry object
  39710. */
  39711. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39712. if (scene.getGeometryByID(parsedVertexData.id)) {
  39713. return null; // null since geometry could be something else than a box...
  39714. }
  39715. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39716. if (BABYLON.Tags) {
  39717. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39718. }
  39719. if (parsedVertexData.delayLoadingFile) {
  39720. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39721. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39722. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39723. geometry._delayInfo = [];
  39724. if (parsedVertexData.hasUVs) {
  39725. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39726. }
  39727. if (parsedVertexData.hasUVs2) {
  39728. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39729. }
  39730. if (parsedVertexData.hasUVs3) {
  39731. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39732. }
  39733. if (parsedVertexData.hasUVs4) {
  39734. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39735. }
  39736. if (parsedVertexData.hasUVs5) {
  39737. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39738. }
  39739. if (parsedVertexData.hasUVs6) {
  39740. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39741. }
  39742. if (parsedVertexData.hasColors) {
  39743. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39744. }
  39745. if (parsedVertexData.hasMatricesIndices) {
  39746. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39747. }
  39748. if (parsedVertexData.hasMatricesWeights) {
  39749. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39750. }
  39751. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39752. }
  39753. else {
  39754. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39755. }
  39756. scene.pushGeometry(geometry, true);
  39757. return geometry;
  39758. };
  39759. return Geometry;
  39760. }());
  39761. BABYLON.Geometry = Geometry;
  39762. // Primitives
  39763. /// Abstract class
  39764. /**
  39765. * Abstract class used to provide common services for all typed geometries
  39766. * @hidden
  39767. */
  39768. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39769. __extends(_PrimitiveGeometry, _super);
  39770. /**
  39771. * Creates a new typed geometry
  39772. * @param id defines the unique ID of the geometry
  39773. * @param scene defines the hosting scene
  39774. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39775. * @param mesh defines the hosting mesh (can be null)
  39776. */
  39777. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39778. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39779. if (mesh === void 0) { mesh = null; }
  39780. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39781. _this._canBeRegenerated = _canBeRegenerated;
  39782. _this._beingRegenerated = true;
  39783. _this.regenerate();
  39784. _this._beingRegenerated = false;
  39785. return _this;
  39786. }
  39787. /**
  39788. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39789. * @returns true if the geometry can be regenerated
  39790. */
  39791. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39792. return this._canBeRegenerated;
  39793. };
  39794. /**
  39795. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39796. */
  39797. _PrimitiveGeometry.prototype.regenerate = function () {
  39798. if (!this._canBeRegenerated) {
  39799. return;
  39800. }
  39801. this._beingRegenerated = true;
  39802. this.setAllVerticesData(this._regenerateVertexData(), false);
  39803. this._beingRegenerated = false;
  39804. };
  39805. /**
  39806. * Clone the geometry
  39807. * @param id defines the unique ID of the new geometry
  39808. * @returns the new geometry
  39809. */
  39810. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39811. return _super.prototype.copy.call(this, id);
  39812. };
  39813. // overrides
  39814. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39815. if (!this._beingRegenerated) {
  39816. return;
  39817. }
  39818. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39819. };
  39820. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39821. if (!this._beingRegenerated) {
  39822. return;
  39823. }
  39824. _super.prototype.setVerticesData.call(this, kind, data, false);
  39825. };
  39826. // to override
  39827. /** @hidden */
  39828. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39829. throw new Error("Abstract method");
  39830. };
  39831. _PrimitiveGeometry.prototype.copy = function (id) {
  39832. throw new Error("Must be overriden in sub-classes.");
  39833. };
  39834. _PrimitiveGeometry.prototype.serialize = function () {
  39835. var serializationObject = _super.prototype.serialize.call(this);
  39836. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39837. return serializationObject;
  39838. };
  39839. return _PrimitiveGeometry;
  39840. }(Geometry));
  39841. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39842. /**
  39843. * Creates a ribbon geometry
  39844. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39845. */
  39846. var RibbonGeometry = /** @class */ (function (_super) {
  39847. __extends(RibbonGeometry, _super);
  39848. /**
  39849. * Creates a ribbon geometry
  39850. * @param id defines the unique ID of the geometry
  39851. * @param scene defines the hosting scene
  39852. * @param pathArray defines the array of paths to use
  39853. * @param closeArray defines if the last path and the first path must be joined
  39854. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39855. * @param offset defines the offset between points
  39856. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39857. * @param mesh defines the hosting mesh (can be null)
  39858. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39859. */
  39860. function RibbonGeometry(id, scene,
  39861. /**
  39862. * Defines the array of paths to use
  39863. */
  39864. pathArray,
  39865. /**
  39866. * Defines if the last and first points of each path in your pathArray must be joined
  39867. */
  39868. closeArray,
  39869. /**
  39870. * Defines if the last and first points of each path in your pathArray must be joined
  39871. */
  39872. closePath,
  39873. /**
  39874. * Defines the offset between points
  39875. */
  39876. offset, canBeRegenerated, mesh,
  39877. /**
  39878. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39879. */
  39880. side) {
  39881. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39882. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39883. _this.pathArray = pathArray;
  39884. _this.closeArray = closeArray;
  39885. _this.closePath = closePath;
  39886. _this.offset = offset;
  39887. _this.side = side;
  39888. return _this;
  39889. }
  39890. /** @hidden */
  39891. RibbonGeometry.prototype._regenerateVertexData = function () {
  39892. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39893. };
  39894. RibbonGeometry.prototype.copy = function (id) {
  39895. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39896. };
  39897. return RibbonGeometry;
  39898. }(_PrimitiveGeometry));
  39899. BABYLON.RibbonGeometry = RibbonGeometry;
  39900. /**
  39901. * Creates a box geometry
  39902. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39903. */
  39904. var BoxGeometry = /** @class */ (function (_super) {
  39905. __extends(BoxGeometry, _super);
  39906. /**
  39907. * Creates a box geometry
  39908. * @param id defines the unique ID of the geometry
  39909. * @param scene defines the hosting scene
  39910. * @param size defines the zise of the box (width, height and depth are the same)
  39911. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39912. * @param mesh defines the hosting mesh (can be null)
  39913. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39914. */
  39915. function BoxGeometry(id, scene,
  39916. /**
  39917. * Defines the zise of the box (width, height and depth are the same)
  39918. */
  39919. size, canBeRegenerated, mesh,
  39920. /**
  39921. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39922. */
  39923. side) {
  39924. if (mesh === void 0) { mesh = null; }
  39925. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39926. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39927. _this.size = size;
  39928. _this.side = side;
  39929. return _this;
  39930. }
  39931. /** @hidden */
  39932. BoxGeometry.prototype._regenerateVertexData = function () {
  39933. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39934. };
  39935. BoxGeometry.prototype.copy = function (id) {
  39936. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39937. };
  39938. BoxGeometry.prototype.serialize = function () {
  39939. var serializationObject = _super.prototype.serialize.call(this);
  39940. serializationObject.size = this.size;
  39941. return serializationObject;
  39942. };
  39943. BoxGeometry.Parse = function (parsedBox, scene) {
  39944. if (scene.getGeometryByID(parsedBox.id)) {
  39945. return null; // null since geometry could be something else than a box...
  39946. }
  39947. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39948. if (BABYLON.Tags) {
  39949. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39950. }
  39951. scene.pushGeometry(box, true);
  39952. return box;
  39953. };
  39954. return BoxGeometry;
  39955. }(_PrimitiveGeometry));
  39956. BABYLON.BoxGeometry = BoxGeometry;
  39957. /**
  39958. * Creates a sphere geometry
  39959. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39960. */
  39961. var SphereGeometry = /** @class */ (function (_super) {
  39962. __extends(SphereGeometry, _super);
  39963. /**
  39964. * Create a new sphere geometry
  39965. * @param id defines the unique ID of the geometry
  39966. * @param scene defines the hosting scene
  39967. * @param segments defines the number of segments to use to create the sphere
  39968. * @param diameter defines the diameter of the sphere
  39969. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39970. * @param mesh defines the hosting mesh (can be null)
  39971. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39972. */
  39973. function SphereGeometry(id, scene,
  39974. /**
  39975. * Defines the number of segments to use to create the sphere
  39976. */
  39977. segments,
  39978. /**
  39979. * Defines the diameter of the sphere
  39980. */
  39981. diameter, canBeRegenerated, mesh,
  39982. /**
  39983. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39984. */
  39985. side) {
  39986. if (mesh === void 0) { mesh = null; }
  39987. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39988. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39989. _this.segments = segments;
  39990. _this.diameter = diameter;
  39991. _this.side = side;
  39992. return _this;
  39993. }
  39994. /** @hidden */
  39995. SphereGeometry.prototype._regenerateVertexData = function () {
  39996. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39997. };
  39998. SphereGeometry.prototype.copy = function (id) {
  39999. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40000. };
  40001. SphereGeometry.prototype.serialize = function () {
  40002. var serializationObject = _super.prototype.serialize.call(this);
  40003. serializationObject.segments = this.segments;
  40004. serializationObject.diameter = this.diameter;
  40005. return serializationObject;
  40006. };
  40007. SphereGeometry.Parse = function (parsedSphere, scene) {
  40008. if (scene.getGeometryByID(parsedSphere.id)) {
  40009. return null; // null since geometry could be something else than a sphere...
  40010. }
  40011. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40012. if (BABYLON.Tags) {
  40013. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40014. }
  40015. scene.pushGeometry(sphere, true);
  40016. return sphere;
  40017. };
  40018. return SphereGeometry;
  40019. }(_PrimitiveGeometry));
  40020. BABYLON.SphereGeometry = SphereGeometry;
  40021. /**
  40022. * Creates a disc geometry
  40023. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40024. */
  40025. var DiscGeometry = /** @class */ (function (_super) {
  40026. __extends(DiscGeometry, _super);
  40027. /**
  40028. * Creates a new disc geometry
  40029. * @param id defines the unique ID of the geometry
  40030. * @param scene defines the hosting scene
  40031. * @param radius defines the radius of the disc
  40032. * @param tessellation defines the tesselation factor to apply to the disc
  40033. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40034. * @param mesh defines the hosting mesh (can be null)
  40035. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40036. */
  40037. function DiscGeometry(id, scene,
  40038. /**
  40039. * Defines the radius of the disc
  40040. */
  40041. radius,
  40042. /**
  40043. * Defines the tesselation factor to apply to the disc
  40044. */
  40045. tessellation, canBeRegenerated, mesh,
  40046. /**
  40047. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40048. */
  40049. side) {
  40050. if (mesh === void 0) { mesh = null; }
  40051. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40052. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40053. _this.radius = radius;
  40054. _this.tessellation = tessellation;
  40055. _this.side = side;
  40056. return _this;
  40057. }
  40058. /** @hidden */
  40059. DiscGeometry.prototype._regenerateVertexData = function () {
  40060. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40061. };
  40062. DiscGeometry.prototype.copy = function (id) {
  40063. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40064. };
  40065. return DiscGeometry;
  40066. }(_PrimitiveGeometry));
  40067. BABYLON.DiscGeometry = DiscGeometry;
  40068. /**
  40069. * Creates a new cylinder geometry
  40070. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40071. */
  40072. var CylinderGeometry = /** @class */ (function (_super) {
  40073. __extends(CylinderGeometry, _super);
  40074. /**
  40075. * Creates a new cylinder geometry
  40076. * @param id defines the unique ID of the geometry
  40077. * @param scene defines the hosting scene
  40078. * @param height defines the height of the cylinder
  40079. * @param diameterTop defines the diameter of the cylinder's top cap
  40080. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40081. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40082. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40083. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40084. * @param mesh defines the hosting mesh (can be null)
  40085. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40086. */
  40087. function CylinderGeometry(id, scene,
  40088. /**
  40089. * Defines the height of the cylinder
  40090. */
  40091. height,
  40092. /**
  40093. * Defines the diameter of the cylinder's top cap
  40094. */
  40095. diameterTop,
  40096. /**
  40097. * Defines the diameter of the cylinder's bottom cap
  40098. */
  40099. diameterBottom,
  40100. /**
  40101. * Defines the tessellation factor to apply to the cylinder
  40102. */
  40103. tessellation,
  40104. /**
  40105. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40106. */
  40107. subdivisions, canBeRegenerated, mesh,
  40108. /**
  40109. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40110. */
  40111. side) {
  40112. if (subdivisions === void 0) { subdivisions = 1; }
  40113. if (mesh === void 0) { mesh = null; }
  40114. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40115. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40116. _this.height = height;
  40117. _this.diameterTop = diameterTop;
  40118. _this.diameterBottom = diameterBottom;
  40119. _this.tessellation = tessellation;
  40120. _this.subdivisions = subdivisions;
  40121. _this.side = side;
  40122. return _this;
  40123. }
  40124. /** @hidden */
  40125. CylinderGeometry.prototype._regenerateVertexData = function () {
  40126. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40127. };
  40128. CylinderGeometry.prototype.copy = function (id) {
  40129. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40130. };
  40131. CylinderGeometry.prototype.serialize = function () {
  40132. var serializationObject = _super.prototype.serialize.call(this);
  40133. serializationObject.height = this.height;
  40134. serializationObject.diameterTop = this.diameterTop;
  40135. serializationObject.diameterBottom = this.diameterBottom;
  40136. serializationObject.tessellation = this.tessellation;
  40137. return serializationObject;
  40138. };
  40139. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40140. if (scene.getGeometryByID(parsedCylinder.id)) {
  40141. return null; // null since geometry could be something else than a cylinder...
  40142. }
  40143. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40144. if (BABYLON.Tags) {
  40145. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40146. }
  40147. scene.pushGeometry(cylinder, true);
  40148. return cylinder;
  40149. };
  40150. return CylinderGeometry;
  40151. }(_PrimitiveGeometry));
  40152. BABYLON.CylinderGeometry = CylinderGeometry;
  40153. /**
  40154. * Creates a new torus geometry
  40155. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40156. */
  40157. var TorusGeometry = /** @class */ (function (_super) {
  40158. __extends(TorusGeometry, _super);
  40159. /**
  40160. * Creates a new torus geometry
  40161. * @param id defines the unique ID of the geometry
  40162. * @param scene defines the hosting scene
  40163. * @param diameter defines the diameter of the torus
  40164. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40165. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40166. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40167. * @param mesh defines the hosting mesh (can be null)
  40168. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40169. */
  40170. function TorusGeometry(id, scene,
  40171. /**
  40172. * Defines the diameter of the torus
  40173. */
  40174. diameter,
  40175. /**
  40176. * Defines the thickness of the torus (ie. internal diameter)
  40177. */
  40178. thickness,
  40179. /**
  40180. * Defines the tesselation factor to apply to the torus
  40181. */
  40182. tessellation, canBeRegenerated, mesh,
  40183. /**
  40184. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40185. */
  40186. side) {
  40187. if (mesh === void 0) { mesh = null; }
  40188. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40189. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40190. _this.diameter = diameter;
  40191. _this.thickness = thickness;
  40192. _this.tessellation = tessellation;
  40193. _this.side = side;
  40194. return _this;
  40195. }
  40196. /** @hidden */
  40197. TorusGeometry.prototype._regenerateVertexData = function () {
  40198. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40199. };
  40200. TorusGeometry.prototype.copy = function (id) {
  40201. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40202. };
  40203. TorusGeometry.prototype.serialize = function () {
  40204. var serializationObject = _super.prototype.serialize.call(this);
  40205. serializationObject.diameter = this.diameter;
  40206. serializationObject.thickness = this.thickness;
  40207. serializationObject.tessellation = this.tessellation;
  40208. return serializationObject;
  40209. };
  40210. TorusGeometry.Parse = function (parsedTorus, scene) {
  40211. if (scene.getGeometryByID(parsedTorus.id)) {
  40212. return null; // null since geometry could be something else than a torus...
  40213. }
  40214. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40215. if (BABYLON.Tags) {
  40216. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40217. }
  40218. scene.pushGeometry(torus, true);
  40219. return torus;
  40220. };
  40221. return TorusGeometry;
  40222. }(_PrimitiveGeometry));
  40223. BABYLON.TorusGeometry = TorusGeometry;
  40224. /**
  40225. * Creates a new ground geometry
  40226. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40227. */
  40228. var GroundGeometry = /** @class */ (function (_super) {
  40229. __extends(GroundGeometry, _super);
  40230. /**
  40231. * Creates a new ground geometry
  40232. * @param id defines the unique ID of the geometry
  40233. * @param scene defines the hosting scene
  40234. * @param width defines the width of the ground
  40235. * @param height defines the height of the ground
  40236. * @param subdivisions defines the subdivisions to apply to the ground
  40237. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40238. * @param mesh defines the hosting mesh (can be null)
  40239. */
  40240. function GroundGeometry(id, scene,
  40241. /**
  40242. * Defines the width of the ground
  40243. */
  40244. width,
  40245. /**
  40246. * Defines the height of the ground
  40247. */
  40248. height,
  40249. /**
  40250. * Defines the subdivisions to apply to the ground
  40251. */
  40252. subdivisions, canBeRegenerated, mesh) {
  40253. if (mesh === void 0) { mesh = null; }
  40254. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40255. _this.width = width;
  40256. _this.height = height;
  40257. _this.subdivisions = subdivisions;
  40258. return _this;
  40259. }
  40260. /** @hidden */
  40261. GroundGeometry.prototype._regenerateVertexData = function () {
  40262. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40263. };
  40264. GroundGeometry.prototype.copy = function (id) {
  40265. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40266. };
  40267. GroundGeometry.prototype.serialize = function () {
  40268. var serializationObject = _super.prototype.serialize.call(this);
  40269. serializationObject.width = this.width;
  40270. serializationObject.height = this.height;
  40271. serializationObject.subdivisions = this.subdivisions;
  40272. return serializationObject;
  40273. };
  40274. GroundGeometry.Parse = function (parsedGround, scene) {
  40275. if (scene.getGeometryByID(parsedGround.id)) {
  40276. return null; // null since geometry could be something else than a ground...
  40277. }
  40278. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40279. if (BABYLON.Tags) {
  40280. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40281. }
  40282. scene.pushGeometry(ground, true);
  40283. return ground;
  40284. };
  40285. return GroundGeometry;
  40286. }(_PrimitiveGeometry));
  40287. BABYLON.GroundGeometry = GroundGeometry;
  40288. /**
  40289. * Creates a tiled ground geometry
  40290. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40291. */
  40292. var TiledGroundGeometry = /** @class */ (function (_super) {
  40293. __extends(TiledGroundGeometry, _super);
  40294. /**
  40295. * Creates a tiled ground geometry
  40296. * @param id defines the unique ID of the geometry
  40297. * @param scene defines the hosting scene
  40298. * @param xmin defines the minimum value on X axis
  40299. * @param zmin defines the minimum value on Z axis
  40300. * @param xmax defines the maximum value on X axis
  40301. * @param zmax defines the maximum value on Z axis
  40302. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40303. * @param precision defines the precision to use when computing the tiles
  40304. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40305. * @param mesh defines the hosting mesh (can be null)
  40306. */
  40307. function TiledGroundGeometry(id, scene,
  40308. /**
  40309. * Defines the minimum value on X axis
  40310. */
  40311. xmin,
  40312. /**
  40313. * Defines the minimum value on Z axis
  40314. */
  40315. zmin,
  40316. /**
  40317. * Defines the maximum value on X axis
  40318. */
  40319. xmax,
  40320. /**
  40321. * Defines the maximum value on Z axis
  40322. */
  40323. zmax,
  40324. /**
  40325. * Defines the subdivisions to apply to the ground
  40326. */
  40327. subdivisions,
  40328. /**
  40329. * Defines the precision to use when computing the tiles
  40330. */
  40331. precision, canBeRegenerated, mesh) {
  40332. if (mesh === void 0) { mesh = null; }
  40333. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40334. _this.xmin = xmin;
  40335. _this.zmin = zmin;
  40336. _this.xmax = xmax;
  40337. _this.zmax = zmax;
  40338. _this.subdivisions = subdivisions;
  40339. _this.precision = precision;
  40340. return _this;
  40341. }
  40342. /** @hidden */
  40343. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40344. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40345. };
  40346. TiledGroundGeometry.prototype.copy = function (id) {
  40347. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40348. };
  40349. return TiledGroundGeometry;
  40350. }(_PrimitiveGeometry));
  40351. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40352. /**
  40353. * Creates a plane geometry
  40354. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40355. */
  40356. var PlaneGeometry = /** @class */ (function (_super) {
  40357. __extends(PlaneGeometry, _super);
  40358. /**
  40359. * Creates a plane geometry
  40360. * @param id defines the unique ID of the geometry
  40361. * @param scene defines the hosting scene
  40362. * @param size defines the size of the plane (width === height)
  40363. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40364. * @param mesh defines the hosting mesh (can be null)
  40365. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40366. */
  40367. function PlaneGeometry(id, scene,
  40368. /**
  40369. * Defines the size of the plane (width === height)
  40370. */
  40371. size, canBeRegenerated, mesh,
  40372. /**
  40373. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40374. */
  40375. side) {
  40376. if (mesh === void 0) { mesh = null; }
  40377. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40378. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40379. _this.size = size;
  40380. _this.side = side;
  40381. return _this;
  40382. }
  40383. /** @hidden */
  40384. PlaneGeometry.prototype._regenerateVertexData = function () {
  40385. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40386. };
  40387. PlaneGeometry.prototype.copy = function (id) {
  40388. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40389. };
  40390. PlaneGeometry.prototype.serialize = function () {
  40391. var serializationObject = _super.prototype.serialize.call(this);
  40392. serializationObject.size = this.size;
  40393. return serializationObject;
  40394. };
  40395. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40396. if (scene.getGeometryByID(parsedPlane.id)) {
  40397. return null; // null since geometry could be something else than a ground...
  40398. }
  40399. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40400. if (BABYLON.Tags) {
  40401. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40402. }
  40403. scene.pushGeometry(plane, true);
  40404. return plane;
  40405. };
  40406. return PlaneGeometry;
  40407. }(_PrimitiveGeometry));
  40408. BABYLON.PlaneGeometry = PlaneGeometry;
  40409. /**
  40410. * Creates a torus knot geometry
  40411. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40412. */
  40413. var TorusKnotGeometry = /** @class */ (function (_super) {
  40414. __extends(TorusKnotGeometry, _super);
  40415. /**
  40416. * Creates a torus knot geometry
  40417. * @param id defines the unique ID of the geometry
  40418. * @param scene defines the hosting scene
  40419. * @param radius defines the radius of the torus knot
  40420. * @param tube defines the thickness of the torus knot tube
  40421. * @param radialSegments defines the number of radial segments
  40422. * @param tubularSegments defines the number of tubular segments
  40423. * @param p defines the first number of windings
  40424. * @param q defines the second number of windings
  40425. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40426. * @param mesh defines the hosting mesh (can be null)
  40427. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40428. */
  40429. function TorusKnotGeometry(id, scene,
  40430. /**
  40431. * Defines the radius of the torus knot
  40432. */
  40433. radius,
  40434. /**
  40435. * Defines the thickness of the torus knot tube
  40436. */
  40437. tube,
  40438. /**
  40439. * Defines the number of radial segments
  40440. */
  40441. radialSegments,
  40442. /**
  40443. * Defines the number of tubular segments
  40444. */
  40445. tubularSegments,
  40446. /**
  40447. * Defines the first number of windings
  40448. */
  40449. p,
  40450. /**
  40451. * Defines the second number of windings
  40452. */
  40453. q, canBeRegenerated, mesh,
  40454. /**
  40455. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40456. */
  40457. side) {
  40458. if (mesh === void 0) { mesh = null; }
  40459. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40460. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40461. _this.radius = radius;
  40462. _this.tube = tube;
  40463. _this.radialSegments = radialSegments;
  40464. _this.tubularSegments = tubularSegments;
  40465. _this.p = p;
  40466. _this.q = q;
  40467. _this.side = side;
  40468. return _this;
  40469. }
  40470. /** @hidden */
  40471. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40472. 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 });
  40473. };
  40474. TorusKnotGeometry.prototype.copy = function (id) {
  40475. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40476. };
  40477. TorusKnotGeometry.prototype.serialize = function () {
  40478. var serializationObject = _super.prototype.serialize.call(this);
  40479. serializationObject.radius = this.radius;
  40480. serializationObject.tube = this.tube;
  40481. serializationObject.radialSegments = this.radialSegments;
  40482. serializationObject.tubularSegments = this.tubularSegments;
  40483. serializationObject.p = this.p;
  40484. serializationObject.q = this.q;
  40485. return serializationObject;
  40486. };
  40487. ;
  40488. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40489. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40490. return null; // null since geometry could be something else than a ground...
  40491. }
  40492. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40493. if (BABYLON.Tags) {
  40494. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40495. }
  40496. scene.pushGeometry(torusKnot, true);
  40497. return torusKnot;
  40498. };
  40499. return TorusKnotGeometry;
  40500. }(_PrimitiveGeometry));
  40501. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40502. //}
  40503. })(BABYLON || (BABYLON = {}));
  40504. //# sourceMappingURL=babylon.geometry.js.map
  40505. var BABYLON;
  40506. (function (BABYLON) {
  40507. /**
  40508. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40509. */
  40510. var PerformanceMonitor = /** @class */ (function () {
  40511. /**
  40512. * constructor
  40513. * @param frameSampleSize The number of samples required to saturate the sliding window
  40514. */
  40515. function PerformanceMonitor(frameSampleSize) {
  40516. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40517. this._enabled = true;
  40518. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40519. }
  40520. /**
  40521. * Samples current frame
  40522. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40523. */
  40524. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40525. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40526. if (!this._enabled)
  40527. return;
  40528. if (this._lastFrameTimeMs != null) {
  40529. var dt = timeMs - this._lastFrameTimeMs;
  40530. this._rollingFrameTime.add(dt);
  40531. }
  40532. this._lastFrameTimeMs = timeMs;
  40533. };
  40534. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40535. /**
  40536. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40537. * @return Average frame time in milliseconds
  40538. */
  40539. get: function () {
  40540. return this._rollingFrameTime.average;
  40541. },
  40542. enumerable: true,
  40543. configurable: true
  40544. });
  40545. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40546. /**
  40547. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40548. * @return Frame time variance in milliseconds squared
  40549. */
  40550. get: function () {
  40551. return this._rollingFrameTime.variance;
  40552. },
  40553. enumerable: true,
  40554. configurable: true
  40555. });
  40556. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40557. /**
  40558. * Returns the frame time of the most recent frame
  40559. * @return Frame time in milliseconds
  40560. */
  40561. get: function () {
  40562. return this._rollingFrameTime.history(0);
  40563. },
  40564. enumerable: true,
  40565. configurable: true
  40566. });
  40567. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40568. /**
  40569. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40570. * @return Framerate in frames per second
  40571. */
  40572. get: function () {
  40573. return 1000.0 / this._rollingFrameTime.average;
  40574. },
  40575. enumerable: true,
  40576. configurable: true
  40577. });
  40578. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40579. /**
  40580. * Returns the average framerate in frames per second using the most recent frame time
  40581. * @return Framerate in frames per second
  40582. */
  40583. get: function () {
  40584. var history = this._rollingFrameTime.history(0);
  40585. if (history === 0) {
  40586. return 0;
  40587. }
  40588. return 1000.0 / history;
  40589. },
  40590. enumerable: true,
  40591. configurable: true
  40592. });
  40593. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40594. /**
  40595. * Returns true if enough samples have been taken to completely fill the sliding window
  40596. * @return true if saturated
  40597. */
  40598. get: function () {
  40599. return this._rollingFrameTime.isSaturated();
  40600. },
  40601. enumerable: true,
  40602. configurable: true
  40603. });
  40604. /**
  40605. * Enables contributions to the sliding window sample set
  40606. */
  40607. PerformanceMonitor.prototype.enable = function () {
  40608. this._enabled = true;
  40609. };
  40610. /**
  40611. * Disables contributions to the sliding window sample set
  40612. * Samples will not be interpolated over the disabled period
  40613. */
  40614. PerformanceMonitor.prototype.disable = function () {
  40615. this._enabled = false;
  40616. //clear last sample to avoid interpolating over the disabled period when next enabled
  40617. this._lastFrameTimeMs = null;
  40618. };
  40619. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40620. /**
  40621. * Returns true if sampling is enabled
  40622. * @return true if enabled
  40623. */
  40624. get: function () {
  40625. return this._enabled;
  40626. },
  40627. enumerable: true,
  40628. configurable: true
  40629. });
  40630. /**
  40631. * Resets performance monitor
  40632. */
  40633. PerformanceMonitor.prototype.reset = function () {
  40634. //clear last sample to avoid interpolating over the disabled period when next enabled
  40635. this._lastFrameTimeMs = null;
  40636. //wipe record
  40637. this._rollingFrameTime.reset();
  40638. };
  40639. return PerformanceMonitor;
  40640. }());
  40641. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40642. /**
  40643. * RollingAverage
  40644. *
  40645. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40646. */
  40647. var RollingAverage = /** @class */ (function () {
  40648. /**
  40649. * constructor
  40650. * @param length The number of samples required to saturate the sliding window
  40651. */
  40652. function RollingAverage(length) {
  40653. this._samples = new Array(length);
  40654. this.reset();
  40655. }
  40656. /**
  40657. * Adds a sample to the sample set
  40658. * @param v The sample value
  40659. */
  40660. RollingAverage.prototype.add = function (v) {
  40661. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40662. var delta;
  40663. //we need to check if we've already wrapped round
  40664. if (this.isSaturated()) {
  40665. //remove bottom of stack from mean
  40666. var bottomValue = this._samples[this._pos];
  40667. delta = bottomValue - this.average;
  40668. this.average -= delta / (this._sampleCount - 1);
  40669. this._m2 -= delta * (bottomValue - this.average);
  40670. }
  40671. else {
  40672. this._sampleCount++;
  40673. }
  40674. //add new value to mean
  40675. delta = v - this.average;
  40676. this.average += delta / (this._sampleCount);
  40677. this._m2 += delta * (v - this.average);
  40678. //set the new variance
  40679. this.variance = this._m2 / (this._sampleCount - 1);
  40680. this._samples[this._pos] = v;
  40681. this._pos++;
  40682. this._pos %= this._samples.length; //positive wrap around
  40683. };
  40684. /**
  40685. * Returns previously added values or null if outside of history or outside the sliding window domain
  40686. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40687. * @return Value previously recorded with add() or null if outside of range
  40688. */
  40689. RollingAverage.prototype.history = function (i) {
  40690. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40691. return 0;
  40692. }
  40693. var i0 = this._wrapPosition(this._pos - 1.0);
  40694. return this._samples[this._wrapPosition(i0 - i)];
  40695. };
  40696. /**
  40697. * Returns true if enough samples have been taken to completely fill the sliding window
  40698. * @return true if sample-set saturated
  40699. */
  40700. RollingAverage.prototype.isSaturated = function () {
  40701. return this._sampleCount >= this._samples.length;
  40702. };
  40703. /**
  40704. * Resets the rolling average (equivalent to 0 samples taken so far)
  40705. */
  40706. RollingAverage.prototype.reset = function () {
  40707. this.average = 0;
  40708. this.variance = 0;
  40709. this._sampleCount = 0;
  40710. this._pos = 0;
  40711. this._m2 = 0;
  40712. };
  40713. /**
  40714. * Wraps a value around the sample range boundaries
  40715. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40716. * @return Wrapped position in sample range
  40717. */
  40718. RollingAverage.prototype._wrapPosition = function (i) {
  40719. var max = this._samples.length;
  40720. return ((i % max) + max) % max;
  40721. };
  40722. return RollingAverage;
  40723. }());
  40724. BABYLON.RollingAverage = RollingAverage;
  40725. })(BABYLON || (BABYLON = {}));
  40726. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40727. var BABYLON;
  40728. (function (BABYLON) {
  40729. /**
  40730. * "Static Class" containing the most commonly used helper while dealing with material for
  40731. * rendering purpose.
  40732. *
  40733. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40734. *
  40735. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40736. */
  40737. var MaterialHelper = /** @class */ (function () {
  40738. function MaterialHelper() {
  40739. }
  40740. /**
  40741. * Bind the current view position to an effect.
  40742. * @param effect The effect to be bound
  40743. * @param scene The scene the eyes position is used from
  40744. */
  40745. MaterialHelper.BindEyePosition = function (effect, scene) {
  40746. if (scene._forcedViewPosition) {
  40747. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40748. return;
  40749. }
  40750. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40751. };
  40752. /**
  40753. * Helps preparing the defines values about the UVs in used in the effect.
  40754. * UVs are shared as much as we can accross chanels in the shaders.
  40755. * @param texture The texture we are preparing the UVs for
  40756. * @param defines The defines to update
  40757. * @param key The chanel key "diffuse", "specular"... used in the shader
  40758. */
  40759. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40760. defines._needUVs = true;
  40761. defines[key] = true;
  40762. if (texture.getTextureMatrix().isIdentity(true)) {
  40763. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40764. if (texture.coordinatesIndex === 0) {
  40765. defines["MAINUV1"] = true;
  40766. }
  40767. else {
  40768. defines["MAINUV2"] = true;
  40769. }
  40770. }
  40771. else {
  40772. defines[key + "DIRECTUV"] = 0;
  40773. }
  40774. };
  40775. /**
  40776. * Binds a texture matrix value to its corrsponding uniform
  40777. * @param texture The texture to bind the matrix for
  40778. * @param uniformBuffer The uniform buffer receivin the data
  40779. * @param key The chanel key "diffuse", "specular"... used in the shader
  40780. */
  40781. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40782. var matrix = texture.getTextureMatrix();
  40783. if (!matrix.isIdentity(true)) {
  40784. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40785. }
  40786. };
  40787. /**
  40788. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40789. * @param mesh defines the current mesh
  40790. * @param scene defines the current scene
  40791. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40792. * @param pointsCloud defines if point cloud rendering has to be turned on
  40793. * @param fogEnabled defines if fog has to be turned on
  40794. * @param alphaTest defines if alpha testing has to be turned on
  40795. * @param defines defines the current list of defines
  40796. */
  40797. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40798. if (defines._areMiscDirty) {
  40799. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40800. defines["POINTSIZE"] = pointsCloud;
  40801. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40802. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40803. defines["ALPHATEST"] = alphaTest;
  40804. }
  40805. };
  40806. /**
  40807. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40808. * @param scene defines the current scene
  40809. * @param engine defines the current engine
  40810. * @param defines specifies the list of active defines
  40811. * @param useInstances defines if instances have to be turned on
  40812. * @param useClipPlane defines if clip plane have to be turned on
  40813. */
  40814. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40815. if (useClipPlane === void 0) { useClipPlane = null; }
  40816. var changed = false;
  40817. var useClipPlane1 = false;
  40818. var useClipPlane2 = false;
  40819. var useClipPlane3 = false;
  40820. var useClipPlane4 = false;
  40821. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  40822. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  40823. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  40824. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  40825. if (defines["CLIPPLANE"] !== useClipPlane1) {
  40826. defines["CLIPPLANE"] = useClipPlane1;
  40827. changed = true;
  40828. }
  40829. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  40830. defines["CLIPPLANE2"] = useClipPlane2;
  40831. changed = true;
  40832. }
  40833. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  40834. defines["CLIPPLANE3"] = useClipPlane3;
  40835. changed = true;
  40836. }
  40837. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  40838. defines["CLIPPLANE4"] = useClipPlane4;
  40839. changed = true;
  40840. }
  40841. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40842. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40843. changed = true;
  40844. }
  40845. if (defines["INSTANCES"] !== useInstances) {
  40846. defines["INSTANCES"] = useInstances;
  40847. changed = true;
  40848. }
  40849. if (changed) {
  40850. defines.markAsUnprocessed();
  40851. }
  40852. };
  40853. /**
  40854. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40855. * @param mesh The mesh containing the geometry data we will draw
  40856. * @param defines The defines to update
  40857. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40858. * @param useBones Precise whether bones should be used or not (override mesh info)
  40859. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40860. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40861. * @returns false if defines are considered not dirty and have not been checked
  40862. */
  40863. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40864. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40865. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40866. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40867. return false;
  40868. }
  40869. defines._normals = defines._needNormals;
  40870. defines._uvs = defines._needUVs;
  40871. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40872. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40873. defines["TANGENT"] = true;
  40874. }
  40875. if (defines._needUVs) {
  40876. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40877. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40878. }
  40879. else {
  40880. defines["UV1"] = false;
  40881. defines["UV2"] = false;
  40882. }
  40883. if (useVertexColor) {
  40884. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40885. defines["VERTEXCOLOR"] = hasVertexColors;
  40886. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40887. }
  40888. if (useBones) {
  40889. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40890. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40891. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40892. }
  40893. else {
  40894. defines["NUM_BONE_INFLUENCERS"] = 0;
  40895. defines["BonesPerMesh"] = 0;
  40896. }
  40897. }
  40898. if (useMorphTargets) {
  40899. var manager = mesh.morphTargetManager;
  40900. if (manager) {
  40901. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40902. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40903. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40904. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40905. }
  40906. else {
  40907. defines["MORPHTARGETS_TANGENT"] = false;
  40908. defines["MORPHTARGETS_NORMAL"] = false;
  40909. defines["MORPHTARGETS"] = false;
  40910. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40911. }
  40912. }
  40913. return true;
  40914. };
  40915. /**
  40916. * Prepares the defines related to the light information passed in parameter
  40917. * @param scene The scene we are intending to draw
  40918. * @param mesh The mesh the effect is compiling for
  40919. * @param defines The defines to update
  40920. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40921. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40922. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40923. * @returns true if normals will be required for the rest of the effect
  40924. */
  40925. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40926. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40927. if (disableLighting === void 0) { disableLighting = false; }
  40928. if (!defines._areLightsDirty) {
  40929. return defines._needNormals;
  40930. }
  40931. var lightIndex = 0;
  40932. var needNormals = false;
  40933. var needRebuild = false;
  40934. var lightmapMode = false;
  40935. var shadowEnabled = false;
  40936. var specularEnabled = false;
  40937. if (scene.lightsEnabled && !disableLighting) {
  40938. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40939. var light = _a[_i];
  40940. needNormals = true;
  40941. if (defines["LIGHT" + lightIndex] === undefined) {
  40942. needRebuild = true;
  40943. }
  40944. defines["LIGHT" + lightIndex] = true;
  40945. defines["SPOTLIGHT" + lightIndex] = false;
  40946. defines["HEMILIGHT" + lightIndex] = false;
  40947. defines["POINTLIGHT" + lightIndex] = false;
  40948. defines["DIRLIGHT" + lightIndex] = false;
  40949. light.prepareLightSpecificDefines(defines, lightIndex);
  40950. // FallOff.
  40951. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  40952. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  40953. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  40954. switch (light.falloffType) {
  40955. case BABYLON.Light.FALLOFF_GLTF:
  40956. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  40957. break;
  40958. case BABYLON.Light.FALLOFF_PHYSICAL:
  40959. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  40960. break;
  40961. case BABYLON.Light.FALLOFF_STANDARD:
  40962. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  40963. break;
  40964. }
  40965. // Specular
  40966. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40967. specularEnabled = true;
  40968. }
  40969. // Shadows
  40970. defines["SHADOW" + lightIndex] = false;
  40971. defines["SHADOWPCF" + lightIndex] = false;
  40972. defines["SHADOWPCSS" + lightIndex] = false;
  40973. defines["SHADOWPOISSON" + lightIndex] = false;
  40974. defines["SHADOWESM" + lightIndex] = false;
  40975. defines["SHADOWCUBE" + lightIndex] = false;
  40976. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40977. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40978. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40979. var shadowGenerator = light.getShadowGenerator();
  40980. if (shadowGenerator) {
  40981. var shadowMap = shadowGenerator.getShadowMap();
  40982. if (shadowMap) {
  40983. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40984. shadowEnabled = true;
  40985. shadowGenerator.prepareDefines(defines, lightIndex);
  40986. }
  40987. }
  40988. }
  40989. }
  40990. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40991. lightmapMode = true;
  40992. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40993. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40994. }
  40995. else {
  40996. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40997. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40998. }
  40999. lightIndex++;
  41000. if (lightIndex === maxSimultaneousLights)
  41001. break;
  41002. }
  41003. }
  41004. defines["SPECULARTERM"] = specularEnabled;
  41005. defines["SHADOWS"] = shadowEnabled;
  41006. // Resetting all other lights if any
  41007. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41008. if (defines["LIGHT" + index] !== undefined) {
  41009. defines["LIGHT" + index] = false;
  41010. defines["HEMILIGHT" + lightIndex] = false;
  41011. defines["POINTLIGHT" + lightIndex] = false;
  41012. defines["DIRLIGHT" + lightIndex] = false;
  41013. defines["SPOTLIGHT" + lightIndex] = false;
  41014. defines["SHADOW" + lightIndex] = false;
  41015. }
  41016. }
  41017. var caps = scene.getEngine().getCaps();
  41018. if (defines["SHADOWFLOAT"] === undefined) {
  41019. needRebuild = true;
  41020. }
  41021. defines["SHADOWFLOAT"] = shadowEnabled &&
  41022. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41023. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41024. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41025. if (needRebuild) {
  41026. defines.rebuild();
  41027. }
  41028. return needNormals;
  41029. };
  41030. /**
  41031. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41032. * that won t be acctive due to defines being turned off.
  41033. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41034. * @param samplersList The samplers list
  41035. * @param defines The defines helping in the list generation
  41036. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41037. */
  41038. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41039. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41040. var uniformsList;
  41041. var uniformBuffersList = null;
  41042. if (uniformsListOrOptions.uniformsNames) {
  41043. var options = uniformsListOrOptions;
  41044. uniformsList = options.uniformsNames;
  41045. uniformBuffersList = options.uniformBuffersNames;
  41046. samplersList = options.samplers;
  41047. defines = options.defines;
  41048. maxSimultaneousLights = options.maxSimultaneousLights;
  41049. }
  41050. else {
  41051. uniformsList = uniformsListOrOptions;
  41052. if (!samplersList) {
  41053. samplersList = [];
  41054. }
  41055. }
  41056. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41057. if (!defines["LIGHT" + lightIndex]) {
  41058. break;
  41059. }
  41060. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41061. if (uniformBuffersList) {
  41062. uniformBuffersList.push("Light" + lightIndex);
  41063. }
  41064. samplersList.push("shadowSampler" + lightIndex);
  41065. samplersList.push("depthSampler" + lightIndex);
  41066. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41067. samplersList.push("projectionLightSampler" + lightIndex);
  41068. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41069. }
  41070. }
  41071. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41072. uniformsList.push("morphTargetInfluences");
  41073. }
  41074. };
  41075. /**
  41076. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41077. * @param defines The defines to update while falling back
  41078. * @param fallbacks The authorized effect fallbacks
  41079. * @param maxSimultaneousLights The maximum number of lights allowed
  41080. * @param rank the current rank of the Effect
  41081. * @returns The newly affected rank
  41082. */
  41083. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41084. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41085. if (rank === void 0) { rank = 0; }
  41086. var lightFallbackRank = 0;
  41087. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41088. if (!defines["LIGHT" + lightIndex]) {
  41089. break;
  41090. }
  41091. if (lightIndex > 0) {
  41092. lightFallbackRank = rank + lightIndex;
  41093. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41094. }
  41095. if (!defines["SHADOWS"]) {
  41096. if (defines["SHADOW" + lightIndex]) {
  41097. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41098. }
  41099. if (defines["SHADOWPCF" + lightIndex]) {
  41100. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41101. }
  41102. if (defines["SHADOWPCSS" + lightIndex]) {
  41103. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41104. }
  41105. if (defines["SHADOWPOISSON" + lightIndex]) {
  41106. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41107. }
  41108. if (defines["SHADOWESM" + lightIndex]) {
  41109. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41110. }
  41111. }
  41112. }
  41113. return lightFallbackRank++;
  41114. };
  41115. /**
  41116. * Prepares the list of attributes required for morph targets according to the effect defines.
  41117. * @param attribs The current list of supported attribs
  41118. * @param mesh The mesh to prepare the morph targets attributes for
  41119. * @param defines The current Defines of the effect
  41120. */
  41121. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41122. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41123. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41124. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41125. var manager = mesh.morphTargetManager;
  41126. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41127. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41128. for (var index = 0; index < influencers; index++) {
  41129. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41130. if (normal) {
  41131. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41132. }
  41133. if (tangent) {
  41134. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41135. }
  41136. if (attribs.length > maxAttributesCount) {
  41137. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41138. }
  41139. }
  41140. }
  41141. };
  41142. /**
  41143. * Prepares the list of attributes required for bones according to the effect defines.
  41144. * @param attribs The current list of supported attribs
  41145. * @param mesh The mesh to prepare the bones attributes for
  41146. * @param defines The current Defines of the effect
  41147. * @param fallbacks The current efffect fallback strategy
  41148. */
  41149. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41150. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41151. fallbacks.addCPUSkinningFallback(0, mesh);
  41152. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41153. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41154. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41155. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41156. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41157. }
  41158. }
  41159. };
  41160. /**
  41161. * Prepares the list of attributes required for instances according to the effect defines.
  41162. * @param attribs The current list of supported attribs
  41163. * @param defines The current Defines of the effect
  41164. */
  41165. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41166. if (defines["INSTANCES"]) {
  41167. attribs.push("world0");
  41168. attribs.push("world1");
  41169. attribs.push("world2");
  41170. attribs.push("world3");
  41171. }
  41172. };
  41173. /**
  41174. * Binds the light shadow information to the effect for the given mesh.
  41175. * @param light The light containing the generator
  41176. * @param scene The scene the lights belongs to
  41177. * @param mesh The mesh we are binding the information to render
  41178. * @param lightIndex The light index in the effect used to render the mesh
  41179. * @param effect The effect we are binding the data to
  41180. */
  41181. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41182. if (light.shadowEnabled && mesh.receiveShadows) {
  41183. var shadowGenerator = light.getShadowGenerator();
  41184. if (shadowGenerator) {
  41185. shadowGenerator.bindShadowLight(lightIndex, effect);
  41186. }
  41187. }
  41188. };
  41189. /**
  41190. * Binds the light information to the effect.
  41191. * @param light The light containing the generator
  41192. * @param effect The effect we are binding the data to
  41193. * @param lightIndex The light index in the effect used to render
  41194. */
  41195. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41196. light.transferToEffect(effect, lightIndex + "");
  41197. };
  41198. /**
  41199. * Binds the lights information from the scene to the effect for the given mesh.
  41200. * @param scene The scene the lights belongs to
  41201. * @param mesh The mesh we are binding the information to render
  41202. * @param effect The effect we are binding the data to
  41203. * @param defines The generated defines for the effect
  41204. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41205. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41206. */
  41207. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41208. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41209. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41210. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41211. for (var i = 0; i < len; i++) {
  41212. var light = mesh._lightSources[i];
  41213. var iAsString = i.toString();
  41214. var scaledIntensity = light.getScaledIntensity();
  41215. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41216. MaterialHelper.BindLightProperties(light, effect, i);
  41217. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41218. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41219. if (defines["SPECULARTERM"]) {
  41220. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41221. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41222. }
  41223. // Shadows
  41224. if (scene.shadowsEnabled) {
  41225. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41226. }
  41227. light._uniformBuffer.update();
  41228. }
  41229. };
  41230. /**
  41231. * Binds the fog information from the scene to the effect for the given mesh.
  41232. * @param scene The scene the lights belongs to
  41233. * @param mesh The mesh we are binding the information to render
  41234. * @param effect The effect we are binding the data to
  41235. */
  41236. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41237. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41238. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41239. effect.setColor3("vFogColor", scene.fogColor);
  41240. }
  41241. };
  41242. /**
  41243. * Binds the bones information from the mesh to the effect.
  41244. * @param mesh The mesh we are binding the information to render
  41245. * @param effect The effect we are binding the data to
  41246. */
  41247. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41248. if (!effect || !mesh) {
  41249. return;
  41250. }
  41251. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41252. mesh.computeBonesUsingShaders = false;
  41253. }
  41254. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41255. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41256. if (matrices) {
  41257. effect.setMatrices("mBones", matrices);
  41258. }
  41259. }
  41260. };
  41261. /**
  41262. * Binds the morph targets information from the mesh to the effect.
  41263. * @param abstractMesh The mesh we are binding the information to render
  41264. * @param effect The effect we are binding the data to
  41265. */
  41266. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41267. var manager = abstractMesh.morphTargetManager;
  41268. if (!abstractMesh || !manager) {
  41269. return;
  41270. }
  41271. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41272. };
  41273. /**
  41274. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41275. * @param defines The generated defines used in the effect
  41276. * @param effect The effect we are binding the data to
  41277. * @param scene The scene we are willing to render with logarithmic scale for
  41278. */
  41279. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41280. if (defines["LOGARITHMICDEPTH"]) {
  41281. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41282. }
  41283. };
  41284. /**
  41285. * Binds the clip plane information from the scene to the effect.
  41286. * @param scene The scene the clip plane information are extracted from
  41287. * @param effect The effect we are binding the data to
  41288. */
  41289. MaterialHelper.BindClipPlane = function (effect, scene) {
  41290. if (scene.clipPlane) {
  41291. var clipPlane = scene.clipPlane;
  41292. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41293. }
  41294. if (scene.clipPlane2) {
  41295. var clipPlane = scene.clipPlane2;
  41296. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41297. }
  41298. if (scene.clipPlane3) {
  41299. var clipPlane = scene.clipPlane3;
  41300. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41301. }
  41302. if (scene.clipPlane4) {
  41303. var clipPlane = scene.clipPlane4;
  41304. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41305. }
  41306. };
  41307. return MaterialHelper;
  41308. }());
  41309. BABYLON.MaterialHelper = MaterialHelper;
  41310. })(BABYLON || (BABYLON = {}));
  41311. //# sourceMappingURL=babylon.materialHelper.js.map
  41312. var BABYLON;
  41313. (function (BABYLON) {
  41314. var PushMaterial = /** @class */ (function (_super) {
  41315. __extends(PushMaterial, _super);
  41316. function PushMaterial(name, scene) {
  41317. var _this = _super.call(this, name, scene) || this;
  41318. _this._normalMatrix = new BABYLON.Matrix();
  41319. _this.storeEffectOnSubMeshes = true;
  41320. return _this;
  41321. }
  41322. PushMaterial.prototype.getEffect = function () {
  41323. return this._activeEffect;
  41324. };
  41325. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41326. if (!mesh) {
  41327. return false;
  41328. }
  41329. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41330. return true;
  41331. }
  41332. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41333. };
  41334. /**
  41335. * Binds the given world matrix to the active effect
  41336. *
  41337. * @param world the matrix to bind
  41338. */
  41339. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41340. this._activeEffect.setMatrix("world", world);
  41341. };
  41342. /**
  41343. * Binds the given normal matrix to the active effect
  41344. *
  41345. * @param normalMatrix the matrix to bind
  41346. */
  41347. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41348. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41349. };
  41350. PushMaterial.prototype.bind = function (world, mesh) {
  41351. if (!mesh) {
  41352. return;
  41353. }
  41354. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41355. };
  41356. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41357. if (effect === void 0) { effect = null; }
  41358. _super.prototype._afterBind.call(this, mesh);
  41359. this.getScene()._cachedEffect = effect;
  41360. };
  41361. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41362. if (visibility === void 0) { visibility = 1; }
  41363. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41364. };
  41365. return PushMaterial;
  41366. }(BABYLON.Material));
  41367. BABYLON.PushMaterial = PushMaterial;
  41368. })(BABYLON || (BABYLON = {}));
  41369. //# sourceMappingURL=babylon.pushMaterial.js.map
  41370. var BABYLON;
  41371. (function (BABYLON) {
  41372. /** @hidden */
  41373. var StandardMaterialDefines = /** @class */ (function (_super) {
  41374. __extends(StandardMaterialDefines, _super);
  41375. function StandardMaterialDefines() {
  41376. var _this = _super.call(this) || this;
  41377. _this.MAINUV1 = false;
  41378. _this.MAINUV2 = false;
  41379. _this.DIFFUSE = false;
  41380. _this.DIFFUSEDIRECTUV = 0;
  41381. _this.AMBIENT = false;
  41382. _this.AMBIENTDIRECTUV = 0;
  41383. _this.OPACITY = false;
  41384. _this.OPACITYDIRECTUV = 0;
  41385. _this.OPACITYRGB = false;
  41386. _this.REFLECTION = false;
  41387. _this.EMISSIVE = false;
  41388. _this.EMISSIVEDIRECTUV = 0;
  41389. _this.SPECULAR = false;
  41390. _this.SPECULARDIRECTUV = 0;
  41391. _this.BUMP = false;
  41392. _this.BUMPDIRECTUV = 0;
  41393. _this.PARALLAX = false;
  41394. _this.PARALLAXOCCLUSION = false;
  41395. _this.SPECULAROVERALPHA = false;
  41396. _this.CLIPPLANE = false;
  41397. _this.CLIPPLANE2 = false;
  41398. _this.CLIPPLANE3 = false;
  41399. _this.CLIPPLANE4 = false;
  41400. _this.ALPHATEST = false;
  41401. _this.DEPTHPREPASS = false;
  41402. _this.ALPHAFROMDIFFUSE = false;
  41403. _this.POINTSIZE = false;
  41404. _this.FOG = false;
  41405. _this.SPECULARTERM = false;
  41406. _this.DIFFUSEFRESNEL = false;
  41407. _this.OPACITYFRESNEL = false;
  41408. _this.REFLECTIONFRESNEL = false;
  41409. _this.REFRACTIONFRESNEL = false;
  41410. _this.EMISSIVEFRESNEL = false;
  41411. _this.FRESNEL = false;
  41412. _this.NORMAL = false;
  41413. _this.UV1 = false;
  41414. _this.UV2 = false;
  41415. _this.VERTEXCOLOR = false;
  41416. _this.VERTEXALPHA = false;
  41417. _this.NUM_BONE_INFLUENCERS = 0;
  41418. _this.BonesPerMesh = 0;
  41419. _this.INSTANCES = false;
  41420. _this.GLOSSINESS = false;
  41421. _this.ROUGHNESS = false;
  41422. _this.EMISSIVEASILLUMINATION = false;
  41423. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41424. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41425. _this.LIGHTMAP = false;
  41426. _this.LIGHTMAPDIRECTUV = 0;
  41427. _this.OBJECTSPACE_NORMALMAP = false;
  41428. _this.USELIGHTMAPASSHADOWMAP = false;
  41429. _this.REFLECTIONMAP_3D = false;
  41430. _this.REFLECTIONMAP_SPHERICAL = false;
  41431. _this.REFLECTIONMAP_PLANAR = false;
  41432. _this.REFLECTIONMAP_CUBIC = false;
  41433. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41434. _this.REFLECTIONMAP_PROJECTION = false;
  41435. _this.REFLECTIONMAP_SKYBOX = false;
  41436. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41437. _this.REFLECTIONMAP_EXPLICIT = false;
  41438. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41439. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41440. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41441. _this.INVERTCUBICMAP = false;
  41442. _this.LOGARITHMICDEPTH = false;
  41443. _this.REFRACTION = false;
  41444. _this.REFRACTIONMAP_3D = false;
  41445. _this.REFLECTIONOVERALPHA = false;
  41446. _this.TWOSIDEDLIGHTING = false;
  41447. _this.SHADOWFLOAT = false;
  41448. _this.MORPHTARGETS = false;
  41449. _this.MORPHTARGETS_NORMAL = false;
  41450. _this.MORPHTARGETS_TANGENT = false;
  41451. _this.NUM_MORPH_INFLUENCERS = 0;
  41452. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41453. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41454. _this.IMAGEPROCESSING = false;
  41455. _this.VIGNETTE = false;
  41456. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41457. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41458. _this.TONEMAPPING = false;
  41459. _this.TONEMAPPING_ACES = false;
  41460. _this.CONTRAST = false;
  41461. _this.COLORCURVES = false;
  41462. _this.COLORGRADING = false;
  41463. _this.COLORGRADING3D = false;
  41464. _this.SAMPLER3DGREENDEPTH = false;
  41465. _this.SAMPLER3DBGRMAP = false;
  41466. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41467. /**
  41468. * If the reflection texture on this material is in linear color space
  41469. * @hidden
  41470. */
  41471. _this.IS_REFLECTION_LINEAR = false;
  41472. /**
  41473. * If the refraction texture on this material is in linear color space
  41474. * @hidden
  41475. */
  41476. _this.IS_REFRACTION_LINEAR = false;
  41477. _this.EXPOSURE = false;
  41478. _this.rebuild();
  41479. return _this;
  41480. }
  41481. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41482. var modes = [
  41483. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41484. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41485. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41486. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41487. ];
  41488. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41489. var mode = modes_1[_i];
  41490. this[mode] = (mode === modeToEnable);
  41491. }
  41492. };
  41493. return StandardMaterialDefines;
  41494. }(BABYLON.MaterialDefines));
  41495. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41496. var StandardMaterial = /** @class */ (function (_super) {
  41497. __extends(StandardMaterial, _super);
  41498. function StandardMaterial(name, scene) {
  41499. var _this = _super.call(this, name, scene) || this;
  41500. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41501. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41502. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41503. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41504. _this.specularPower = 64;
  41505. _this._useAlphaFromDiffuseTexture = false;
  41506. _this._useEmissiveAsIllumination = false;
  41507. _this._linkEmissiveWithDiffuse = false;
  41508. _this._useSpecularOverAlpha = false;
  41509. _this._useReflectionOverAlpha = false;
  41510. _this._disableLighting = false;
  41511. _this._useObjectSpaceNormalMap = false;
  41512. _this._useParallax = false;
  41513. _this._useParallaxOcclusion = false;
  41514. _this.parallaxScaleBias = 0.05;
  41515. _this._roughness = 0;
  41516. _this.indexOfRefraction = 0.98;
  41517. _this.invertRefractionY = true;
  41518. /**
  41519. * Defines the alpha limits in alpha test mode
  41520. */
  41521. _this.alphaCutOff = 0.4;
  41522. _this._useLightmapAsShadowmap = false;
  41523. _this._useReflectionFresnelFromSpecular = false;
  41524. _this._useGlossinessFromSpecularMapAlpha = false;
  41525. _this._maxSimultaneousLights = 4;
  41526. /**
  41527. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41528. */
  41529. _this._invertNormalMapX = false;
  41530. /**
  41531. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41532. */
  41533. _this._invertNormalMapY = false;
  41534. /**
  41535. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41536. */
  41537. _this._twoSidedLighting = false;
  41538. _this._renderTargets = new BABYLON.SmartArray(16);
  41539. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41540. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41541. // Setup the default processing configuration to the scene.
  41542. _this._attachImageProcessingConfiguration(null);
  41543. _this.getRenderTargetTextures = function () {
  41544. _this._renderTargets.reset();
  41545. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41546. _this._renderTargets.push(_this._reflectionTexture);
  41547. }
  41548. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41549. _this._renderTargets.push(_this._refractionTexture);
  41550. }
  41551. return _this._renderTargets;
  41552. };
  41553. return _this;
  41554. }
  41555. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41556. /**
  41557. * Gets the image processing configuration used either in this material.
  41558. */
  41559. get: function () {
  41560. return this._imageProcessingConfiguration;
  41561. },
  41562. /**
  41563. * Sets the Default image processing configuration used either in the this material.
  41564. *
  41565. * If sets to null, the scene one is in use.
  41566. */
  41567. set: function (value) {
  41568. this._attachImageProcessingConfiguration(value);
  41569. // Ensure the effect will be rebuilt.
  41570. this._markAllSubMeshesAsTexturesDirty();
  41571. },
  41572. enumerable: true,
  41573. configurable: true
  41574. });
  41575. /**
  41576. * Attaches a new image processing configuration to the Standard Material.
  41577. * @param configuration
  41578. */
  41579. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41580. var _this = this;
  41581. if (configuration === this._imageProcessingConfiguration) {
  41582. return;
  41583. }
  41584. // Detaches observer.
  41585. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41586. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41587. }
  41588. // Pick the scene configuration if needed.
  41589. if (!configuration) {
  41590. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41591. }
  41592. else {
  41593. this._imageProcessingConfiguration = configuration;
  41594. }
  41595. // Attaches observer.
  41596. if (this._imageProcessingConfiguration) {
  41597. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41598. _this._markAllSubMeshesAsImageProcessingDirty();
  41599. });
  41600. }
  41601. };
  41602. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41603. /**
  41604. * Gets wether the color curves effect is enabled.
  41605. */
  41606. get: function () {
  41607. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41608. },
  41609. /**
  41610. * Sets wether the color curves effect is enabled.
  41611. */
  41612. set: function (value) {
  41613. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41614. },
  41615. enumerable: true,
  41616. configurable: true
  41617. });
  41618. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41619. /**
  41620. * Gets wether the color grading effect is enabled.
  41621. */
  41622. get: function () {
  41623. return this.imageProcessingConfiguration.colorGradingEnabled;
  41624. },
  41625. /**
  41626. * Gets wether the color grading effect is enabled.
  41627. */
  41628. set: function (value) {
  41629. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41630. },
  41631. enumerable: true,
  41632. configurable: true
  41633. });
  41634. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41635. /**
  41636. * Gets wether tonemapping is enabled or not.
  41637. */
  41638. get: function () {
  41639. return this._imageProcessingConfiguration.toneMappingEnabled;
  41640. },
  41641. /**
  41642. * Sets wether tonemapping is enabled or not
  41643. */
  41644. set: function (value) {
  41645. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41646. },
  41647. enumerable: true,
  41648. configurable: true
  41649. });
  41650. ;
  41651. ;
  41652. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41653. /**
  41654. * The camera exposure used on this material.
  41655. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41656. * This corresponds to a photographic exposure.
  41657. */
  41658. get: function () {
  41659. return this._imageProcessingConfiguration.exposure;
  41660. },
  41661. /**
  41662. * The camera exposure used on this material.
  41663. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41664. * This corresponds to a photographic exposure.
  41665. */
  41666. set: function (value) {
  41667. this._imageProcessingConfiguration.exposure = value;
  41668. },
  41669. enumerable: true,
  41670. configurable: true
  41671. });
  41672. ;
  41673. ;
  41674. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41675. /**
  41676. * Gets The camera contrast used on this material.
  41677. */
  41678. get: function () {
  41679. return this._imageProcessingConfiguration.contrast;
  41680. },
  41681. /**
  41682. * Sets The camera contrast used on this material.
  41683. */
  41684. set: function (value) {
  41685. this._imageProcessingConfiguration.contrast = value;
  41686. },
  41687. enumerable: true,
  41688. configurable: true
  41689. });
  41690. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41691. /**
  41692. * Gets the Color Grading 2D Lookup Texture.
  41693. */
  41694. get: function () {
  41695. return this._imageProcessingConfiguration.colorGradingTexture;
  41696. },
  41697. /**
  41698. * Sets the Color Grading 2D Lookup Texture.
  41699. */
  41700. set: function (value) {
  41701. this._imageProcessingConfiguration.colorGradingTexture = value;
  41702. },
  41703. enumerable: true,
  41704. configurable: true
  41705. });
  41706. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41707. /**
  41708. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41709. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41710. * 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;
  41711. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41712. */
  41713. get: function () {
  41714. return this._imageProcessingConfiguration.colorCurves;
  41715. },
  41716. /**
  41717. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41718. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41719. * 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;
  41720. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41721. */
  41722. set: function (value) {
  41723. this._imageProcessingConfiguration.colorCurves = value;
  41724. },
  41725. enumerable: true,
  41726. configurable: true
  41727. });
  41728. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41729. /**
  41730. * Gets a boolean indicating that current material needs to register RTT
  41731. */
  41732. get: function () {
  41733. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41734. return true;
  41735. }
  41736. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41737. return true;
  41738. }
  41739. return false;
  41740. },
  41741. enumerable: true,
  41742. configurable: true
  41743. });
  41744. StandardMaterial.prototype.getClassName = function () {
  41745. return "StandardMaterial";
  41746. };
  41747. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41748. get: function () {
  41749. return this._useLogarithmicDepth;
  41750. },
  41751. set: function (value) {
  41752. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41753. this._markAllSubMeshesAsMiscDirty();
  41754. },
  41755. enumerable: true,
  41756. configurable: true
  41757. });
  41758. StandardMaterial.prototype.needAlphaBlending = function () {
  41759. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41760. };
  41761. StandardMaterial.prototype.needAlphaTesting = function () {
  41762. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41763. };
  41764. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41765. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41766. };
  41767. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41768. return this._diffuseTexture;
  41769. };
  41770. /**
  41771. * Child classes can use it to update shaders
  41772. */
  41773. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41774. if (useInstances === void 0) { useInstances = false; }
  41775. if (subMesh.effect && this.isFrozen) {
  41776. if (this._wasPreviouslyReady) {
  41777. return true;
  41778. }
  41779. }
  41780. if (!subMesh._materialDefines) {
  41781. subMesh._materialDefines = new StandardMaterialDefines();
  41782. }
  41783. var scene = this.getScene();
  41784. var defines = subMesh._materialDefines;
  41785. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41786. if (defines._renderId === scene.getRenderId()) {
  41787. return true;
  41788. }
  41789. }
  41790. var engine = scene.getEngine();
  41791. // Lights
  41792. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41793. // Textures
  41794. if (defines._areTexturesDirty) {
  41795. defines._needUVs = false;
  41796. defines.MAINUV1 = false;
  41797. defines.MAINUV2 = false;
  41798. if (scene.texturesEnabled) {
  41799. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41800. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41801. return false;
  41802. }
  41803. else {
  41804. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41805. }
  41806. }
  41807. else {
  41808. defines.DIFFUSE = false;
  41809. }
  41810. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41811. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41812. return false;
  41813. }
  41814. else {
  41815. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41816. }
  41817. }
  41818. else {
  41819. defines.AMBIENT = false;
  41820. }
  41821. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41822. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41823. return false;
  41824. }
  41825. else {
  41826. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41827. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41828. }
  41829. }
  41830. else {
  41831. defines.OPACITY = false;
  41832. }
  41833. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41834. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41835. return false;
  41836. }
  41837. else {
  41838. defines._needNormals = true;
  41839. defines.REFLECTION = true;
  41840. defines.ROUGHNESS = (this._roughness > 0);
  41841. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41842. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41843. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41844. switch (this._reflectionTexture.coordinatesMode) {
  41845. case BABYLON.Texture.EXPLICIT_MODE:
  41846. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41847. break;
  41848. case BABYLON.Texture.PLANAR_MODE:
  41849. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41850. break;
  41851. case BABYLON.Texture.PROJECTION_MODE:
  41852. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41853. break;
  41854. case BABYLON.Texture.SKYBOX_MODE:
  41855. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41856. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  41857. break;
  41858. case BABYLON.Texture.SPHERICAL_MODE:
  41859. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41860. break;
  41861. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41862. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41863. break;
  41864. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41865. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41866. break;
  41867. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41868. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41869. break;
  41870. case BABYLON.Texture.CUBIC_MODE:
  41871. case BABYLON.Texture.INVCUBIC_MODE:
  41872. default:
  41873. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41874. break;
  41875. }
  41876. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41877. }
  41878. }
  41879. else {
  41880. defines.REFLECTION = false;
  41881. }
  41882. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41883. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41884. return false;
  41885. }
  41886. else {
  41887. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41888. }
  41889. }
  41890. else {
  41891. defines.EMISSIVE = false;
  41892. }
  41893. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41894. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41895. return false;
  41896. }
  41897. else {
  41898. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41899. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41900. }
  41901. }
  41902. else {
  41903. defines.LIGHTMAP = false;
  41904. }
  41905. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41906. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41907. return false;
  41908. }
  41909. else {
  41910. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41911. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41912. }
  41913. }
  41914. else {
  41915. defines.SPECULAR = false;
  41916. }
  41917. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41918. // Bump texure can not be not blocking.
  41919. if (!this._bumpTexture.isReady()) {
  41920. return false;
  41921. }
  41922. else {
  41923. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41924. defines.PARALLAX = this._useParallax;
  41925. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41926. }
  41927. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41928. }
  41929. else {
  41930. defines.BUMP = false;
  41931. }
  41932. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41933. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41934. return false;
  41935. }
  41936. else {
  41937. defines._needUVs = true;
  41938. defines.REFRACTION = true;
  41939. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41940. }
  41941. }
  41942. else {
  41943. defines.REFRACTION = false;
  41944. }
  41945. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41946. }
  41947. else {
  41948. defines.DIFFUSE = false;
  41949. defines.AMBIENT = false;
  41950. defines.OPACITY = false;
  41951. defines.REFLECTION = false;
  41952. defines.EMISSIVE = false;
  41953. defines.LIGHTMAP = false;
  41954. defines.BUMP = false;
  41955. defines.REFRACTION = false;
  41956. }
  41957. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41958. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41959. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41960. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41961. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41962. }
  41963. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41964. if (!this._imageProcessingConfiguration.isReady()) {
  41965. return false;
  41966. }
  41967. this._imageProcessingConfiguration.prepareDefines(defines);
  41968. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41969. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41970. }
  41971. if (defines._areFresnelDirty) {
  41972. if (StandardMaterial.FresnelEnabled) {
  41973. // Fresnel
  41974. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41975. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41976. this._reflectionFresnelParameters) {
  41977. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41978. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41979. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41980. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41981. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41982. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41983. defines._needNormals = true;
  41984. defines.FRESNEL = true;
  41985. }
  41986. }
  41987. else {
  41988. defines.FRESNEL = false;
  41989. }
  41990. }
  41991. // Misc.
  41992. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41993. // Attribs
  41994. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41995. // Values that need to be evaluated on every frame
  41996. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41997. // Get correct effect
  41998. if (defines.isDirty) {
  41999. defines.markAsProcessed();
  42000. scene.resetCachedMaterial();
  42001. // Fallbacks
  42002. var fallbacks = new BABYLON.EffectFallbacks();
  42003. if (defines.REFLECTION) {
  42004. fallbacks.addFallback(0, "REFLECTION");
  42005. }
  42006. if (defines.SPECULAR) {
  42007. fallbacks.addFallback(0, "SPECULAR");
  42008. }
  42009. if (defines.BUMP) {
  42010. fallbacks.addFallback(0, "BUMP");
  42011. }
  42012. if (defines.PARALLAX) {
  42013. fallbacks.addFallback(1, "PARALLAX");
  42014. }
  42015. if (defines.PARALLAXOCCLUSION) {
  42016. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42017. }
  42018. if (defines.SPECULAROVERALPHA) {
  42019. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42020. }
  42021. if (defines.FOG) {
  42022. fallbacks.addFallback(1, "FOG");
  42023. }
  42024. if (defines.POINTSIZE) {
  42025. fallbacks.addFallback(0, "POINTSIZE");
  42026. }
  42027. if (defines.LOGARITHMICDEPTH) {
  42028. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42029. }
  42030. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42031. if (defines.SPECULARTERM) {
  42032. fallbacks.addFallback(0, "SPECULARTERM");
  42033. }
  42034. if (defines.DIFFUSEFRESNEL) {
  42035. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42036. }
  42037. if (defines.OPACITYFRESNEL) {
  42038. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42039. }
  42040. if (defines.REFLECTIONFRESNEL) {
  42041. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42042. }
  42043. if (defines.EMISSIVEFRESNEL) {
  42044. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42045. }
  42046. if (defines.FRESNEL) {
  42047. fallbacks.addFallback(4, "FRESNEL");
  42048. }
  42049. //Attributes
  42050. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42051. if (defines.NORMAL) {
  42052. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42053. }
  42054. if (defines.UV1) {
  42055. attribs.push(BABYLON.VertexBuffer.UVKind);
  42056. }
  42057. if (defines.UV2) {
  42058. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42059. }
  42060. if (defines.VERTEXCOLOR) {
  42061. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42062. }
  42063. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42064. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42065. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42066. var shaderName = "default";
  42067. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42068. "vFogInfos", "vFogColor", "pointSize",
  42069. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42070. "mBones",
  42071. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42072. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42073. "vReflectionPosition", "vReflectionSize",
  42074. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42075. ];
  42076. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42077. var uniformBuffers = ["Material", "Scene"];
  42078. if (BABYLON.ImageProcessingConfiguration) {
  42079. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42080. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42081. }
  42082. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42083. uniformsNames: uniforms,
  42084. uniformBuffersNames: uniformBuffers,
  42085. samplers: samplers,
  42086. defines: defines,
  42087. maxSimultaneousLights: this._maxSimultaneousLights
  42088. });
  42089. if (this.customShaderNameResolve) {
  42090. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42091. }
  42092. var join = defines.toString();
  42093. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42094. attributes: attribs,
  42095. uniformsNames: uniforms,
  42096. uniformBuffersNames: uniformBuffers,
  42097. samplers: samplers,
  42098. defines: join,
  42099. fallbacks: fallbacks,
  42100. onCompiled: this.onCompiled,
  42101. onError: this.onError,
  42102. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42103. }, engine), defines);
  42104. this.buildUniformLayout();
  42105. }
  42106. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42107. return false;
  42108. }
  42109. defines._renderId = scene.getRenderId();
  42110. this._wasPreviouslyReady = true;
  42111. return true;
  42112. };
  42113. StandardMaterial.prototype.buildUniformLayout = function () {
  42114. // Order is important !
  42115. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42116. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42117. this._uniformBuffer.addUniform("opacityParts", 4);
  42118. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42119. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42120. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42121. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42122. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42123. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42124. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42125. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42126. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42127. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42128. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42129. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42130. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42131. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42132. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42133. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42134. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42135. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42136. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42137. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42138. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42139. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42140. this._uniformBuffer.addUniform("specularMatrix", 16);
  42141. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42142. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42143. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42144. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42145. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42146. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42147. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42148. this._uniformBuffer.addUniform("pointSize", 1);
  42149. this._uniformBuffer.create();
  42150. };
  42151. StandardMaterial.prototype.unbind = function () {
  42152. if (this._activeEffect) {
  42153. var needFlag = false;
  42154. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42155. this._activeEffect.setTexture("reflection2DSampler", null);
  42156. needFlag = true;
  42157. }
  42158. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42159. this._activeEffect.setTexture("refraction2DSampler", null);
  42160. needFlag = true;
  42161. }
  42162. if (needFlag) {
  42163. this._markAllSubMeshesAsTexturesDirty();
  42164. }
  42165. }
  42166. _super.prototype.unbind.call(this);
  42167. };
  42168. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42169. var scene = this.getScene();
  42170. var defines = subMesh._materialDefines;
  42171. if (!defines) {
  42172. return;
  42173. }
  42174. var effect = subMesh.effect;
  42175. if (!effect) {
  42176. return;
  42177. }
  42178. this._activeEffect = effect;
  42179. // Matrices
  42180. this.bindOnlyWorldMatrix(world);
  42181. // Normal Matrix
  42182. if (defines.OBJECTSPACE_NORMALMAP) {
  42183. world.toNormalMatrix(this._normalMatrix);
  42184. this.bindOnlyNormalMatrix(this._normalMatrix);
  42185. }
  42186. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42187. // Bones
  42188. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42189. if (mustRebind) {
  42190. this._uniformBuffer.bindToEffect(effect, "Material");
  42191. this.bindViewProjection(effect);
  42192. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42193. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42194. // Fresnel
  42195. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42196. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42197. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42198. }
  42199. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42200. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42201. }
  42202. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42203. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42204. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42205. }
  42206. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42207. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42208. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42209. }
  42210. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42211. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42212. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42213. }
  42214. }
  42215. // Textures
  42216. if (scene.texturesEnabled) {
  42217. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42218. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42219. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42220. if (this._diffuseTexture.hasAlpha) {
  42221. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42222. }
  42223. }
  42224. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42225. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42226. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42227. }
  42228. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42229. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42230. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42231. }
  42232. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42233. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42234. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42235. if (this._reflectionTexture.boundingBoxSize) {
  42236. var cubeTexture = this._reflectionTexture;
  42237. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42238. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42239. }
  42240. }
  42241. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42242. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42243. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42244. }
  42245. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42246. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42247. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42248. }
  42249. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42250. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42251. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42252. }
  42253. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42254. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42255. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42256. if (scene._mirroredCameraPosition) {
  42257. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42258. }
  42259. else {
  42260. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42261. }
  42262. }
  42263. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42264. var depth = 1.0;
  42265. if (!this._refractionTexture.isCube) {
  42266. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42267. if (this._refractionTexture.depth) {
  42268. depth = this._refractionTexture.depth;
  42269. }
  42270. }
  42271. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42272. }
  42273. }
  42274. // Point size
  42275. if (this.pointsCloud) {
  42276. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42277. }
  42278. if (defines.SPECULARTERM) {
  42279. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42280. }
  42281. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42282. // Diffuse
  42283. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42284. }
  42285. // Textures
  42286. if (scene.texturesEnabled) {
  42287. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42288. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42289. }
  42290. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42291. effect.setTexture("ambientSampler", this._ambientTexture);
  42292. }
  42293. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42294. effect.setTexture("opacitySampler", this._opacityTexture);
  42295. }
  42296. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42297. if (this._reflectionTexture.isCube) {
  42298. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42299. }
  42300. else {
  42301. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42302. }
  42303. }
  42304. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42305. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42306. }
  42307. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42308. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42309. }
  42310. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42311. effect.setTexture("specularSampler", this._specularTexture);
  42312. }
  42313. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42314. effect.setTexture("bumpSampler", this._bumpTexture);
  42315. }
  42316. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42317. var depth = 1.0;
  42318. if (this._refractionTexture.isCube) {
  42319. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42320. }
  42321. else {
  42322. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42323. }
  42324. }
  42325. }
  42326. // Clip plane
  42327. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42328. // Colors
  42329. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42330. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42331. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42332. }
  42333. if (mustRebind || !this.isFrozen) {
  42334. // Lights
  42335. if (scene.lightsEnabled && !this._disableLighting) {
  42336. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42337. }
  42338. // View
  42339. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42340. this.bindView(effect);
  42341. }
  42342. // Fog
  42343. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42344. // Morph targets
  42345. if (defines.NUM_MORPH_INFLUENCERS) {
  42346. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42347. }
  42348. // Log. depth
  42349. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42350. // image processing
  42351. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42352. this._imageProcessingConfiguration.bind(this._activeEffect);
  42353. }
  42354. }
  42355. this._uniformBuffer.update();
  42356. this._afterBind(mesh, this._activeEffect);
  42357. };
  42358. StandardMaterial.prototype.getAnimatables = function () {
  42359. var results = [];
  42360. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42361. results.push(this._diffuseTexture);
  42362. }
  42363. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42364. results.push(this._ambientTexture);
  42365. }
  42366. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42367. results.push(this._opacityTexture);
  42368. }
  42369. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42370. results.push(this._reflectionTexture);
  42371. }
  42372. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42373. results.push(this._emissiveTexture);
  42374. }
  42375. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42376. results.push(this._specularTexture);
  42377. }
  42378. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42379. results.push(this._bumpTexture);
  42380. }
  42381. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42382. results.push(this._lightmapTexture);
  42383. }
  42384. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42385. results.push(this._refractionTexture);
  42386. }
  42387. return results;
  42388. };
  42389. StandardMaterial.prototype.getActiveTextures = function () {
  42390. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42391. if (this._diffuseTexture) {
  42392. activeTextures.push(this._diffuseTexture);
  42393. }
  42394. if (this._ambientTexture) {
  42395. activeTextures.push(this._ambientTexture);
  42396. }
  42397. if (this._opacityTexture) {
  42398. activeTextures.push(this._opacityTexture);
  42399. }
  42400. if (this._reflectionTexture) {
  42401. activeTextures.push(this._reflectionTexture);
  42402. }
  42403. if (this._emissiveTexture) {
  42404. activeTextures.push(this._emissiveTexture);
  42405. }
  42406. if (this._specularTexture) {
  42407. activeTextures.push(this._specularTexture);
  42408. }
  42409. if (this._bumpTexture) {
  42410. activeTextures.push(this._bumpTexture);
  42411. }
  42412. if (this._lightmapTexture) {
  42413. activeTextures.push(this._lightmapTexture);
  42414. }
  42415. if (this._refractionTexture) {
  42416. activeTextures.push(this._refractionTexture);
  42417. }
  42418. return activeTextures;
  42419. };
  42420. StandardMaterial.prototype.hasTexture = function (texture) {
  42421. if (_super.prototype.hasTexture.call(this, texture)) {
  42422. return true;
  42423. }
  42424. if (this._diffuseTexture === texture) {
  42425. return true;
  42426. }
  42427. if (this._ambientTexture === texture) {
  42428. return true;
  42429. }
  42430. if (this._opacityTexture === texture) {
  42431. return true;
  42432. }
  42433. if (this._reflectionTexture === texture) {
  42434. return true;
  42435. }
  42436. if (this._emissiveTexture === texture) {
  42437. return true;
  42438. }
  42439. if (this._specularTexture === texture) {
  42440. return true;
  42441. }
  42442. if (this._bumpTexture === texture) {
  42443. return true;
  42444. }
  42445. if (this._lightmapTexture === texture) {
  42446. return true;
  42447. }
  42448. if (this._refractionTexture === texture) {
  42449. return true;
  42450. }
  42451. return false;
  42452. };
  42453. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42454. if (forceDisposeTextures) {
  42455. if (this._diffuseTexture) {
  42456. this._diffuseTexture.dispose();
  42457. }
  42458. if (this._ambientTexture) {
  42459. this._ambientTexture.dispose();
  42460. }
  42461. if (this._opacityTexture) {
  42462. this._opacityTexture.dispose();
  42463. }
  42464. if (this._reflectionTexture) {
  42465. this._reflectionTexture.dispose();
  42466. }
  42467. if (this._emissiveTexture) {
  42468. this._emissiveTexture.dispose();
  42469. }
  42470. if (this._specularTexture) {
  42471. this._specularTexture.dispose();
  42472. }
  42473. if (this._bumpTexture) {
  42474. this._bumpTexture.dispose();
  42475. }
  42476. if (this._lightmapTexture) {
  42477. this._lightmapTexture.dispose();
  42478. }
  42479. if (this._refractionTexture) {
  42480. this._refractionTexture.dispose();
  42481. }
  42482. }
  42483. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42484. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42485. }
  42486. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42487. };
  42488. StandardMaterial.prototype.clone = function (name) {
  42489. var _this = this;
  42490. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42491. result.name = name;
  42492. result.id = name;
  42493. return result;
  42494. };
  42495. StandardMaterial.prototype.serialize = function () {
  42496. return BABYLON.SerializationHelper.Serialize(this);
  42497. };
  42498. // Statics
  42499. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42500. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42501. };
  42502. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42503. get: function () {
  42504. return StandardMaterial._DiffuseTextureEnabled;
  42505. },
  42506. set: function (value) {
  42507. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42508. return;
  42509. }
  42510. StandardMaterial._DiffuseTextureEnabled = value;
  42511. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42512. },
  42513. enumerable: true,
  42514. configurable: true
  42515. });
  42516. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42517. get: function () {
  42518. return StandardMaterial._AmbientTextureEnabled;
  42519. },
  42520. set: function (value) {
  42521. if (StandardMaterial._AmbientTextureEnabled === value) {
  42522. return;
  42523. }
  42524. StandardMaterial._AmbientTextureEnabled = value;
  42525. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42526. },
  42527. enumerable: true,
  42528. configurable: true
  42529. });
  42530. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42531. get: function () {
  42532. return StandardMaterial._OpacityTextureEnabled;
  42533. },
  42534. set: function (value) {
  42535. if (StandardMaterial._OpacityTextureEnabled === value) {
  42536. return;
  42537. }
  42538. StandardMaterial._OpacityTextureEnabled = value;
  42539. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42540. },
  42541. enumerable: true,
  42542. configurable: true
  42543. });
  42544. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42545. get: function () {
  42546. return StandardMaterial._ReflectionTextureEnabled;
  42547. },
  42548. set: function (value) {
  42549. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42550. return;
  42551. }
  42552. StandardMaterial._ReflectionTextureEnabled = value;
  42553. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42554. },
  42555. enumerable: true,
  42556. configurable: true
  42557. });
  42558. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42559. get: function () {
  42560. return StandardMaterial._EmissiveTextureEnabled;
  42561. },
  42562. set: function (value) {
  42563. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42564. return;
  42565. }
  42566. StandardMaterial._EmissiveTextureEnabled = value;
  42567. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42568. },
  42569. enumerable: true,
  42570. configurable: true
  42571. });
  42572. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42573. get: function () {
  42574. return StandardMaterial._SpecularTextureEnabled;
  42575. },
  42576. set: function (value) {
  42577. if (StandardMaterial._SpecularTextureEnabled === value) {
  42578. return;
  42579. }
  42580. StandardMaterial._SpecularTextureEnabled = value;
  42581. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42582. },
  42583. enumerable: true,
  42584. configurable: true
  42585. });
  42586. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42587. get: function () {
  42588. return StandardMaterial._BumpTextureEnabled;
  42589. },
  42590. set: function (value) {
  42591. if (StandardMaterial._BumpTextureEnabled === value) {
  42592. return;
  42593. }
  42594. StandardMaterial._BumpTextureEnabled = value;
  42595. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42596. },
  42597. enumerable: true,
  42598. configurable: true
  42599. });
  42600. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42601. get: function () {
  42602. return StandardMaterial._LightmapTextureEnabled;
  42603. },
  42604. set: function (value) {
  42605. if (StandardMaterial._LightmapTextureEnabled === value) {
  42606. return;
  42607. }
  42608. StandardMaterial._LightmapTextureEnabled = value;
  42609. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42610. },
  42611. enumerable: true,
  42612. configurable: true
  42613. });
  42614. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42615. get: function () {
  42616. return StandardMaterial._RefractionTextureEnabled;
  42617. },
  42618. set: function (value) {
  42619. if (StandardMaterial._RefractionTextureEnabled === value) {
  42620. return;
  42621. }
  42622. StandardMaterial._RefractionTextureEnabled = value;
  42623. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42624. },
  42625. enumerable: true,
  42626. configurable: true
  42627. });
  42628. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42629. get: function () {
  42630. return StandardMaterial._ColorGradingTextureEnabled;
  42631. },
  42632. set: function (value) {
  42633. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42634. return;
  42635. }
  42636. StandardMaterial._ColorGradingTextureEnabled = value;
  42637. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42638. },
  42639. enumerable: true,
  42640. configurable: true
  42641. });
  42642. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42643. get: function () {
  42644. return StandardMaterial._FresnelEnabled;
  42645. },
  42646. set: function (value) {
  42647. if (StandardMaterial._FresnelEnabled === value) {
  42648. return;
  42649. }
  42650. StandardMaterial._FresnelEnabled = value;
  42651. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42652. },
  42653. enumerable: true,
  42654. configurable: true
  42655. });
  42656. // Flags used to enable or disable a type of texture for all Standard Materials
  42657. StandardMaterial._DiffuseTextureEnabled = true;
  42658. StandardMaterial._AmbientTextureEnabled = true;
  42659. StandardMaterial._OpacityTextureEnabled = true;
  42660. StandardMaterial._ReflectionTextureEnabled = true;
  42661. StandardMaterial._EmissiveTextureEnabled = true;
  42662. StandardMaterial._SpecularTextureEnabled = true;
  42663. StandardMaterial._BumpTextureEnabled = true;
  42664. StandardMaterial._LightmapTextureEnabled = true;
  42665. StandardMaterial._RefractionTextureEnabled = true;
  42666. StandardMaterial._ColorGradingTextureEnabled = true;
  42667. StandardMaterial._FresnelEnabled = true;
  42668. __decorate([
  42669. BABYLON.serializeAsTexture("diffuseTexture")
  42670. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42671. __decorate([
  42672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42673. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42674. __decorate([
  42675. BABYLON.serializeAsTexture("ambientTexture")
  42676. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42677. __decorate([
  42678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42679. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42680. __decorate([
  42681. BABYLON.serializeAsTexture("opacityTexture")
  42682. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42683. __decorate([
  42684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42685. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42686. __decorate([
  42687. BABYLON.serializeAsTexture("reflectionTexture")
  42688. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42689. __decorate([
  42690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42691. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42692. __decorate([
  42693. BABYLON.serializeAsTexture("emissiveTexture")
  42694. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42695. __decorate([
  42696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42697. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42698. __decorate([
  42699. BABYLON.serializeAsTexture("specularTexture")
  42700. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42701. __decorate([
  42702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42703. ], StandardMaterial.prototype, "specularTexture", void 0);
  42704. __decorate([
  42705. BABYLON.serializeAsTexture("bumpTexture")
  42706. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42707. __decorate([
  42708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42709. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42710. __decorate([
  42711. BABYLON.serializeAsTexture("lightmapTexture")
  42712. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42713. __decorate([
  42714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42715. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42716. __decorate([
  42717. BABYLON.serializeAsTexture("refractionTexture")
  42718. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42719. __decorate([
  42720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42721. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42722. __decorate([
  42723. BABYLON.serializeAsColor3("ambient")
  42724. ], StandardMaterial.prototype, "ambientColor", void 0);
  42725. __decorate([
  42726. BABYLON.serializeAsColor3("diffuse")
  42727. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42728. __decorate([
  42729. BABYLON.serializeAsColor3("specular")
  42730. ], StandardMaterial.prototype, "specularColor", void 0);
  42731. __decorate([
  42732. BABYLON.serializeAsColor3("emissive")
  42733. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42734. __decorate([
  42735. BABYLON.serialize()
  42736. ], StandardMaterial.prototype, "specularPower", void 0);
  42737. __decorate([
  42738. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42739. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42740. __decorate([
  42741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42742. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42743. __decorate([
  42744. BABYLON.serialize("useEmissiveAsIllumination")
  42745. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42746. __decorate([
  42747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42748. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42749. __decorate([
  42750. BABYLON.serialize("linkEmissiveWithDiffuse")
  42751. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42752. __decorate([
  42753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42754. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42755. __decorate([
  42756. BABYLON.serialize("useSpecularOverAlpha")
  42757. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42758. __decorate([
  42759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42760. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42761. __decorate([
  42762. BABYLON.serialize("useReflectionOverAlpha")
  42763. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42764. __decorate([
  42765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42766. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42767. __decorate([
  42768. BABYLON.serialize("disableLighting")
  42769. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42770. __decorate([
  42771. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42772. ], StandardMaterial.prototype, "disableLighting", void 0);
  42773. __decorate([
  42774. BABYLON.serialize("useObjectSpaceNormalMap")
  42775. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42776. __decorate([
  42777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42778. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42779. __decorate([
  42780. BABYLON.serialize("useParallax")
  42781. ], StandardMaterial.prototype, "_useParallax", void 0);
  42782. __decorate([
  42783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42784. ], StandardMaterial.prototype, "useParallax", void 0);
  42785. __decorate([
  42786. BABYLON.serialize("useParallaxOcclusion")
  42787. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42788. __decorate([
  42789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42790. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42791. __decorate([
  42792. BABYLON.serialize()
  42793. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42794. __decorate([
  42795. BABYLON.serialize("roughness")
  42796. ], StandardMaterial.prototype, "_roughness", void 0);
  42797. __decorate([
  42798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42799. ], StandardMaterial.prototype, "roughness", void 0);
  42800. __decorate([
  42801. BABYLON.serialize()
  42802. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42803. __decorate([
  42804. BABYLON.serialize()
  42805. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42806. __decorate([
  42807. BABYLON.serialize()
  42808. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42809. __decorate([
  42810. BABYLON.serialize("useLightmapAsShadowmap")
  42811. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42812. __decorate([
  42813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42814. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42815. __decorate([
  42816. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42817. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42818. __decorate([
  42819. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42820. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42821. __decorate([
  42822. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42823. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42824. __decorate([
  42825. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42826. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42827. __decorate([
  42828. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42829. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42830. __decorate([
  42831. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42832. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42833. __decorate([
  42834. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42835. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42836. __decorate([
  42837. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42838. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42839. __decorate([
  42840. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42841. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42842. __decorate([
  42843. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42844. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42845. __decorate([
  42846. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42847. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42848. __decorate([
  42849. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42850. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42851. __decorate([
  42852. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42853. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42854. __decorate([
  42855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42856. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42857. __decorate([
  42858. BABYLON.serialize("maxSimultaneousLights")
  42859. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42860. __decorate([
  42861. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42862. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42863. __decorate([
  42864. BABYLON.serialize("invertNormalMapX")
  42865. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42866. __decorate([
  42867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42868. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42869. __decorate([
  42870. BABYLON.serialize("invertNormalMapY")
  42871. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42872. __decorate([
  42873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42874. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42875. __decorate([
  42876. BABYLON.serialize("twoSidedLighting")
  42877. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42878. __decorate([
  42879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42880. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42881. __decorate([
  42882. BABYLON.serialize()
  42883. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42884. return StandardMaterial;
  42885. }(BABYLON.PushMaterial));
  42886. BABYLON.StandardMaterial = StandardMaterial;
  42887. })(BABYLON || (BABYLON = {}));
  42888. //# sourceMappingURL=babylon.standardMaterial.js.map
  42889. var BABYLON;
  42890. (function (BABYLON) {
  42891. /**
  42892. * Class representing spherical polynomial coefficients to the 3rd degree
  42893. */
  42894. var SphericalPolynomial = /** @class */ (function () {
  42895. function SphericalPolynomial() {
  42896. /**
  42897. * The x coefficients of the spherical polynomial
  42898. */
  42899. this.x = BABYLON.Vector3.Zero();
  42900. /**
  42901. * The y coefficients of the spherical polynomial
  42902. */
  42903. this.y = BABYLON.Vector3.Zero();
  42904. /**
  42905. * The z coefficients of the spherical polynomial
  42906. */
  42907. this.z = BABYLON.Vector3.Zero();
  42908. /**
  42909. * The xx coefficients of the spherical polynomial
  42910. */
  42911. this.xx = BABYLON.Vector3.Zero();
  42912. /**
  42913. * The yy coefficients of the spherical polynomial
  42914. */
  42915. this.yy = BABYLON.Vector3.Zero();
  42916. /**
  42917. * The zz coefficients of the spherical polynomial
  42918. */
  42919. this.zz = BABYLON.Vector3.Zero();
  42920. /**
  42921. * The xy coefficients of the spherical polynomial
  42922. */
  42923. this.xy = BABYLON.Vector3.Zero();
  42924. /**
  42925. * The yz coefficients of the spherical polynomial
  42926. */
  42927. this.yz = BABYLON.Vector3.Zero();
  42928. /**
  42929. * The zx coefficients of the spherical polynomial
  42930. */
  42931. this.zx = BABYLON.Vector3.Zero();
  42932. }
  42933. /**
  42934. * Adds an ambient color to the spherical polynomial
  42935. * @param color the color to add
  42936. */
  42937. SphericalPolynomial.prototype.addAmbient = function (color) {
  42938. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42939. this.xx = this.xx.add(colorVector);
  42940. this.yy = this.yy.add(colorVector);
  42941. this.zz = this.zz.add(colorVector);
  42942. };
  42943. /**
  42944. * Scales the spherical polynomial by the given amount
  42945. * @param scale the amount to scale
  42946. */
  42947. SphericalPolynomial.prototype.scale = function (scale) {
  42948. this.x = this.x.scale(scale);
  42949. this.y = this.y.scale(scale);
  42950. this.z = this.z.scale(scale);
  42951. this.xx = this.xx.scale(scale);
  42952. this.yy = this.yy.scale(scale);
  42953. this.zz = this.zz.scale(scale);
  42954. this.yz = this.yz.scale(scale);
  42955. this.zx = this.zx.scale(scale);
  42956. this.xy = this.xy.scale(scale);
  42957. };
  42958. /**
  42959. * Gets the spherical polynomial from harmonics
  42960. * @param harmonics the spherical harmonics
  42961. * @returns the spherical polynomial
  42962. */
  42963. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42964. var result = new SphericalPolynomial();
  42965. result.x = harmonics.l11.scale(1.02333);
  42966. result.y = harmonics.l1_1.scale(1.02333);
  42967. result.z = harmonics.l10.scale(1.02333);
  42968. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42969. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42970. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42971. result.yz = harmonics.l2_1.scale(0.858086);
  42972. result.zx = harmonics.l21.scale(0.858086);
  42973. result.xy = harmonics.l2_2.scale(0.858086);
  42974. result.scale(1.0 / Math.PI);
  42975. return result;
  42976. };
  42977. /**
  42978. * Constructs a spherical polynomial from an array.
  42979. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42980. * @returns the spherical polynomial
  42981. */
  42982. SphericalPolynomial.FromArray = function (data) {
  42983. var sp = new SphericalPolynomial();
  42984. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42985. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42986. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42987. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42988. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42989. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42990. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42991. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42992. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  42993. return sp;
  42994. };
  42995. return SphericalPolynomial;
  42996. }());
  42997. BABYLON.SphericalPolynomial = SphericalPolynomial;
  42998. /**
  42999. * Class representing spherical harmonics coefficients to the 3rd degree
  43000. */
  43001. var SphericalHarmonics = /** @class */ (function () {
  43002. function SphericalHarmonics() {
  43003. /**
  43004. * The l0,0 coefficients of the spherical harmonics
  43005. */
  43006. this.l00 = BABYLON.Vector3.Zero();
  43007. /**
  43008. * The l1,-1 coefficients of the spherical harmonics
  43009. */
  43010. this.l1_1 = BABYLON.Vector3.Zero();
  43011. /**
  43012. * The l1,0 coefficients of the spherical harmonics
  43013. */
  43014. this.l10 = BABYLON.Vector3.Zero();
  43015. /**
  43016. * The l1,1 coefficients of the spherical harmonics
  43017. */
  43018. this.l11 = BABYLON.Vector3.Zero();
  43019. /**
  43020. * The l2,-2 coefficients of the spherical harmonics
  43021. */
  43022. this.l2_2 = BABYLON.Vector3.Zero();
  43023. /**
  43024. * The l2,-1 coefficients of the spherical harmonics
  43025. */
  43026. this.l2_1 = BABYLON.Vector3.Zero();
  43027. /**
  43028. * The l2,0 coefficients of the spherical harmonics
  43029. */
  43030. this.l20 = BABYLON.Vector3.Zero();
  43031. /**
  43032. * The l2,1 coefficients of the spherical harmonics
  43033. */
  43034. this.l21 = BABYLON.Vector3.Zero();
  43035. /**
  43036. * The l2,2 coefficients of the spherical harmonics
  43037. */
  43038. this.lL22 = BABYLON.Vector3.Zero();
  43039. }
  43040. /**
  43041. * Adds a light to the spherical harmonics
  43042. * @param direction the direction of the light
  43043. * @param color the color of the light
  43044. * @param deltaSolidAngle the delta solid angle of the light
  43045. */
  43046. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43047. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43048. var c = colorVector.scale(deltaSolidAngle);
  43049. this.l00 = this.l00.add(c.scale(0.282095));
  43050. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43051. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43052. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43053. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43054. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43055. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43056. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43057. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43058. };
  43059. /**
  43060. * Scales the spherical harmonics by the given amount
  43061. * @param scale the amount to scale
  43062. */
  43063. SphericalHarmonics.prototype.scale = function (scale) {
  43064. this.l00 = this.l00.scale(scale);
  43065. this.l1_1 = this.l1_1.scale(scale);
  43066. this.l10 = this.l10.scale(scale);
  43067. this.l11 = this.l11.scale(scale);
  43068. this.l2_2 = this.l2_2.scale(scale);
  43069. this.l2_1 = this.l2_1.scale(scale);
  43070. this.l20 = this.l20.scale(scale);
  43071. this.l21 = this.l21.scale(scale);
  43072. this.lL22 = this.lL22.scale(scale);
  43073. };
  43074. /**
  43075. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43076. *
  43077. * ```
  43078. * E_lm = A_l * L_lm
  43079. * ```
  43080. *
  43081. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43082. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43083. * the scaling factors are given in equation 9.
  43084. */
  43085. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43086. // Constant (Band 0)
  43087. this.l00 = this.l00.scale(3.141593);
  43088. // Linear (Band 1)
  43089. this.l1_1 = this.l1_1.scale(2.094395);
  43090. this.l10 = this.l10.scale(2.094395);
  43091. this.l11 = this.l11.scale(2.094395);
  43092. // Quadratic (Band 2)
  43093. this.l2_2 = this.l2_2.scale(0.785398);
  43094. this.l2_1 = this.l2_1.scale(0.785398);
  43095. this.l20 = this.l20.scale(0.785398);
  43096. this.l21 = this.l21.scale(0.785398);
  43097. this.lL22 = this.lL22.scale(0.785398);
  43098. };
  43099. /**
  43100. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43101. *
  43102. * ```
  43103. * L = (1/pi) * E * rho
  43104. * ```
  43105. *
  43106. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43107. */
  43108. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43109. this.scale(1.0 / Math.PI);
  43110. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43111. // (The pixel shader must apply albedo after texture fetches, etc).
  43112. };
  43113. /**
  43114. * Gets the spherical harmonics from polynomial
  43115. * @param polynomial the spherical polynomial
  43116. * @returns the spherical harmonics
  43117. */
  43118. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43119. var result = new SphericalHarmonics();
  43120. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43121. result.l1_1 = polynomial.y.scale(0.977204);
  43122. result.l10 = polynomial.z.scale(0.977204);
  43123. result.l11 = polynomial.x.scale(0.977204);
  43124. result.l2_2 = polynomial.xy.scale(1.16538);
  43125. result.l2_1 = polynomial.yz.scale(1.16538);
  43126. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43127. result.l21 = polynomial.zx.scale(1.16538);
  43128. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43129. result.scale(Math.PI);
  43130. return result;
  43131. };
  43132. /**
  43133. * Constructs a spherical harmonics from an array.
  43134. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43135. * @returns the spherical harmonics
  43136. */
  43137. SphericalHarmonics.FromArray = function (data) {
  43138. var sh = new SphericalHarmonics();
  43139. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43140. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43141. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43142. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43143. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43144. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43145. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43146. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43147. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43148. return sh;
  43149. };
  43150. return SphericalHarmonics;
  43151. }());
  43152. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43153. })(BABYLON || (BABYLON = {}));
  43154. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43155. var BABYLON;
  43156. (function (BABYLON) {
  43157. var FileFaceOrientation = /** @class */ (function () {
  43158. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43159. this.name = name;
  43160. this.worldAxisForNormal = worldAxisForNormal;
  43161. this.worldAxisForFileX = worldAxisForFileX;
  43162. this.worldAxisForFileY = worldAxisForFileY;
  43163. }
  43164. return FileFaceOrientation;
  43165. }());
  43166. ;
  43167. /**
  43168. * Helper class dealing with the extraction of spherical polynomial dataArray
  43169. * from a cube map.
  43170. */
  43171. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43172. function CubeMapToSphericalPolynomialTools() {
  43173. }
  43174. /**
  43175. * Converts a texture to the according Spherical Polynomial data.
  43176. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43177. *
  43178. * @param texture The texture to extract the information from.
  43179. * @return The Spherical Polynomial data.
  43180. */
  43181. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43182. if (!texture.isCube) {
  43183. // Only supports cube Textures currently.
  43184. return null;
  43185. }
  43186. var size = texture.getSize().width;
  43187. var right = texture.readPixels(0);
  43188. var left = texture.readPixels(1);
  43189. var up;
  43190. var down;
  43191. if (texture.isRenderTarget) {
  43192. up = texture.readPixels(3);
  43193. down = texture.readPixels(2);
  43194. }
  43195. else {
  43196. up = texture.readPixels(2);
  43197. down = texture.readPixels(3);
  43198. }
  43199. var front = texture.readPixels(4);
  43200. var back = texture.readPixels(5);
  43201. var gammaSpace = texture.gammaSpace;
  43202. // Always read as RGBA.
  43203. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43204. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43205. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43206. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43207. }
  43208. var cubeInfo = {
  43209. size: size,
  43210. right: right,
  43211. left: left,
  43212. up: up,
  43213. down: down,
  43214. front: front,
  43215. back: back,
  43216. format: format,
  43217. type: type,
  43218. gammaSpace: gammaSpace,
  43219. };
  43220. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43221. };
  43222. /**
  43223. * Converts a cubemap to the according Spherical Polynomial data.
  43224. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43225. *
  43226. * @param cubeInfo The Cube map to extract the information from.
  43227. * @return The Spherical Polynomial data.
  43228. */
  43229. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43230. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43231. var totalSolidAngle = 0.0;
  43232. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43233. var du = 2.0 / cubeInfo.size;
  43234. var dv = du;
  43235. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43236. var minUV = du * 0.5 - 1.0;
  43237. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43238. var fileFace = this.FileFaces[faceIndex];
  43239. var dataArray = cubeInfo[fileFace.name];
  43240. var v = minUV;
  43241. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43242. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43243. // Because SP is still linear, so summation is fine in that basis.
  43244. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43245. for (var y = 0; y < cubeInfo.size; y++) {
  43246. var u = minUV;
  43247. for (var x = 0; x < cubeInfo.size; x++) {
  43248. // World direction (not normalised)
  43249. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43250. worldDirection.normalize();
  43251. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43252. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43253. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43254. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43255. // Handle Integer types.
  43256. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43257. r /= 255;
  43258. g /= 255;
  43259. b /= 255;
  43260. }
  43261. // Handle Gamma space textures.
  43262. if (cubeInfo.gammaSpace) {
  43263. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43264. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43265. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43266. }
  43267. var color = new BABYLON.Color3(r, g, b);
  43268. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43269. totalSolidAngle += deltaSolidAngle;
  43270. u += du;
  43271. }
  43272. v += dv;
  43273. }
  43274. }
  43275. // Solid angle for entire sphere is 4*pi
  43276. var sphereSolidAngle = 4.0 * Math.PI;
  43277. // Adjust the solid angle to allow for how many faces we processed.
  43278. var facesProcessed = 6.0;
  43279. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43280. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43281. // This is needed because the numerical integration over the cube uses a
  43282. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43283. // and also to compensate for accumulative error due to float precision in the summation.
  43284. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43285. sphericalHarmonics.scale(correctionFactor);
  43286. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43287. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43288. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43289. };
  43290. CubeMapToSphericalPolynomialTools.FileFaces = [
  43291. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43292. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43293. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43294. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43295. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43296. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43297. ];
  43298. return CubeMapToSphericalPolynomialTools;
  43299. }());
  43300. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43301. })(BABYLON || (BABYLON = {}));
  43302. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43303. var BABYLON;
  43304. (function (BABYLON) {
  43305. /**
  43306. * Manages the defines for the PBR Material.
  43307. * @hiddenChildren
  43308. */
  43309. var PBRMaterialDefines = /** @class */ (function (_super) {
  43310. __extends(PBRMaterialDefines, _super);
  43311. /**
  43312. * Initializes the PBR Material defines.
  43313. */
  43314. function PBRMaterialDefines() {
  43315. var _this = _super.call(this) || this;
  43316. _this.PBR = true;
  43317. _this.MAINUV1 = false;
  43318. _this.MAINUV2 = false;
  43319. _this.UV1 = false;
  43320. _this.UV2 = false;
  43321. _this.ALBEDO = false;
  43322. _this.ALBEDODIRECTUV = 0;
  43323. _this.VERTEXCOLOR = false;
  43324. _this.AMBIENT = false;
  43325. _this.AMBIENTDIRECTUV = 0;
  43326. _this.AMBIENTINGRAYSCALE = false;
  43327. _this.OPACITY = false;
  43328. _this.VERTEXALPHA = false;
  43329. _this.OPACITYDIRECTUV = 0;
  43330. _this.OPACITYRGB = false;
  43331. _this.ALPHATEST = false;
  43332. _this.DEPTHPREPASS = false;
  43333. _this.ALPHABLEND = false;
  43334. _this.ALPHAFROMALBEDO = false;
  43335. _this.ALPHATESTVALUE = "0.5";
  43336. _this.SPECULAROVERALPHA = false;
  43337. _this.RADIANCEOVERALPHA = false;
  43338. _this.ALPHAFRESNEL = false;
  43339. _this.LINEARALPHAFRESNEL = false;
  43340. _this.PREMULTIPLYALPHA = false;
  43341. _this.EMISSIVE = false;
  43342. _this.EMISSIVEDIRECTUV = 0;
  43343. _this.REFLECTIVITY = false;
  43344. _this.REFLECTIVITYDIRECTUV = 0;
  43345. _this.SPECULARTERM = false;
  43346. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43347. _this.MICROSURFACEAUTOMATIC = false;
  43348. _this.LODBASEDMICROSFURACE = false;
  43349. _this.MICROSURFACEMAP = false;
  43350. _this.MICROSURFACEMAPDIRECTUV = 0;
  43351. _this.METALLICWORKFLOW = false;
  43352. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43353. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43354. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43355. _this.AOSTOREINMETALMAPRED = false;
  43356. _this.ENVIRONMENTBRDF = false;
  43357. _this.NORMAL = false;
  43358. _this.TANGENT = false;
  43359. _this.BUMP = false;
  43360. _this.BUMPDIRECTUV = 0;
  43361. _this.OBJECTSPACE_NORMALMAP = false;
  43362. _this.PARALLAX = false;
  43363. _this.PARALLAXOCCLUSION = false;
  43364. _this.NORMALXYSCALE = true;
  43365. _this.LIGHTMAP = false;
  43366. _this.LIGHTMAPDIRECTUV = 0;
  43367. _this.USELIGHTMAPASSHADOWMAP = false;
  43368. _this.GAMMALIGHTMAP = false;
  43369. _this.REFLECTION = false;
  43370. _this.REFLECTIONMAP_3D = false;
  43371. _this.REFLECTIONMAP_SPHERICAL = false;
  43372. _this.REFLECTIONMAP_PLANAR = false;
  43373. _this.REFLECTIONMAP_CUBIC = false;
  43374. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43375. _this.REFLECTIONMAP_PROJECTION = false;
  43376. _this.REFLECTIONMAP_SKYBOX = false;
  43377. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43378. _this.REFLECTIONMAP_EXPLICIT = false;
  43379. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43380. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43381. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43382. _this.INVERTCUBICMAP = false;
  43383. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43384. _this.USESPHERICALINVERTEX = false;
  43385. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43386. _this.LODINREFLECTIONALPHA = false;
  43387. _this.GAMMAREFLECTION = false;
  43388. _this.RGBDREFLECTION = false;
  43389. _this.RADIANCEOCCLUSION = false;
  43390. _this.HORIZONOCCLUSION = false;
  43391. _this.REFRACTION = false;
  43392. _this.REFRACTIONMAP_3D = false;
  43393. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43394. _this.LODINREFRACTIONALPHA = false;
  43395. _this.GAMMAREFRACTION = false;
  43396. _this.RGBDREFRACTION = false;
  43397. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43398. _this.INSTANCES = false;
  43399. _this.NUM_BONE_INFLUENCERS = 0;
  43400. _this.BonesPerMesh = 0;
  43401. _this.NONUNIFORMSCALING = false;
  43402. _this.MORPHTARGETS = false;
  43403. _this.MORPHTARGETS_NORMAL = false;
  43404. _this.MORPHTARGETS_TANGENT = false;
  43405. _this.NUM_MORPH_INFLUENCERS = 0;
  43406. _this.IMAGEPROCESSING = false;
  43407. _this.VIGNETTE = false;
  43408. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43409. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43410. _this.TONEMAPPING = false;
  43411. _this.TONEMAPPING_ACES = false;
  43412. _this.CONTRAST = false;
  43413. _this.COLORCURVES = false;
  43414. _this.COLORGRADING = false;
  43415. _this.COLORGRADING3D = false;
  43416. _this.SAMPLER3DGREENDEPTH = false;
  43417. _this.SAMPLER3DBGRMAP = false;
  43418. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43419. _this.EXPOSURE = false;
  43420. _this.USEPHYSICALLIGHTFALLOFF = false;
  43421. _this.USEGLTFLIGHTFALLOFF = false;
  43422. _this.TWOSIDEDLIGHTING = false;
  43423. _this.SHADOWFLOAT = false;
  43424. _this.CLIPPLANE = false;
  43425. _this.CLIPPLANE2 = false;
  43426. _this.CLIPPLANE3 = false;
  43427. _this.CLIPPLANE4 = false;
  43428. _this.POINTSIZE = false;
  43429. _this.FOG = false;
  43430. _this.LOGARITHMICDEPTH = false;
  43431. _this.FORCENORMALFORWARD = false;
  43432. _this.SPECULARAA = false;
  43433. _this.UNLIT = false;
  43434. _this.rebuild();
  43435. return _this;
  43436. }
  43437. /**
  43438. * Resets the PBR Material defines.
  43439. */
  43440. PBRMaterialDefines.prototype.reset = function () {
  43441. _super.prototype.reset.call(this);
  43442. this.ALPHATESTVALUE = "0.5";
  43443. this.PBR = true;
  43444. };
  43445. return PBRMaterialDefines;
  43446. }(BABYLON.MaterialDefines));
  43447. /**
  43448. * The Physically based material base class of BJS.
  43449. *
  43450. * This offers the main features of a standard PBR material.
  43451. * For more information, please refer to the documentation :
  43452. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43453. */
  43454. var PBRBaseMaterial = /** @class */ (function (_super) {
  43455. __extends(PBRBaseMaterial, _super);
  43456. /**
  43457. * Instantiates a new PBRMaterial instance.
  43458. *
  43459. * @param name The material name
  43460. * @param scene The scene the material will be use in.
  43461. */
  43462. function PBRBaseMaterial(name, scene) {
  43463. var _this = _super.call(this, name, scene) || this;
  43464. /**
  43465. * Intensity of the direct lights e.g. the four lights available in your scene.
  43466. * This impacts both the direct diffuse and specular highlights.
  43467. */
  43468. _this._directIntensity = 1.0;
  43469. /**
  43470. * Intensity of the emissive part of the material.
  43471. * This helps controlling the emissive effect without modifying the emissive color.
  43472. */
  43473. _this._emissiveIntensity = 1.0;
  43474. /**
  43475. * Intensity of the environment e.g. how much the environment will light the object
  43476. * either through harmonics for rough material or through the refelction for shiny ones.
  43477. */
  43478. _this._environmentIntensity = 1.0;
  43479. /**
  43480. * This is a special control allowing the reduction of the specular highlights coming from the
  43481. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43482. */
  43483. _this._specularIntensity = 1.0;
  43484. /**
  43485. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43486. */
  43487. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43488. /**
  43489. * Debug Control allowing disabling the bump map on this material.
  43490. */
  43491. _this._disableBumpMap = false;
  43492. /**
  43493. * AKA Occlusion Texture Intensity in other nomenclature.
  43494. */
  43495. _this._ambientTextureStrength = 1.0;
  43496. /**
  43497. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43498. * 1 means it completely occludes it
  43499. * 0 mean it has no impact
  43500. */
  43501. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43502. /**
  43503. * The color of a material in ambient lighting.
  43504. */
  43505. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43506. /**
  43507. * AKA Diffuse Color in other nomenclature.
  43508. */
  43509. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43510. /**
  43511. * AKA Specular Color in other nomenclature.
  43512. */
  43513. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43514. /**
  43515. * The color applied when light is reflected from a material.
  43516. */
  43517. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43518. /**
  43519. * The color applied when light is emitted from a material.
  43520. */
  43521. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43522. /**
  43523. * AKA Glossiness in other nomenclature.
  43524. */
  43525. _this._microSurface = 0.9;
  43526. /**
  43527. * source material index of refraction (IOR)' / 'destination material IOR.
  43528. */
  43529. _this._indexOfRefraction = 0.66;
  43530. /**
  43531. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43532. */
  43533. _this._invertRefractionY = false;
  43534. /**
  43535. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43536. * Materials half opaque for instance using refraction could benefit from this control.
  43537. */
  43538. _this._linkRefractionWithTransparency = false;
  43539. /**
  43540. * Specifies that the material will use the light map as a show map.
  43541. */
  43542. _this._useLightmapAsShadowmap = false;
  43543. /**
  43544. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43545. * makes the reflect vector face the model (under horizon).
  43546. */
  43547. _this._useHorizonOcclusion = true;
  43548. /**
  43549. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43550. * too much the area relying on ambient texture to define their ambient occlusion.
  43551. */
  43552. _this._useRadianceOcclusion = true;
  43553. /**
  43554. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43555. */
  43556. _this._useAlphaFromAlbedoTexture = false;
  43557. /**
  43558. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43559. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43560. */
  43561. _this._useSpecularOverAlpha = true;
  43562. /**
  43563. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43564. */
  43565. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43566. /**
  43567. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43568. */
  43569. _this._useRoughnessFromMetallicTextureAlpha = true;
  43570. /**
  43571. * Specifies if the metallic texture contains the roughness information in its green channel.
  43572. */
  43573. _this._useRoughnessFromMetallicTextureGreen = false;
  43574. /**
  43575. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43576. */
  43577. _this._useMetallnessFromMetallicTextureBlue = false;
  43578. /**
  43579. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43580. */
  43581. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43582. /**
  43583. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43584. */
  43585. _this._useAmbientInGrayScale = false;
  43586. /**
  43587. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43588. * The material will try to infer what glossiness each pixel should be.
  43589. */
  43590. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43591. /**
  43592. * Defines the falloff type used in this material.
  43593. * It by default is Physical.
  43594. */
  43595. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43596. /**
  43597. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43598. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43599. */
  43600. _this._useRadianceOverAlpha = true;
  43601. /**
  43602. * Allows using an object space normal map (instead of tangent space).
  43603. */
  43604. _this._useObjectSpaceNormalMap = false;
  43605. /**
  43606. * Allows using the bump map in parallax mode.
  43607. */
  43608. _this._useParallax = false;
  43609. /**
  43610. * Allows using the bump map in parallax occlusion mode.
  43611. */
  43612. _this._useParallaxOcclusion = false;
  43613. /**
  43614. * Controls the scale bias of the parallax mode.
  43615. */
  43616. _this._parallaxScaleBias = 0.05;
  43617. /**
  43618. * If sets to true, disables all the lights affecting the material.
  43619. */
  43620. _this._disableLighting = false;
  43621. /**
  43622. * Number of Simultaneous lights allowed on the material.
  43623. */
  43624. _this._maxSimultaneousLights = 4;
  43625. /**
  43626. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43627. */
  43628. _this._invertNormalMapX = false;
  43629. /**
  43630. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43631. */
  43632. _this._invertNormalMapY = false;
  43633. /**
  43634. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43635. */
  43636. _this._twoSidedLighting = false;
  43637. /**
  43638. * Defines the alpha limits in alpha test mode.
  43639. */
  43640. _this._alphaCutOff = 0.4;
  43641. /**
  43642. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43643. */
  43644. _this._forceAlphaTest = false;
  43645. /**
  43646. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43647. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43648. */
  43649. _this._useAlphaFresnel = false;
  43650. /**
  43651. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43652. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43653. */
  43654. _this._useLinearAlphaFresnel = false;
  43655. /**
  43656. * The transparency mode of the material.
  43657. */
  43658. _this._transparencyMode = null;
  43659. /**
  43660. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43661. * from cos thetav and roughness:
  43662. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43663. */
  43664. _this._environmentBRDFTexture = null;
  43665. /**
  43666. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43667. */
  43668. _this._forceIrradianceInFragment = false;
  43669. /**
  43670. * Force normal to face away from face.
  43671. */
  43672. _this._forceNormalForward = false;
  43673. /**
  43674. * Enables specular anti aliasing in the PBR shader.
  43675. * It will both interacts on the Geometry for analytical and IBL lighting.
  43676. * It also prefilter the roughness map based on the bump values.
  43677. */
  43678. _this._enableSpecularAntiAliasing = false;
  43679. /**
  43680. * Stores the available render targets.
  43681. */
  43682. _this._renderTargets = new BABYLON.SmartArray(16);
  43683. /**
  43684. * Sets the global ambient color for the material used in lighting calculations.
  43685. */
  43686. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43687. /**
  43688. * If set to true, no lighting calculations will be applied.
  43689. */
  43690. _this._unlit = false;
  43691. // Setup the default processing configuration to the scene.
  43692. _this._attachImageProcessingConfiguration(null);
  43693. _this.getRenderTargetTextures = function () {
  43694. _this._renderTargets.reset();
  43695. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43696. _this._renderTargets.push(_this._reflectionTexture);
  43697. }
  43698. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43699. _this._renderTargets.push(_this._refractionTexture);
  43700. }
  43701. return _this._renderTargets;
  43702. };
  43703. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43704. return _this;
  43705. }
  43706. /**
  43707. * Attaches a new image processing configuration to the PBR Material.
  43708. * @param configuration
  43709. */
  43710. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43711. var _this = this;
  43712. if (configuration === this._imageProcessingConfiguration) {
  43713. return;
  43714. }
  43715. // Detaches observer.
  43716. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43717. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43718. }
  43719. // Pick the scene configuration if needed.
  43720. if (!configuration) {
  43721. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43722. }
  43723. else {
  43724. this._imageProcessingConfiguration = configuration;
  43725. }
  43726. // Attaches observer.
  43727. if (this._imageProcessingConfiguration) {
  43728. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43729. _this._markAllSubMeshesAsImageProcessingDirty();
  43730. });
  43731. }
  43732. };
  43733. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43734. /**
  43735. * Gets a boolean indicating that current material needs to register RTT
  43736. */
  43737. get: function () {
  43738. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43739. return true;
  43740. }
  43741. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43742. return true;
  43743. }
  43744. return false;
  43745. },
  43746. enumerable: true,
  43747. configurable: true
  43748. });
  43749. /**
  43750. * Gets the name of the material class.
  43751. */
  43752. PBRBaseMaterial.prototype.getClassName = function () {
  43753. return "PBRBaseMaterial";
  43754. };
  43755. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43756. /**
  43757. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43758. */
  43759. get: function () {
  43760. return this._useLogarithmicDepth;
  43761. },
  43762. /**
  43763. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43764. */
  43765. set: function (value) {
  43766. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43767. },
  43768. enumerable: true,
  43769. configurable: true
  43770. });
  43771. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43772. /**
  43773. * Gets the current transparency mode.
  43774. */
  43775. get: function () {
  43776. return this._transparencyMode;
  43777. },
  43778. /**
  43779. * Sets the transparency mode of the material.
  43780. *
  43781. * | Value | Type | Description |
  43782. * | ----- | ----------------------------------- | ----------- |
  43783. * | 0 | OPAQUE | |
  43784. * | 1 | ALPHATEST | |
  43785. * | 2 | ALPHABLEND | |
  43786. * | 3 | ALPHATESTANDBLEND | |
  43787. *
  43788. */
  43789. set: function (value) {
  43790. if (this._transparencyMode === value) {
  43791. return;
  43792. }
  43793. this._transparencyMode = value;
  43794. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43795. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43796. },
  43797. enumerable: true,
  43798. configurable: true
  43799. });
  43800. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43801. /**
  43802. * Returns true if alpha blending should be disabled.
  43803. */
  43804. get: function () {
  43805. return (this._linkRefractionWithTransparency ||
  43806. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43807. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43808. },
  43809. enumerable: true,
  43810. configurable: true
  43811. });
  43812. /**
  43813. * Specifies whether or not this material should be rendered in alpha blend mode.
  43814. */
  43815. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43816. if (this._disableAlphaBlending) {
  43817. return false;
  43818. }
  43819. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43820. };
  43821. /**
  43822. * Specifies if the mesh will require alpha blending.
  43823. * @param mesh - BJS mesh.
  43824. */
  43825. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43826. if (this._disableAlphaBlending) {
  43827. return false;
  43828. }
  43829. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43830. };
  43831. /**
  43832. * Specifies whether or not this material should be rendered in alpha test mode.
  43833. */
  43834. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43835. if (this._forceAlphaTest) {
  43836. return true;
  43837. }
  43838. if (this._linkRefractionWithTransparency) {
  43839. return false;
  43840. }
  43841. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43842. };
  43843. /**
  43844. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43845. */
  43846. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43847. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43848. };
  43849. /**
  43850. * Gets the texture used for the alpha test.
  43851. */
  43852. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43853. return this._albedoTexture;
  43854. };
  43855. /**
  43856. * Specifies that the submesh is ready to be used.
  43857. * @param mesh - BJS mesh.
  43858. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43859. * @param useInstances - Specifies that instances should be used.
  43860. * @returns - boolean indicating that the submesh is ready or not.
  43861. */
  43862. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43863. if (subMesh.effect && this.isFrozen) {
  43864. if (this._wasPreviouslyReady) {
  43865. return true;
  43866. }
  43867. }
  43868. if (!subMesh._materialDefines) {
  43869. subMesh._materialDefines = new PBRMaterialDefines();
  43870. }
  43871. var defines = subMesh._materialDefines;
  43872. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43873. if (defines._renderId === this.getScene().getRenderId()) {
  43874. return true;
  43875. }
  43876. }
  43877. var scene = this.getScene();
  43878. var engine = scene.getEngine();
  43879. if (defines._areTexturesDirty) {
  43880. if (scene.texturesEnabled) {
  43881. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43882. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43883. return false;
  43884. }
  43885. }
  43886. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43887. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43888. return false;
  43889. }
  43890. }
  43891. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43892. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43893. return false;
  43894. }
  43895. }
  43896. var reflectionTexture = this._getReflectionTexture();
  43897. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43898. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43899. return false;
  43900. }
  43901. }
  43902. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43903. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43904. return false;
  43905. }
  43906. }
  43907. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43908. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43909. return false;
  43910. }
  43911. }
  43912. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43913. if (this._metallicTexture) {
  43914. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43915. return false;
  43916. }
  43917. }
  43918. else if (this._reflectivityTexture) {
  43919. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43920. return false;
  43921. }
  43922. }
  43923. if (this._microSurfaceTexture) {
  43924. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43925. return false;
  43926. }
  43927. }
  43928. }
  43929. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43930. // Bump texture cannot be not blocking.
  43931. if (!this._bumpTexture.isReady()) {
  43932. return false;
  43933. }
  43934. }
  43935. var refractionTexture = this._getRefractionTexture();
  43936. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43937. if (!refractionTexture.isReadyOrNotBlocking()) {
  43938. return false;
  43939. }
  43940. }
  43941. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43942. // This is blocking.
  43943. if (!this._environmentBRDFTexture.isReady()) {
  43944. return false;
  43945. }
  43946. }
  43947. }
  43948. }
  43949. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43950. if (!this._imageProcessingConfiguration.isReady()) {
  43951. return false;
  43952. }
  43953. }
  43954. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43955. mesh.createNormals(true);
  43956. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43957. }
  43958. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43959. if (effect) {
  43960. scene.resetCachedMaterial();
  43961. subMesh.setEffect(effect, defines);
  43962. this.buildUniformLayout();
  43963. }
  43964. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43965. return false;
  43966. }
  43967. defines._renderId = scene.getRenderId();
  43968. this._wasPreviouslyReady = true;
  43969. return true;
  43970. };
  43971. /**
  43972. * Specifies if the material uses metallic roughness workflow.
  43973. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43974. */
  43975. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43976. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43977. return true;
  43978. }
  43979. return false;
  43980. };
  43981. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43982. if (onCompiled === void 0) { onCompiled = null; }
  43983. if (onError === void 0) { onError = null; }
  43984. if (useInstances === void 0) { useInstances = null; }
  43985. if (useClipPlane === void 0) { useClipPlane = null; }
  43986. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43987. if (!defines.isDirty) {
  43988. return null;
  43989. }
  43990. defines.markAsProcessed();
  43991. var scene = this.getScene();
  43992. var engine = scene.getEngine();
  43993. // Fallbacks
  43994. var fallbacks = new BABYLON.EffectFallbacks();
  43995. var fallbackRank = 0;
  43996. if (defines.USESPHERICALINVERTEX) {
  43997. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43998. }
  43999. if (defines.FOG) {
  44000. fallbacks.addFallback(fallbackRank, "FOG");
  44001. }
  44002. if (defines.SPECULARAA) {
  44003. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44004. }
  44005. if (defines.POINTSIZE) {
  44006. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44007. }
  44008. if (defines.LOGARITHMICDEPTH) {
  44009. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44010. }
  44011. if (defines.PARALLAX) {
  44012. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44013. }
  44014. if (defines.PARALLAXOCCLUSION) {
  44015. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44016. }
  44017. if (defines.ENVIRONMENTBRDF) {
  44018. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44019. }
  44020. if (defines.TANGENT) {
  44021. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44022. }
  44023. if (defines.BUMP) {
  44024. fallbacks.addFallback(fallbackRank++, "BUMP");
  44025. }
  44026. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44027. if (defines.SPECULARTERM) {
  44028. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44029. }
  44030. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44031. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44032. }
  44033. if (defines.LIGHTMAP) {
  44034. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44035. }
  44036. if (defines.NORMAL) {
  44037. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44038. }
  44039. if (defines.AMBIENT) {
  44040. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44041. }
  44042. if (defines.EMISSIVE) {
  44043. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44044. }
  44045. if (defines.VERTEXCOLOR) {
  44046. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44047. }
  44048. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44049. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44050. }
  44051. if (defines.MORPHTARGETS) {
  44052. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44053. }
  44054. //Attributes
  44055. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44056. if (defines.NORMAL) {
  44057. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44058. }
  44059. if (defines.TANGENT) {
  44060. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44061. }
  44062. if (defines.UV1) {
  44063. attribs.push(BABYLON.VertexBuffer.UVKind);
  44064. }
  44065. if (defines.UV2) {
  44066. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44067. }
  44068. if (defines.VERTEXCOLOR) {
  44069. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44070. }
  44071. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44072. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44073. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44074. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44075. "vFogInfos", "vFogColor", "pointSize",
  44076. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44077. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44078. "mBones",
  44079. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44080. "vLightingIntensity",
  44081. "logarithmicDepthConstant",
  44082. "vSphericalX", "vSphericalY", "vSphericalZ",
  44083. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44084. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44085. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44086. "vTangentSpaceParams"
  44087. ];
  44088. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44089. "bumpSampler", "lightmapSampler", "opacitySampler",
  44090. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44091. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44092. "microSurfaceSampler", "environmentBrdfSampler"];
  44093. var uniformBuffers = ["Material", "Scene"];
  44094. if (BABYLON.ImageProcessingConfiguration) {
  44095. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44096. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44097. }
  44098. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44099. uniformsNames: uniforms,
  44100. uniformBuffersNames: uniformBuffers,
  44101. samplers: samplers,
  44102. defines: defines,
  44103. maxSimultaneousLights: this._maxSimultaneousLights
  44104. });
  44105. var join = defines.toString();
  44106. return engine.createEffect("pbr", {
  44107. attributes: attribs,
  44108. uniformsNames: uniforms,
  44109. uniformBuffersNames: uniformBuffers,
  44110. samplers: samplers,
  44111. defines: join,
  44112. fallbacks: fallbacks,
  44113. onCompiled: onCompiled,
  44114. onError: onError,
  44115. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44116. }, engine);
  44117. };
  44118. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44119. if (useInstances === void 0) { useInstances = null; }
  44120. if (useClipPlane === void 0) { useClipPlane = null; }
  44121. var scene = this.getScene();
  44122. var engine = scene.getEngine();
  44123. // Lights
  44124. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44125. defines._needNormals = true;
  44126. // Textures
  44127. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44128. if (defines._areTexturesDirty) {
  44129. defines._needUVs = false;
  44130. if (scene.texturesEnabled) {
  44131. if (scene.getEngine().getCaps().textureLOD) {
  44132. defines.LODBASEDMICROSFURACE = true;
  44133. }
  44134. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44135. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44136. }
  44137. else {
  44138. defines.ALBEDO = false;
  44139. }
  44140. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44141. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44142. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44143. }
  44144. else {
  44145. defines.AMBIENT = false;
  44146. }
  44147. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44148. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44149. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44150. }
  44151. else {
  44152. defines.OPACITY = false;
  44153. }
  44154. var reflectionTexture = this._getReflectionTexture();
  44155. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44156. defines.REFLECTION = true;
  44157. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44158. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44159. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44160. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44161. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44162. defines.INVERTCUBICMAP = true;
  44163. }
  44164. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44165. switch (reflectionTexture.coordinatesMode) {
  44166. case BABYLON.Texture.EXPLICIT_MODE:
  44167. defines.REFLECTIONMAP_EXPLICIT = true;
  44168. break;
  44169. case BABYLON.Texture.PLANAR_MODE:
  44170. defines.REFLECTIONMAP_PLANAR = true;
  44171. break;
  44172. case BABYLON.Texture.PROJECTION_MODE:
  44173. defines.REFLECTIONMAP_PROJECTION = true;
  44174. break;
  44175. case BABYLON.Texture.SKYBOX_MODE:
  44176. defines.REFLECTIONMAP_SKYBOX = true;
  44177. break;
  44178. case BABYLON.Texture.SPHERICAL_MODE:
  44179. defines.REFLECTIONMAP_SPHERICAL = true;
  44180. break;
  44181. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44182. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44183. break;
  44184. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44185. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44186. break;
  44187. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44188. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44189. break;
  44190. case BABYLON.Texture.CUBIC_MODE:
  44191. case BABYLON.Texture.INVCUBIC_MODE:
  44192. default:
  44193. defines.REFLECTIONMAP_CUBIC = true;
  44194. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44195. break;
  44196. }
  44197. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44198. if (reflectionTexture.sphericalPolynomial) {
  44199. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44200. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44201. defines.USESPHERICALINVERTEX = false;
  44202. }
  44203. else {
  44204. defines.USESPHERICALINVERTEX = true;
  44205. }
  44206. }
  44207. }
  44208. else {
  44209. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44210. }
  44211. }
  44212. else {
  44213. defines.REFLECTION = false;
  44214. defines.REFLECTIONMAP_3D = false;
  44215. defines.REFLECTIONMAP_SPHERICAL = false;
  44216. defines.REFLECTIONMAP_PLANAR = false;
  44217. defines.REFLECTIONMAP_CUBIC = false;
  44218. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44219. defines.REFLECTIONMAP_PROJECTION = false;
  44220. defines.REFLECTIONMAP_SKYBOX = false;
  44221. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44222. defines.REFLECTIONMAP_EXPLICIT = false;
  44223. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44224. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44225. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44226. defines.INVERTCUBICMAP = false;
  44227. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44228. defines.USESPHERICALINVERTEX = false;
  44229. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44230. defines.LODINREFLECTIONALPHA = false;
  44231. defines.GAMMAREFLECTION = false;
  44232. defines.RGBDREFLECTION = false;
  44233. }
  44234. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44235. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44236. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44237. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44238. }
  44239. else {
  44240. defines.LIGHTMAP = false;
  44241. }
  44242. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44243. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44244. }
  44245. else {
  44246. defines.EMISSIVE = false;
  44247. }
  44248. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44249. if (this._metallicTexture) {
  44250. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44251. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44252. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44253. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44254. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44255. }
  44256. else if (this._reflectivityTexture) {
  44257. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44258. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44259. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44260. }
  44261. else {
  44262. defines.REFLECTIVITY = false;
  44263. }
  44264. if (this._microSurfaceTexture) {
  44265. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44266. }
  44267. else {
  44268. defines.MICROSURFACEMAP = false;
  44269. }
  44270. }
  44271. else {
  44272. defines.REFLECTIVITY = false;
  44273. defines.MICROSURFACEMAP = false;
  44274. }
  44275. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44276. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44277. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44278. defines.PARALLAX = true;
  44279. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44280. }
  44281. else {
  44282. defines.PARALLAX = false;
  44283. }
  44284. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44285. }
  44286. else {
  44287. defines.BUMP = false;
  44288. }
  44289. var refractionTexture = this._getRefractionTexture();
  44290. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44291. defines.REFRACTION = true;
  44292. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44293. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44294. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44295. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44296. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44297. if (this._linkRefractionWithTransparency) {
  44298. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44299. }
  44300. }
  44301. else {
  44302. defines.REFRACTION = false;
  44303. }
  44304. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44305. defines.ENVIRONMENTBRDF = true;
  44306. }
  44307. else {
  44308. defines.ENVIRONMENTBRDF = false;
  44309. }
  44310. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44311. defines.ALPHAFROMALBEDO = true;
  44312. }
  44313. else {
  44314. defines.ALPHAFROMALBEDO = false;
  44315. }
  44316. }
  44317. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44318. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44319. defines.USEPHYSICALLIGHTFALLOFF = false;
  44320. defines.USEGLTFLIGHTFALLOFF = false;
  44321. }
  44322. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44323. defines.USEPHYSICALLIGHTFALLOFF = false;
  44324. defines.USEGLTFLIGHTFALLOFF = true;
  44325. }
  44326. else {
  44327. defines.USEPHYSICALLIGHTFALLOFF = true;
  44328. defines.USEGLTFLIGHTFALLOFF = false;
  44329. }
  44330. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44331. if (!this.backFaceCulling && this._twoSidedLighting) {
  44332. defines.TWOSIDEDLIGHTING = true;
  44333. }
  44334. else {
  44335. defines.TWOSIDEDLIGHTING = false;
  44336. }
  44337. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44338. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44339. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44340. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44341. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44342. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44343. }
  44344. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44345. this._imageProcessingConfiguration.prepareDefines(defines);
  44346. }
  44347. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44348. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44349. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44350. // Misc.
  44351. if (defines._areMiscDirty) {
  44352. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44353. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44354. }
  44355. // Values that need to be evaluated on every frame
  44356. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44357. // Attribs
  44358. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44359. };
  44360. /**
  44361. * Force shader compilation
  44362. */
  44363. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44364. var _this = this;
  44365. var localOptions = __assign({ clipPlane: false }, options);
  44366. var defines = new PBRMaterialDefines();
  44367. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44368. if (effect.isReady()) {
  44369. if (onCompiled) {
  44370. onCompiled(this);
  44371. }
  44372. }
  44373. else {
  44374. effect.onCompileObservable.add(function () {
  44375. if (onCompiled) {
  44376. onCompiled(_this);
  44377. }
  44378. });
  44379. }
  44380. };
  44381. /**
  44382. * Initializes the uniform buffer layout for the shader.
  44383. */
  44384. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44385. // Order is important !
  44386. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44387. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44388. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44389. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44390. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44391. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44392. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44393. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44394. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44395. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44396. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44397. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44398. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44399. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44400. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44401. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44402. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44403. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44404. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44405. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44406. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44407. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44408. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44409. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44410. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44411. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44412. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44413. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44414. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44415. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44416. this._uniformBuffer.addUniform("pointSize", 1);
  44417. this._uniformBuffer.create();
  44418. };
  44419. /**
  44420. * Unbinds the textures.
  44421. */
  44422. PBRBaseMaterial.prototype.unbind = function () {
  44423. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44424. this._uniformBuffer.setTexture("reflectionSampler", null);
  44425. }
  44426. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44427. this._uniformBuffer.setTexture("refractionSampler", null);
  44428. }
  44429. _super.prototype.unbind.call(this);
  44430. };
  44431. /**
  44432. * Binds the submesh data.
  44433. * @param world - The world matrix.
  44434. * @param mesh - The BJS mesh.
  44435. * @param subMesh - A submesh of the BJS mesh.
  44436. */
  44437. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44438. var scene = this.getScene();
  44439. var defines = subMesh._materialDefines;
  44440. if (!defines) {
  44441. return;
  44442. }
  44443. var effect = subMesh.effect;
  44444. if (!effect) {
  44445. return;
  44446. }
  44447. this._activeEffect = effect;
  44448. // Matrices
  44449. this.bindOnlyWorldMatrix(world);
  44450. // Normal Matrix
  44451. if (defines.OBJECTSPACE_NORMALMAP) {
  44452. world.toNormalMatrix(this._normalMatrix);
  44453. this.bindOnlyNormalMatrix(this._normalMatrix);
  44454. }
  44455. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44456. // Bones
  44457. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44458. var reflectionTexture = null;
  44459. if (mustRebind) {
  44460. this._uniformBuffer.bindToEffect(effect, "Material");
  44461. this.bindViewProjection(effect);
  44462. reflectionTexture = this._getReflectionTexture();
  44463. var refractionTexture = this._getRefractionTexture();
  44464. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44465. // Texture uniforms
  44466. if (scene.texturesEnabled) {
  44467. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44468. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44469. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44470. }
  44471. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44472. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44473. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44474. }
  44475. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44476. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44477. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44478. }
  44479. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44480. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44481. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44482. if (reflectionTexture.boundingBoxSize) {
  44483. var cubeTexture = reflectionTexture;
  44484. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44485. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44486. }
  44487. var polynomials = reflectionTexture.sphericalPolynomial;
  44488. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44489. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44490. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44491. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44492. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44493. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44494. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44495. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44496. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44497. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44498. }
  44499. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44500. }
  44501. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44502. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44503. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44504. }
  44505. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44506. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44507. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44508. }
  44509. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44510. if (this._metallicTexture) {
  44511. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44512. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44513. }
  44514. else if (this._reflectivityTexture) {
  44515. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44516. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44517. }
  44518. if (this._microSurfaceTexture) {
  44519. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44520. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44521. }
  44522. }
  44523. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44524. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44525. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44526. if (scene._mirroredCameraPosition) {
  44527. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44528. }
  44529. else {
  44530. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44531. }
  44532. }
  44533. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44534. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44535. var depth = 1.0;
  44536. if (!refractionTexture.isCube) {
  44537. if (refractionTexture.depth) {
  44538. depth = refractionTexture.depth;
  44539. }
  44540. }
  44541. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44542. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44543. }
  44544. }
  44545. // Point size
  44546. if (this.pointsCloud) {
  44547. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44548. }
  44549. // Colors
  44550. if (defines.METALLICWORKFLOW) {
  44551. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44552. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44553. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44554. }
  44555. else {
  44556. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44557. }
  44558. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44559. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44560. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44561. // Misc
  44562. this._lightingInfos.x = this._directIntensity;
  44563. this._lightingInfos.y = this._emissiveIntensity;
  44564. this._lightingInfos.z = this._environmentIntensity;
  44565. this._lightingInfos.w = this._specularIntensity;
  44566. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44567. }
  44568. // Textures
  44569. if (scene.texturesEnabled) {
  44570. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44571. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44572. }
  44573. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44574. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44575. }
  44576. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44577. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44578. }
  44579. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44580. if (defines.LODBASEDMICROSFURACE) {
  44581. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44582. }
  44583. else {
  44584. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44585. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44586. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44587. }
  44588. }
  44589. if (defines.ENVIRONMENTBRDF) {
  44590. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44591. }
  44592. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44593. if (defines.LODBASEDMICROSFURACE) {
  44594. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44595. }
  44596. else {
  44597. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44598. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44599. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44600. }
  44601. }
  44602. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44603. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44604. }
  44605. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44606. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44607. }
  44608. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44609. if (this._metallicTexture) {
  44610. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44611. }
  44612. else if (this._reflectivityTexture) {
  44613. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44614. }
  44615. if (this._microSurfaceTexture) {
  44616. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44617. }
  44618. }
  44619. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44620. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44621. }
  44622. }
  44623. // Clip plane
  44624. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44625. // Colors
  44626. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44627. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44628. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44629. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44630. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44631. }
  44632. if (mustRebind || !this.isFrozen) {
  44633. // Lights
  44634. if (scene.lightsEnabled && !this._disableLighting) {
  44635. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44636. }
  44637. // View
  44638. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44639. this.bindView(effect);
  44640. }
  44641. // Fog
  44642. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44643. // Morph targets
  44644. if (defines.NUM_MORPH_INFLUENCERS) {
  44645. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44646. }
  44647. // image processing
  44648. this._imageProcessingConfiguration.bind(this._activeEffect);
  44649. // Log. depth
  44650. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44651. }
  44652. this._uniformBuffer.update();
  44653. this._afterBind(mesh, this._activeEffect);
  44654. };
  44655. /**
  44656. * Returns the animatable textures.
  44657. * @returns - Array of animatable textures.
  44658. */
  44659. PBRBaseMaterial.prototype.getAnimatables = function () {
  44660. var results = [];
  44661. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44662. results.push(this._albedoTexture);
  44663. }
  44664. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44665. results.push(this._ambientTexture);
  44666. }
  44667. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44668. results.push(this._opacityTexture);
  44669. }
  44670. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44671. results.push(this._reflectionTexture);
  44672. }
  44673. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44674. results.push(this._emissiveTexture);
  44675. }
  44676. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44677. results.push(this._metallicTexture);
  44678. }
  44679. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44680. results.push(this._reflectivityTexture);
  44681. }
  44682. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44683. results.push(this._bumpTexture);
  44684. }
  44685. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44686. results.push(this._lightmapTexture);
  44687. }
  44688. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44689. results.push(this._refractionTexture);
  44690. }
  44691. return results;
  44692. };
  44693. /**
  44694. * Returns the texture used for reflections.
  44695. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44696. */
  44697. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44698. if (this._reflectionTexture) {
  44699. return this._reflectionTexture;
  44700. }
  44701. return this.getScene().environmentTexture;
  44702. };
  44703. /**
  44704. * Returns the texture used for refraction or null if none is used.
  44705. * @returns - Refection texture if present. If no refraction texture and refraction
  44706. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44707. */
  44708. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44709. if (this._refractionTexture) {
  44710. return this._refractionTexture;
  44711. }
  44712. if (this._linkRefractionWithTransparency) {
  44713. return this.getScene().environmentTexture;
  44714. }
  44715. return null;
  44716. };
  44717. /**
  44718. * Disposes the resources of the material.
  44719. * @param forceDisposeEffect - Forces the disposal of effects.
  44720. * @param forceDisposeTextures - Forces the disposal of all textures.
  44721. */
  44722. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44723. if (forceDisposeTextures) {
  44724. if (this._albedoTexture) {
  44725. this._albedoTexture.dispose();
  44726. }
  44727. if (this._ambientTexture) {
  44728. this._ambientTexture.dispose();
  44729. }
  44730. if (this._opacityTexture) {
  44731. this._opacityTexture.dispose();
  44732. }
  44733. if (this._reflectionTexture) {
  44734. this._reflectionTexture.dispose();
  44735. }
  44736. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44737. this._environmentBRDFTexture.dispose();
  44738. }
  44739. if (this._emissiveTexture) {
  44740. this._emissiveTexture.dispose();
  44741. }
  44742. if (this._metallicTexture) {
  44743. this._metallicTexture.dispose();
  44744. }
  44745. if (this._reflectivityTexture) {
  44746. this._reflectivityTexture.dispose();
  44747. }
  44748. if (this._bumpTexture) {
  44749. this._bumpTexture.dispose();
  44750. }
  44751. if (this._lightmapTexture) {
  44752. this._lightmapTexture.dispose();
  44753. }
  44754. if (this._refractionTexture) {
  44755. this._refractionTexture.dispose();
  44756. }
  44757. }
  44758. this._renderTargets.dispose();
  44759. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44760. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44761. }
  44762. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44763. };
  44764. /**
  44765. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44766. */
  44767. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44768. /**
  44769. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44770. * to enhance interoperability with other engines.
  44771. */
  44772. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44773. /**
  44774. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44775. * to enhance interoperability with other materials.
  44776. */
  44777. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44778. /**
  44779. * Stores the reflectivity values based on metallic roughness workflow.
  44780. */
  44781. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44782. __decorate([
  44783. BABYLON.serializeAsImageProcessingConfiguration()
  44784. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44785. __decorate([
  44786. BABYLON.serialize()
  44787. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44788. __decorate([
  44789. BABYLON.serialize()
  44790. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44791. return PBRBaseMaterial;
  44792. }(BABYLON.PushMaterial));
  44793. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44794. })(BABYLON || (BABYLON = {}));
  44795. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44796. var BABYLON;
  44797. (function (BABYLON) {
  44798. /**
  44799. * The Physically based simple base material of BJS.
  44800. *
  44801. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44802. * It is used as the base class for both the specGloss and metalRough conventions.
  44803. */
  44804. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44805. __extends(PBRBaseSimpleMaterial, _super);
  44806. /**
  44807. * Instantiates a new PBRMaterial instance.
  44808. *
  44809. * @param name The material name
  44810. * @param scene The scene the material will be use in.
  44811. */
  44812. function PBRBaseSimpleMaterial(name, scene) {
  44813. var _this = _super.call(this, name, scene) || this;
  44814. /**
  44815. * Number of Simultaneous lights allowed on the material.
  44816. */
  44817. _this.maxSimultaneousLights = 4;
  44818. /**
  44819. * If sets to true, disables all the lights affecting the material.
  44820. */
  44821. _this.disableLighting = false;
  44822. /**
  44823. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44824. */
  44825. _this.invertNormalMapX = false;
  44826. /**
  44827. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44828. */
  44829. _this.invertNormalMapY = false;
  44830. /**
  44831. * Emissivie color used to self-illuminate the model.
  44832. */
  44833. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44834. /**
  44835. * Occlusion Channel Strenght.
  44836. */
  44837. _this.occlusionStrength = 1.0;
  44838. _this.useLightmapAsShadowmap = false;
  44839. _this._useAlphaFromAlbedoTexture = true;
  44840. _this._useAmbientInGrayScale = true;
  44841. return _this;
  44842. }
  44843. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44844. /**
  44845. * Gets the current double sided mode.
  44846. */
  44847. get: function () {
  44848. return this._twoSidedLighting;
  44849. },
  44850. /**
  44851. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44852. */
  44853. set: function (value) {
  44854. if (this._twoSidedLighting === value) {
  44855. return;
  44856. }
  44857. this._twoSidedLighting = value;
  44858. this.backFaceCulling = !value;
  44859. this._markAllSubMeshesAsTexturesDirty();
  44860. },
  44861. enumerable: true,
  44862. configurable: true
  44863. });
  44864. /**
  44865. * Return the active textures of the material.
  44866. */
  44867. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44868. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44869. if (this.environmentTexture) {
  44870. activeTextures.push(this.environmentTexture);
  44871. }
  44872. if (this.normalTexture) {
  44873. activeTextures.push(this.normalTexture);
  44874. }
  44875. if (this.emissiveTexture) {
  44876. activeTextures.push(this.emissiveTexture);
  44877. }
  44878. if (this.occlusionTexture) {
  44879. activeTextures.push(this.occlusionTexture);
  44880. }
  44881. if (this.lightmapTexture) {
  44882. activeTextures.push(this.lightmapTexture);
  44883. }
  44884. return activeTextures;
  44885. };
  44886. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44887. if (_super.prototype.hasTexture.call(this, texture)) {
  44888. return true;
  44889. }
  44890. if (this.lightmapTexture === texture) {
  44891. return true;
  44892. }
  44893. return false;
  44894. };
  44895. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44896. return "PBRBaseSimpleMaterial";
  44897. };
  44898. __decorate([
  44899. BABYLON.serialize(),
  44900. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44901. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44902. __decorate([
  44903. BABYLON.serialize(),
  44904. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44905. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44906. __decorate([
  44907. BABYLON.serializeAsTexture(),
  44908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44909. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44910. __decorate([
  44911. BABYLON.serialize(),
  44912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44913. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44914. __decorate([
  44915. BABYLON.serialize(),
  44916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44917. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44918. __decorate([
  44919. BABYLON.serializeAsTexture(),
  44920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44921. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44922. __decorate([
  44923. BABYLON.serializeAsColor3("emissive"),
  44924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44925. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44926. __decorate([
  44927. BABYLON.serializeAsTexture(),
  44928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44929. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44930. __decorate([
  44931. BABYLON.serialize(),
  44932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44933. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44934. __decorate([
  44935. BABYLON.serializeAsTexture(),
  44936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44937. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44938. __decorate([
  44939. BABYLON.serialize(),
  44940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44941. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44942. __decorate([
  44943. BABYLON.serialize()
  44944. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44945. __decorate([
  44946. BABYLON.serializeAsTexture(),
  44947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44948. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44949. __decorate([
  44950. BABYLON.serialize(),
  44951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44952. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44953. return PBRBaseSimpleMaterial;
  44954. }(BABYLON.PBRBaseMaterial));
  44955. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44956. })(BABYLON || (BABYLON = {}));
  44957. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44958. var BABYLON;
  44959. (function (BABYLON) {
  44960. /**
  44961. * The Physically based material of BJS.
  44962. *
  44963. * This offers the main features of a standard PBR material.
  44964. * For more information, please refer to the documentation :
  44965. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44966. */
  44967. var PBRMaterial = /** @class */ (function (_super) {
  44968. __extends(PBRMaterial, _super);
  44969. /**
  44970. * Instantiates a new PBRMaterial instance.
  44971. *
  44972. * @param name The material name
  44973. * @param scene The scene the material will be use in.
  44974. */
  44975. function PBRMaterial(name, scene) {
  44976. var _this = _super.call(this, name, scene) || this;
  44977. /**
  44978. * Intensity of the direct lights e.g. the four lights available in your scene.
  44979. * This impacts both the direct diffuse and specular highlights.
  44980. */
  44981. _this.directIntensity = 1.0;
  44982. /**
  44983. * Intensity of the emissive part of the material.
  44984. * This helps controlling the emissive effect without modifying the emissive color.
  44985. */
  44986. _this.emissiveIntensity = 1.0;
  44987. /**
  44988. * Intensity of the environment e.g. how much the environment will light the object
  44989. * either through harmonics for rough material or through the refelction for shiny ones.
  44990. */
  44991. _this.environmentIntensity = 1.0;
  44992. /**
  44993. * This is a special control allowing the reduction of the specular highlights coming from the
  44994. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44995. */
  44996. _this.specularIntensity = 1.0;
  44997. /**
  44998. * Debug Control allowing disabling the bump map on this material.
  44999. */
  45000. _this.disableBumpMap = false;
  45001. /**
  45002. * AKA Occlusion Texture Intensity in other nomenclature.
  45003. */
  45004. _this.ambientTextureStrength = 1.0;
  45005. /**
  45006. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45007. * 1 means it completely occludes it
  45008. * 0 mean it has no impact
  45009. */
  45010. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45011. /**
  45012. * The color of a material in ambient lighting.
  45013. */
  45014. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45015. /**
  45016. * AKA Diffuse Color in other nomenclature.
  45017. */
  45018. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45019. /**
  45020. * AKA Specular Color in other nomenclature.
  45021. */
  45022. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45023. /**
  45024. * The color reflected from the material.
  45025. */
  45026. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45027. /**
  45028. * The color emitted from the material.
  45029. */
  45030. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45031. /**
  45032. * AKA Glossiness in other nomenclature.
  45033. */
  45034. _this.microSurface = 1.0;
  45035. /**
  45036. * source material index of refraction (IOR)' / 'destination material IOR.
  45037. */
  45038. _this.indexOfRefraction = 0.66;
  45039. /**
  45040. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45041. */
  45042. _this.invertRefractionY = false;
  45043. /**
  45044. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45045. * Materials half opaque for instance using refraction could benefit from this control.
  45046. */
  45047. _this.linkRefractionWithTransparency = false;
  45048. _this.useLightmapAsShadowmap = false;
  45049. /**
  45050. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45051. */
  45052. _this.useAlphaFromAlbedoTexture = false;
  45053. /**
  45054. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45055. */
  45056. _this.forceAlphaTest = false;
  45057. /**
  45058. * Defines the alpha limits in alpha test mode.
  45059. */
  45060. _this.alphaCutOff = 0.4;
  45061. /**
  45062. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45063. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45064. */
  45065. _this.useSpecularOverAlpha = true;
  45066. /**
  45067. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45068. */
  45069. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45070. /**
  45071. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45072. */
  45073. _this.useRoughnessFromMetallicTextureAlpha = true;
  45074. /**
  45075. * Specifies if the metallic texture contains the roughness information in its green channel.
  45076. */
  45077. _this.useRoughnessFromMetallicTextureGreen = false;
  45078. /**
  45079. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45080. */
  45081. _this.useMetallnessFromMetallicTextureBlue = false;
  45082. /**
  45083. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45084. */
  45085. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45086. /**
  45087. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45088. */
  45089. _this.useAmbientInGrayScale = false;
  45090. /**
  45091. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45092. * The material will try to infer what glossiness each pixel should be.
  45093. */
  45094. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45095. /**
  45096. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45097. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45098. */
  45099. _this.useRadianceOverAlpha = true;
  45100. /**
  45101. * Allows using an object space normal map (instead of tangent space).
  45102. */
  45103. _this.useObjectSpaceNormalMap = false;
  45104. /**
  45105. * Allows using the bump map in parallax mode.
  45106. */
  45107. _this.useParallax = false;
  45108. /**
  45109. * Allows using the bump map in parallax occlusion mode.
  45110. */
  45111. _this.useParallaxOcclusion = false;
  45112. /**
  45113. * Controls the scale bias of the parallax mode.
  45114. */
  45115. _this.parallaxScaleBias = 0.05;
  45116. /**
  45117. * If sets to true, disables all the lights affecting the material.
  45118. */
  45119. _this.disableLighting = false;
  45120. /**
  45121. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45122. */
  45123. _this.forceIrradianceInFragment = false;
  45124. /**
  45125. * Number of Simultaneous lights allowed on the material.
  45126. */
  45127. _this.maxSimultaneousLights = 4;
  45128. /**
  45129. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45130. */
  45131. _this.invertNormalMapX = false;
  45132. /**
  45133. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45134. */
  45135. _this.invertNormalMapY = false;
  45136. /**
  45137. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45138. */
  45139. _this.twoSidedLighting = false;
  45140. /**
  45141. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45142. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45143. */
  45144. _this.useAlphaFresnel = false;
  45145. /**
  45146. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45147. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45148. */
  45149. _this.useLinearAlphaFresnel = false;
  45150. /**
  45151. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45152. * And/Or occlude the blended part.
  45153. */
  45154. _this.environmentBRDFTexture = null;
  45155. /**
  45156. * Force normal to face away from face.
  45157. */
  45158. _this.forceNormalForward = false;
  45159. /**
  45160. * Enables specular anti aliasing in the PBR shader.
  45161. * It will both interacts on the Geometry for analytical and IBL lighting.
  45162. * It also prefilter the roughness map based on the bump values.
  45163. */
  45164. _this.enableSpecularAntiAliasing = false;
  45165. /**
  45166. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45167. * makes the reflect vector face the model (under horizon).
  45168. */
  45169. _this.useHorizonOcclusion = true;
  45170. /**
  45171. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45172. * too much the area relying on ambient texture to define their ambient occlusion.
  45173. */
  45174. _this.useRadianceOcclusion = true;
  45175. /**
  45176. * If set to true, no lighting calculations will be applied.
  45177. */
  45178. _this.unlit = false;
  45179. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45180. return _this;
  45181. }
  45182. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45183. /**
  45184. * BJS is using an harcoded light falloff based on a manually sets up range.
  45185. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45186. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45187. */
  45188. get: function () {
  45189. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45190. },
  45191. /**
  45192. * BJS is using an harcoded light falloff based on a manually sets up range.
  45193. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45194. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45195. */
  45196. set: function (value) {
  45197. if (value !== this.usePhysicalLightFalloff) {
  45198. // Ensure the effect will be rebuilt.
  45199. this._markAllSubMeshesAsTexturesDirty();
  45200. if (value) {
  45201. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45202. }
  45203. else {
  45204. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45205. }
  45206. }
  45207. },
  45208. enumerable: true,
  45209. configurable: true
  45210. });
  45211. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45212. /**
  45213. * In order to support the falloff compatibility with gltf, a special mode has been added
  45214. * to reproduce the gltf light falloff.
  45215. */
  45216. get: function () {
  45217. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45218. },
  45219. /**
  45220. * In order to support the falloff compatibility with gltf, a special mode has been added
  45221. * to reproduce the gltf light falloff.
  45222. */
  45223. set: function (value) {
  45224. if (value !== this.useGLTFLightFalloff) {
  45225. // Ensure the effect will be rebuilt.
  45226. this._markAllSubMeshesAsTexturesDirty();
  45227. if (value) {
  45228. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45229. }
  45230. else {
  45231. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45232. }
  45233. }
  45234. },
  45235. enumerable: true,
  45236. configurable: true
  45237. });
  45238. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45239. /**
  45240. * Gets the image processing configuration used either in this material.
  45241. */
  45242. get: function () {
  45243. return this._imageProcessingConfiguration;
  45244. },
  45245. /**
  45246. * Sets the Default image processing configuration used either in the this material.
  45247. *
  45248. * If sets to null, the scene one is in use.
  45249. */
  45250. set: function (value) {
  45251. this._attachImageProcessingConfiguration(value);
  45252. // Ensure the effect will be rebuilt.
  45253. this._markAllSubMeshesAsTexturesDirty();
  45254. },
  45255. enumerable: true,
  45256. configurable: true
  45257. });
  45258. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45259. /**
  45260. * Gets wether the color curves effect is enabled.
  45261. */
  45262. get: function () {
  45263. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45264. },
  45265. /**
  45266. * Sets wether the color curves effect is enabled.
  45267. */
  45268. set: function (value) {
  45269. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45270. },
  45271. enumerable: true,
  45272. configurable: true
  45273. });
  45274. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45275. /**
  45276. * Gets wether the color grading effect is enabled.
  45277. */
  45278. get: function () {
  45279. return this.imageProcessingConfiguration.colorGradingEnabled;
  45280. },
  45281. /**
  45282. * Gets wether the color grading effect is enabled.
  45283. */
  45284. set: function (value) {
  45285. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45286. },
  45287. enumerable: true,
  45288. configurable: true
  45289. });
  45290. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45291. /**
  45292. * Gets wether tonemapping is enabled or not.
  45293. */
  45294. get: function () {
  45295. return this._imageProcessingConfiguration.toneMappingEnabled;
  45296. },
  45297. /**
  45298. * Sets wether tonemapping is enabled or not
  45299. */
  45300. set: function (value) {
  45301. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45302. },
  45303. enumerable: true,
  45304. configurable: true
  45305. });
  45306. ;
  45307. ;
  45308. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45309. /**
  45310. * The camera exposure used on this material.
  45311. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45312. * This corresponds to a photographic exposure.
  45313. */
  45314. get: function () {
  45315. return this._imageProcessingConfiguration.exposure;
  45316. },
  45317. /**
  45318. * The camera exposure used on this material.
  45319. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45320. * This corresponds to a photographic exposure.
  45321. */
  45322. set: function (value) {
  45323. this._imageProcessingConfiguration.exposure = value;
  45324. },
  45325. enumerable: true,
  45326. configurable: true
  45327. });
  45328. ;
  45329. ;
  45330. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45331. /**
  45332. * Gets The camera contrast used on this material.
  45333. */
  45334. get: function () {
  45335. return this._imageProcessingConfiguration.contrast;
  45336. },
  45337. /**
  45338. * Sets The camera contrast used on this material.
  45339. */
  45340. set: function (value) {
  45341. this._imageProcessingConfiguration.contrast = value;
  45342. },
  45343. enumerable: true,
  45344. configurable: true
  45345. });
  45346. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45347. /**
  45348. * Gets the Color Grading 2D Lookup Texture.
  45349. */
  45350. get: function () {
  45351. return this._imageProcessingConfiguration.colorGradingTexture;
  45352. },
  45353. /**
  45354. * Sets the Color Grading 2D Lookup Texture.
  45355. */
  45356. set: function (value) {
  45357. this._imageProcessingConfiguration.colorGradingTexture = value;
  45358. },
  45359. enumerable: true,
  45360. configurable: true
  45361. });
  45362. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45363. /**
  45364. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45365. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45366. * 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;
  45367. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45368. */
  45369. get: function () {
  45370. return this._imageProcessingConfiguration.colorCurves;
  45371. },
  45372. /**
  45373. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45374. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45375. * 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;
  45376. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45377. */
  45378. set: function (value) {
  45379. this._imageProcessingConfiguration.colorCurves = value;
  45380. },
  45381. enumerable: true,
  45382. configurable: true
  45383. });
  45384. /**
  45385. * Returns the name of this material class.
  45386. */
  45387. PBRMaterial.prototype.getClassName = function () {
  45388. return "PBRMaterial";
  45389. };
  45390. /**
  45391. * Returns an array of the actively used textures.
  45392. * @returns - Array of BaseTextures
  45393. */
  45394. PBRMaterial.prototype.getActiveTextures = function () {
  45395. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45396. if (this._albedoTexture) {
  45397. activeTextures.push(this._albedoTexture);
  45398. }
  45399. if (this._ambientTexture) {
  45400. activeTextures.push(this._ambientTexture);
  45401. }
  45402. if (this._opacityTexture) {
  45403. activeTextures.push(this._opacityTexture);
  45404. }
  45405. if (this._reflectionTexture) {
  45406. activeTextures.push(this._reflectionTexture);
  45407. }
  45408. if (this._emissiveTexture) {
  45409. activeTextures.push(this._emissiveTexture);
  45410. }
  45411. if (this._reflectivityTexture) {
  45412. activeTextures.push(this._reflectivityTexture);
  45413. }
  45414. if (this._metallicTexture) {
  45415. activeTextures.push(this._metallicTexture);
  45416. }
  45417. if (this._microSurfaceTexture) {
  45418. activeTextures.push(this._microSurfaceTexture);
  45419. }
  45420. if (this._bumpTexture) {
  45421. activeTextures.push(this._bumpTexture);
  45422. }
  45423. if (this._lightmapTexture) {
  45424. activeTextures.push(this._lightmapTexture);
  45425. }
  45426. if (this._refractionTexture) {
  45427. activeTextures.push(this._refractionTexture);
  45428. }
  45429. return activeTextures;
  45430. };
  45431. /**
  45432. * Checks to see if a texture is used in the material.
  45433. * @param texture - Base texture to use.
  45434. * @returns - Boolean specifying if a texture is used in the material.
  45435. */
  45436. PBRMaterial.prototype.hasTexture = function (texture) {
  45437. if (_super.prototype.hasTexture.call(this, texture)) {
  45438. return true;
  45439. }
  45440. if (this._albedoTexture === texture) {
  45441. return true;
  45442. }
  45443. if (this._ambientTexture === texture) {
  45444. return true;
  45445. }
  45446. if (this._opacityTexture === texture) {
  45447. return true;
  45448. }
  45449. if (this._reflectionTexture === texture) {
  45450. return true;
  45451. }
  45452. if (this._reflectivityTexture === texture) {
  45453. return true;
  45454. }
  45455. if (this._metallicTexture === texture) {
  45456. return true;
  45457. }
  45458. if (this._microSurfaceTexture === texture) {
  45459. return true;
  45460. }
  45461. if (this._bumpTexture === texture) {
  45462. return true;
  45463. }
  45464. if (this._lightmapTexture === texture) {
  45465. return true;
  45466. }
  45467. if (this._refractionTexture === texture) {
  45468. return true;
  45469. }
  45470. return false;
  45471. };
  45472. /**
  45473. * Makes a duplicate of the current material.
  45474. * @param name - name to use for the new material.
  45475. */
  45476. PBRMaterial.prototype.clone = function (name) {
  45477. var _this = this;
  45478. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45479. clone.id = name;
  45480. clone.name = name;
  45481. return clone;
  45482. };
  45483. /**
  45484. * Serializes this PBR Material.
  45485. * @returns - An object with the serialized material.
  45486. */
  45487. PBRMaterial.prototype.serialize = function () {
  45488. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45489. serializationObject.customType = "BABYLON.PBRMaterial";
  45490. return serializationObject;
  45491. };
  45492. // Statics
  45493. /**
  45494. * Parses a PBR Material from a serialized object.
  45495. * @param source - Serialized object.
  45496. * @param scene - BJS scene instance.
  45497. * @param rootUrl - url for the scene object
  45498. * @returns - PBRMaterial
  45499. */
  45500. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45501. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45502. };
  45503. /**
  45504. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45505. */
  45506. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45507. /**
  45508. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45509. */
  45510. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45511. /**
  45512. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45513. */
  45514. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45515. /**
  45516. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45517. * They are also discarded below the alpha cutoff threshold to improve performances.
  45518. */
  45519. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45520. /**
  45521. * Defines the default value of how much AO map is occluding the analytical lights
  45522. * (point spot...).
  45523. */
  45524. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45525. __decorate([
  45526. BABYLON.serialize(),
  45527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45528. ], PBRMaterial.prototype, "directIntensity", void 0);
  45529. __decorate([
  45530. BABYLON.serialize(),
  45531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45532. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45533. __decorate([
  45534. BABYLON.serialize(),
  45535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45536. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45537. __decorate([
  45538. BABYLON.serialize(),
  45539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45540. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45541. __decorate([
  45542. BABYLON.serialize(),
  45543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45544. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45545. __decorate([
  45546. BABYLON.serializeAsTexture(),
  45547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45548. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45549. __decorate([
  45550. BABYLON.serializeAsTexture(),
  45551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45552. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45553. __decorate([
  45554. BABYLON.serialize(),
  45555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45556. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45557. __decorate([
  45558. BABYLON.serialize(),
  45559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45560. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45561. __decorate([
  45562. BABYLON.serializeAsTexture(),
  45563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45564. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45565. __decorate([
  45566. BABYLON.serializeAsTexture(),
  45567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45568. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45569. __decorate([
  45570. BABYLON.serializeAsTexture(),
  45571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45572. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45573. __decorate([
  45574. BABYLON.serializeAsTexture(),
  45575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45576. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45577. __decorate([
  45578. BABYLON.serializeAsTexture(),
  45579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45580. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45581. __decorate([
  45582. BABYLON.serialize(),
  45583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45584. ], PBRMaterial.prototype, "metallic", void 0);
  45585. __decorate([
  45586. BABYLON.serialize(),
  45587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45588. ], PBRMaterial.prototype, "roughness", void 0);
  45589. __decorate([
  45590. BABYLON.serializeAsTexture(),
  45591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45592. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45593. __decorate([
  45594. BABYLON.serializeAsTexture(),
  45595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45596. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45597. __decorate([
  45598. BABYLON.serializeAsTexture(),
  45599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45600. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45601. __decorate([
  45602. BABYLON.serializeAsTexture(),
  45603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45604. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45605. __decorate([
  45606. BABYLON.serializeAsColor3("ambient"),
  45607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45608. ], PBRMaterial.prototype, "ambientColor", void 0);
  45609. __decorate([
  45610. BABYLON.serializeAsColor3("albedo"),
  45611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45612. ], PBRMaterial.prototype, "albedoColor", void 0);
  45613. __decorate([
  45614. BABYLON.serializeAsColor3("reflectivity"),
  45615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45616. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45617. __decorate([
  45618. BABYLON.serializeAsColor3("reflection"),
  45619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45620. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45621. __decorate([
  45622. BABYLON.serializeAsColor3("emissive"),
  45623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45624. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45625. __decorate([
  45626. BABYLON.serialize(),
  45627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45628. ], PBRMaterial.prototype, "microSurface", void 0);
  45629. __decorate([
  45630. BABYLON.serialize(),
  45631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45632. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45633. __decorate([
  45634. BABYLON.serialize(),
  45635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45636. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45637. __decorate([
  45638. BABYLON.serialize(),
  45639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45640. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45641. __decorate([
  45642. BABYLON.serialize(),
  45643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45644. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45645. __decorate([
  45646. BABYLON.serialize(),
  45647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45648. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45649. __decorate([
  45650. BABYLON.serialize(),
  45651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45652. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45653. __decorate([
  45654. BABYLON.serialize(),
  45655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45656. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45657. __decorate([
  45658. BABYLON.serialize(),
  45659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45660. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45661. __decorate([
  45662. BABYLON.serialize(),
  45663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45664. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45665. __decorate([
  45666. BABYLON.serialize(),
  45667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45668. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45669. __decorate([
  45670. BABYLON.serialize(),
  45671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45672. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45673. __decorate([
  45674. BABYLON.serialize(),
  45675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45676. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45677. __decorate([
  45678. BABYLON.serialize(),
  45679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45680. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45681. __decorate([
  45682. BABYLON.serialize(),
  45683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45684. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45685. __decorate([
  45686. BABYLON.serialize(),
  45687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45688. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45689. __decorate([
  45690. BABYLON.serialize()
  45691. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45692. __decorate([
  45693. BABYLON.serialize()
  45694. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45695. __decorate([
  45696. BABYLON.serialize(),
  45697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45698. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45699. __decorate([
  45700. BABYLON.serialize(),
  45701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45702. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45703. __decorate([
  45704. BABYLON.serialize(),
  45705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45706. ], PBRMaterial.prototype, "useParallax", void 0);
  45707. __decorate([
  45708. BABYLON.serialize(),
  45709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45710. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45711. __decorate([
  45712. BABYLON.serialize(),
  45713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45714. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45715. __decorate([
  45716. BABYLON.serialize(),
  45717. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45718. ], PBRMaterial.prototype, "disableLighting", void 0);
  45719. __decorate([
  45720. BABYLON.serialize(),
  45721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45722. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45723. __decorate([
  45724. BABYLON.serialize(),
  45725. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45726. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45727. __decorate([
  45728. BABYLON.serialize(),
  45729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45730. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45731. __decorate([
  45732. BABYLON.serialize(),
  45733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45734. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45735. __decorate([
  45736. BABYLON.serialize(),
  45737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45738. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45739. __decorate([
  45740. BABYLON.serialize(),
  45741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45742. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45743. __decorate([
  45744. BABYLON.serialize(),
  45745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45746. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45747. __decorate([
  45748. BABYLON.serializeAsTexture(),
  45749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45750. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45751. __decorate([
  45752. BABYLON.serialize(),
  45753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45754. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45755. __decorate([
  45756. BABYLON.serialize(),
  45757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45758. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45759. __decorate([
  45760. BABYLON.serialize(),
  45761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45762. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45763. __decorate([
  45764. BABYLON.serialize(),
  45765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45766. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45767. __decorate([
  45768. BABYLON.serialize(),
  45769. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45770. ], PBRMaterial.prototype, "unlit", void 0);
  45771. return PBRMaterial;
  45772. }(BABYLON.PBRBaseMaterial));
  45773. BABYLON.PBRMaterial = PBRMaterial;
  45774. })(BABYLON || (BABYLON = {}));
  45775. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45776. var BABYLON;
  45777. (function (BABYLON) {
  45778. /**
  45779. * The PBR material of BJS following the metal roughness convention.
  45780. *
  45781. * This fits to the PBR convention in the GLTF definition:
  45782. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45783. */
  45784. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45785. __extends(PBRMetallicRoughnessMaterial, _super);
  45786. /**
  45787. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45788. *
  45789. * @param name The material name
  45790. * @param scene The scene the material will be use in.
  45791. */
  45792. function PBRMetallicRoughnessMaterial(name, scene) {
  45793. var _this = _super.call(this, name, scene) || this;
  45794. _this._useRoughnessFromMetallicTextureAlpha = false;
  45795. _this._useRoughnessFromMetallicTextureGreen = true;
  45796. _this._useMetallnessFromMetallicTextureBlue = true;
  45797. _this.metallic = 1.0;
  45798. _this.roughness = 1.0;
  45799. return _this;
  45800. }
  45801. /**
  45802. * Return the currrent class name of the material.
  45803. */
  45804. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45805. return "PBRMetallicRoughnessMaterial";
  45806. };
  45807. /**
  45808. * Return the active textures of the material.
  45809. */
  45810. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45811. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45812. if (this.baseTexture) {
  45813. activeTextures.push(this.baseTexture);
  45814. }
  45815. if (this.metallicRoughnessTexture) {
  45816. activeTextures.push(this.metallicRoughnessTexture);
  45817. }
  45818. return activeTextures;
  45819. };
  45820. /**
  45821. * Checks to see if a texture is used in the material.
  45822. * @param texture - Base texture to use.
  45823. * @returns - Boolean specifying if a texture is used in the material.
  45824. */
  45825. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45826. if (_super.prototype.hasTexture.call(this, texture)) {
  45827. return true;
  45828. }
  45829. if (this.baseTexture === texture) {
  45830. return true;
  45831. }
  45832. if (this.metallicRoughnessTexture === texture) {
  45833. return true;
  45834. }
  45835. return false;
  45836. };
  45837. /**
  45838. * Makes a duplicate of the current material.
  45839. * @param name - name to use for the new material.
  45840. */
  45841. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45842. var _this = this;
  45843. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45844. clone.id = name;
  45845. clone.name = name;
  45846. return clone;
  45847. };
  45848. /**
  45849. * Serialize the material to a parsable JSON object.
  45850. */
  45851. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45852. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45853. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45854. return serializationObject;
  45855. };
  45856. /**
  45857. * Parses a JSON object correponding to the serialize function.
  45858. */
  45859. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45860. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45861. };
  45862. __decorate([
  45863. BABYLON.serializeAsColor3(),
  45864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45865. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45866. __decorate([
  45867. BABYLON.serializeAsTexture(),
  45868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45869. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45870. __decorate([
  45871. BABYLON.serialize(),
  45872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45873. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45874. __decorate([
  45875. BABYLON.serialize(),
  45876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45877. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45878. __decorate([
  45879. BABYLON.serializeAsTexture(),
  45880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45881. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45882. return PBRMetallicRoughnessMaterial;
  45883. }(BABYLON.PBRBaseSimpleMaterial));
  45884. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45885. })(BABYLON || (BABYLON = {}));
  45886. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45887. var BABYLON;
  45888. (function (BABYLON) {
  45889. /**
  45890. * The PBR material of BJS following the specular glossiness convention.
  45891. *
  45892. * This fits to the PBR convention in the GLTF definition:
  45893. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45894. */
  45895. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45896. __extends(PBRSpecularGlossinessMaterial, _super);
  45897. /**
  45898. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45899. *
  45900. * @param name The material name
  45901. * @param scene The scene the material will be use in.
  45902. */
  45903. function PBRSpecularGlossinessMaterial(name, scene) {
  45904. var _this = _super.call(this, name, scene) || this;
  45905. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45906. return _this;
  45907. }
  45908. /**
  45909. * Return the currrent class name of the material.
  45910. */
  45911. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45912. return "PBRSpecularGlossinessMaterial";
  45913. };
  45914. /**
  45915. * Return the active textures of the material.
  45916. */
  45917. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45918. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45919. if (this.diffuseTexture) {
  45920. activeTextures.push(this.diffuseTexture);
  45921. }
  45922. if (this.specularGlossinessTexture) {
  45923. activeTextures.push(this.specularGlossinessTexture);
  45924. }
  45925. return activeTextures;
  45926. };
  45927. /**
  45928. * Checks to see if a texture is used in the material.
  45929. * @param texture - Base texture to use.
  45930. * @returns - Boolean specifying if a texture is used in the material.
  45931. */
  45932. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45933. if (_super.prototype.hasTexture.call(this, texture)) {
  45934. return true;
  45935. }
  45936. if (this.diffuseTexture === texture) {
  45937. return true;
  45938. }
  45939. if (this.specularGlossinessTexture === texture) {
  45940. return true;
  45941. }
  45942. return false;
  45943. };
  45944. /**
  45945. * Makes a duplicate of the current material.
  45946. * @param name - name to use for the new material.
  45947. */
  45948. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45949. var _this = this;
  45950. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45951. clone.id = name;
  45952. clone.name = name;
  45953. return clone;
  45954. };
  45955. /**
  45956. * Serialize the material to a parsable JSON object.
  45957. */
  45958. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45959. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45960. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45961. return serializationObject;
  45962. };
  45963. /**
  45964. * Parses a JSON object correponding to the serialize function.
  45965. */
  45966. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45967. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45968. };
  45969. __decorate([
  45970. BABYLON.serializeAsColor3("diffuse"),
  45971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45972. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45973. __decorate([
  45974. BABYLON.serializeAsTexture(),
  45975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45976. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45977. __decorate([
  45978. BABYLON.serializeAsColor3("specular"),
  45979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45980. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45981. __decorate([
  45982. BABYLON.serialize(),
  45983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45984. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45985. __decorate([
  45986. BABYLON.serializeAsTexture(),
  45987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45988. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45989. return PBRSpecularGlossinessMaterial;
  45990. }(BABYLON.PBRBaseSimpleMaterial));
  45991. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45992. })(BABYLON || (BABYLON = {}));
  45993. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45994. var BABYLON;
  45995. (function (BABYLON) {
  45996. BABYLON.CameraInputTypes = {};
  45997. var CameraInputsManager = /** @class */ (function () {
  45998. function CameraInputsManager(camera) {
  45999. this.attached = {};
  46000. this.camera = camera;
  46001. this.checkInputs = function () { };
  46002. }
  46003. /**
  46004. * Add an input method to a camera
  46005. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46006. * @param input camera input method
  46007. */
  46008. CameraInputsManager.prototype.add = function (input) {
  46009. var type = input.getSimpleName();
  46010. if (this.attached[type]) {
  46011. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46012. return;
  46013. }
  46014. this.attached[type] = input;
  46015. input.camera = this.camera;
  46016. //for checkInputs, we are dynamically creating a function
  46017. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46018. if (input.checkInputs) {
  46019. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46020. }
  46021. if (this.attachedElement) {
  46022. input.attachControl(this.attachedElement);
  46023. }
  46024. };
  46025. /**
  46026. * Remove a specific input method from a camera
  46027. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46028. * @param inputToRemove camera input method
  46029. */
  46030. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46031. for (var cam in this.attached) {
  46032. var input = this.attached[cam];
  46033. if (input === inputToRemove) {
  46034. input.detachControl(this.attachedElement);
  46035. input.camera = null;
  46036. delete this.attached[cam];
  46037. this.rebuildInputCheck();
  46038. }
  46039. }
  46040. };
  46041. CameraInputsManager.prototype.removeByType = function (inputType) {
  46042. for (var cam in this.attached) {
  46043. var input = this.attached[cam];
  46044. if (input.getClassName() === inputType) {
  46045. input.detachControl(this.attachedElement);
  46046. input.camera = null;
  46047. delete this.attached[cam];
  46048. this.rebuildInputCheck();
  46049. }
  46050. }
  46051. };
  46052. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46053. var current = this.checkInputs;
  46054. return function () {
  46055. current();
  46056. fn();
  46057. };
  46058. };
  46059. CameraInputsManager.prototype.attachInput = function (input) {
  46060. if (this.attachedElement) {
  46061. input.attachControl(this.attachedElement, this.noPreventDefault);
  46062. }
  46063. };
  46064. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46065. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46066. if (this.attachedElement) {
  46067. return;
  46068. }
  46069. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46070. this.attachedElement = element;
  46071. this.noPreventDefault = noPreventDefault;
  46072. for (var cam in this.attached) {
  46073. this.attached[cam].attachControl(element, noPreventDefault);
  46074. }
  46075. };
  46076. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46077. if (disconnect === void 0) { disconnect = false; }
  46078. if (this.attachedElement !== element) {
  46079. return;
  46080. }
  46081. for (var cam in this.attached) {
  46082. this.attached[cam].detachControl(element);
  46083. if (disconnect) {
  46084. this.attached[cam].camera = null;
  46085. }
  46086. }
  46087. this.attachedElement = null;
  46088. };
  46089. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46090. this.checkInputs = function () { };
  46091. for (var cam in this.attached) {
  46092. var input = this.attached[cam];
  46093. if (input.checkInputs) {
  46094. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46095. }
  46096. }
  46097. };
  46098. /**
  46099. * Remove all attached input methods from a camera
  46100. */
  46101. CameraInputsManager.prototype.clear = function () {
  46102. if (this.attachedElement) {
  46103. this.detachElement(this.attachedElement, true);
  46104. }
  46105. this.attached = {};
  46106. this.attachedElement = null;
  46107. this.checkInputs = function () { };
  46108. };
  46109. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46110. var inputs = {};
  46111. for (var cam in this.attached) {
  46112. var input = this.attached[cam];
  46113. var res = BABYLON.SerializationHelper.Serialize(input);
  46114. inputs[input.getClassName()] = res;
  46115. }
  46116. serializedCamera.inputsmgr = inputs;
  46117. };
  46118. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46119. var parsedInputs = parsedCamera.inputsmgr;
  46120. if (parsedInputs) {
  46121. this.clear();
  46122. for (var n in parsedInputs) {
  46123. var construct = BABYLON.CameraInputTypes[n];
  46124. if (construct) {
  46125. var parsedinput = parsedInputs[n];
  46126. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46127. this.add(input);
  46128. }
  46129. }
  46130. }
  46131. else {
  46132. //2016-03-08 this part is for managing backward compatibility
  46133. for (var n in this.attached) {
  46134. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46135. if (construct) {
  46136. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46137. this.remove(this.attached[n]);
  46138. this.add(input);
  46139. }
  46140. }
  46141. }
  46142. };
  46143. return CameraInputsManager;
  46144. }());
  46145. BABYLON.CameraInputsManager = CameraInputsManager;
  46146. })(BABYLON || (BABYLON = {}));
  46147. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46148. var BABYLON;
  46149. (function (BABYLON) {
  46150. var TargetCamera = /** @class */ (function (_super) {
  46151. __extends(TargetCamera, _super);
  46152. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46153. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46154. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46155. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46156. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46157. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46158. _this.speed = 2.0;
  46159. _this.noRotationConstraint = false;
  46160. _this.lockedTarget = null;
  46161. /** @hidden */
  46162. _this._currentTarget = BABYLON.Vector3.Zero();
  46163. /** @hidden */
  46164. _this._viewMatrix = BABYLON.Matrix.Zero();
  46165. /** @hidden */
  46166. _this._camMatrix = BABYLON.Matrix.Zero();
  46167. /** @hidden */
  46168. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46169. /** @hidden */
  46170. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46171. /** @hidden */
  46172. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46173. /** @hidden */
  46174. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46175. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46176. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46177. _this._defaultUp = BABYLON.Vector3.Up();
  46178. _this._cachedRotationZ = 0;
  46179. return _this;
  46180. }
  46181. TargetCamera.prototype.getFrontPosition = function (distance) {
  46182. this.getWorldMatrix();
  46183. var direction = this.getTarget().subtract(this.position);
  46184. direction.normalize();
  46185. direction.scaleInPlace(distance);
  46186. return this.globalPosition.add(direction);
  46187. };
  46188. /** @hidden */
  46189. TargetCamera.prototype._getLockedTargetPosition = function () {
  46190. if (!this.lockedTarget) {
  46191. return null;
  46192. }
  46193. if (this.lockedTarget.absolutePosition) {
  46194. this.lockedTarget.computeWorldMatrix();
  46195. }
  46196. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46197. };
  46198. TargetCamera.prototype.storeState = function () {
  46199. this._storedPosition = this.position.clone();
  46200. this._storedRotation = this.rotation.clone();
  46201. if (this.rotationQuaternion) {
  46202. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46203. }
  46204. return _super.prototype.storeState.call(this);
  46205. };
  46206. /**
  46207. * Restored camera state. You must call storeState() first
  46208. * @returns whether it was successful or not
  46209. * @hidden
  46210. */
  46211. TargetCamera.prototype._restoreStateValues = function () {
  46212. if (!_super.prototype._restoreStateValues.call(this)) {
  46213. return false;
  46214. }
  46215. this.position = this._storedPosition.clone();
  46216. this.rotation = this._storedRotation.clone();
  46217. if (this.rotationQuaternion) {
  46218. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46219. }
  46220. this.cameraDirection.copyFromFloats(0, 0, 0);
  46221. this.cameraRotation.copyFromFloats(0, 0);
  46222. return true;
  46223. };
  46224. // Cache
  46225. /** @hidden */
  46226. TargetCamera.prototype._initCache = function () {
  46227. _super.prototype._initCache.call(this);
  46228. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46229. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46230. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46231. };
  46232. /** @hidden */
  46233. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46234. if (!ignoreParentClass) {
  46235. _super.prototype._updateCache.call(this);
  46236. }
  46237. var lockedTargetPosition = this._getLockedTargetPosition();
  46238. if (!lockedTargetPosition) {
  46239. this._cache.lockedTarget = null;
  46240. }
  46241. else {
  46242. if (!this._cache.lockedTarget) {
  46243. this._cache.lockedTarget = lockedTargetPosition.clone();
  46244. }
  46245. else {
  46246. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46247. }
  46248. }
  46249. this._cache.rotation.copyFrom(this.rotation);
  46250. if (this.rotationQuaternion)
  46251. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46252. };
  46253. // Synchronized
  46254. /** @hidden */
  46255. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46256. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46257. return false;
  46258. }
  46259. var lockedTargetPosition = this._getLockedTargetPosition();
  46260. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46261. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46262. };
  46263. // Methods
  46264. /** @hidden */
  46265. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46266. var engine = this.getEngine();
  46267. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46268. };
  46269. // Target
  46270. /** @hidden */
  46271. TargetCamera.prototype.setTarget = function (target) {
  46272. this.upVector.normalize();
  46273. if (this.position.z === target.z) {
  46274. this.position.z += BABYLON.Epsilon;
  46275. }
  46276. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46277. this._camMatrix.invert();
  46278. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46279. var vDir = target.subtract(this.position);
  46280. if (vDir.x >= 0.0) {
  46281. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46282. }
  46283. else {
  46284. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46285. }
  46286. this.rotation.z = 0;
  46287. if (isNaN(this.rotation.x)) {
  46288. this.rotation.x = 0;
  46289. }
  46290. if (isNaN(this.rotation.y)) {
  46291. this.rotation.y = 0;
  46292. }
  46293. if (isNaN(this.rotation.z)) {
  46294. this.rotation.z = 0;
  46295. }
  46296. if (this.rotationQuaternion) {
  46297. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46298. }
  46299. };
  46300. /**
  46301. * Return the current target position of the camera. This value is expressed in local space.
  46302. */
  46303. TargetCamera.prototype.getTarget = function () {
  46304. return this._currentTarget;
  46305. };
  46306. /** @hidden */
  46307. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46308. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46309. };
  46310. /** @hidden */
  46311. TargetCamera.prototype._updatePosition = function () {
  46312. if (this.parent) {
  46313. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46314. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46315. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46316. return;
  46317. }
  46318. this.position.addInPlace(this.cameraDirection);
  46319. };
  46320. /** @hidden */
  46321. TargetCamera.prototype._checkInputs = function () {
  46322. var needToMove = this._decideIfNeedsToMove();
  46323. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46324. // Move
  46325. if (needToMove) {
  46326. this._updatePosition();
  46327. }
  46328. // Rotate
  46329. if (needToRotate) {
  46330. this.rotation.x += this.cameraRotation.x;
  46331. this.rotation.y += this.cameraRotation.y;
  46332. //rotate, if quaternion is set and rotation was used
  46333. if (this.rotationQuaternion) {
  46334. var len = this.rotation.lengthSquared();
  46335. if (len) {
  46336. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46337. }
  46338. }
  46339. if (!this.noRotationConstraint) {
  46340. var limit = (Math.PI / 2) * 0.95;
  46341. if (this.rotation.x > limit)
  46342. this.rotation.x = limit;
  46343. if (this.rotation.x < -limit)
  46344. this.rotation.x = -limit;
  46345. }
  46346. }
  46347. // Inertia
  46348. if (needToMove) {
  46349. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46350. this.cameraDirection.x = 0;
  46351. }
  46352. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46353. this.cameraDirection.y = 0;
  46354. }
  46355. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46356. this.cameraDirection.z = 0;
  46357. }
  46358. this.cameraDirection.scaleInPlace(this.inertia);
  46359. }
  46360. if (needToRotate) {
  46361. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46362. this.cameraRotation.x = 0;
  46363. }
  46364. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46365. this.cameraRotation.y = 0;
  46366. }
  46367. this.cameraRotation.scaleInPlace(this.inertia);
  46368. }
  46369. _super.prototype._checkInputs.call(this);
  46370. };
  46371. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46372. if (this.rotationQuaternion) {
  46373. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46374. }
  46375. else {
  46376. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46377. }
  46378. };
  46379. /**
  46380. * 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)
  46381. * @returns the current camera
  46382. */
  46383. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46384. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46385. return this;
  46386. };
  46387. /** @hidden */
  46388. TargetCamera.prototype._getViewMatrix = function () {
  46389. if (this.lockedTarget) {
  46390. this.setTarget(this._getLockedTargetPosition());
  46391. }
  46392. // Compute
  46393. this._updateCameraRotationMatrix();
  46394. // Apply the changed rotation to the upVector.
  46395. if (this._cachedRotationZ != this.rotation.z) {
  46396. this._rotateUpVectorWithCameraRotationMatrix();
  46397. this._cachedRotationZ = this.rotation.z;
  46398. }
  46399. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46400. // Computing target and final matrix
  46401. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46402. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46403. return this._viewMatrix;
  46404. };
  46405. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46406. if (this.parent) {
  46407. var parentWorldMatrix = this.parent.getWorldMatrix();
  46408. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46409. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46410. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46411. this._markSyncedWithParent();
  46412. }
  46413. else {
  46414. this._globalPosition.copyFrom(position);
  46415. this._globalCurrentTarget.copyFrom(target);
  46416. this._globalCurrentUpVector.copyFrom(up);
  46417. }
  46418. if (this.getScene().useRightHandedSystem) {
  46419. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46420. }
  46421. else {
  46422. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46423. }
  46424. };
  46425. /**
  46426. * @override
  46427. * Override Camera.createRigCamera
  46428. */
  46429. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46430. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46431. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46432. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46433. if (!this.rotationQuaternion) {
  46434. this.rotationQuaternion = new BABYLON.Quaternion();
  46435. }
  46436. rigCamera._cameraRigParams = {};
  46437. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46438. }
  46439. return rigCamera;
  46440. }
  46441. return null;
  46442. };
  46443. /**
  46444. * @hidden
  46445. * @override
  46446. * Override Camera._updateRigCameras
  46447. */
  46448. TargetCamera.prototype._updateRigCameras = function () {
  46449. var camLeft = this._rigCameras[0];
  46450. var camRight = this._rigCameras[1];
  46451. switch (this.cameraRigMode) {
  46452. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46453. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46454. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46455. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46456. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46457. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46458. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46459. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46460. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46461. camLeft.setTarget(this.getTarget());
  46462. camRight.setTarget(this.getTarget());
  46463. break;
  46464. case BABYLON.Camera.RIG_MODE_VR:
  46465. if (camLeft.rotationQuaternion) {
  46466. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46467. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46468. }
  46469. else {
  46470. camLeft.rotation.copyFrom(this.rotation);
  46471. camRight.rotation.copyFrom(this.rotation);
  46472. }
  46473. camLeft.position.copyFrom(this.position);
  46474. camRight.position.copyFrom(this.position);
  46475. break;
  46476. }
  46477. _super.prototype._updateRigCameras.call(this);
  46478. };
  46479. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46480. if (!this._rigCamTransformMatrix) {
  46481. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46482. }
  46483. var target = this.getTarget();
  46484. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46485. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46486. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46487. };
  46488. TargetCamera.prototype.getClassName = function () {
  46489. return "TargetCamera";
  46490. };
  46491. __decorate([
  46492. BABYLON.serializeAsVector3()
  46493. ], TargetCamera.prototype, "rotation", void 0);
  46494. __decorate([
  46495. BABYLON.serialize()
  46496. ], TargetCamera.prototype, "speed", void 0);
  46497. __decorate([
  46498. BABYLON.serializeAsMeshReference("lockedTargetId")
  46499. ], TargetCamera.prototype, "lockedTarget", void 0);
  46500. return TargetCamera;
  46501. }(BABYLON.Camera));
  46502. BABYLON.TargetCamera = TargetCamera;
  46503. })(BABYLON || (BABYLON = {}));
  46504. //# sourceMappingURL=babylon.targetCamera.js.map
  46505. var BABYLON;
  46506. (function (BABYLON) {
  46507. var FreeCameraMouseInput = /** @class */ (function () {
  46508. function FreeCameraMouseInput(touchEnabled) {
  46509. if (touchEnabled === void 0) { touchEnabled = true; }
  46510. this.touchEnabled = touchEnabled;
  46511. this.buttons = [0, 1, 2];
  46512. this.angularSensibility = 2000.0;
  46513. this.previousPosition = null;
  46514. }
  46515. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46516. var _this = this;
  46517. var engine = this.camera.getEngine();
  46518. if (!this._pointerInput) {
  46519. this._pointerInput = function (p, s) {
  46520. var evt = p.event;
  46521. if (engine.isInVRExclusivePointerMode) {
  46522. return;
  46523. }
  46524. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46525. return;
  46526. }
  46527. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46528. return;
  46529. }
  46530. var srcElement = (evt.srcElement || evt.target);
  46531. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46532. try {
  46533. srcElement.setPointerCapture(evt.pointerId);
  46534. }
  46535. catch (e) {
  46536. //Nothing to do with the error. Execution will continue.
  46537. }
  46538. _this.previousPosition = {
  46539. x: evt.clientX,
  46540. y: evt.clientY
  46541. };
  46542. if (!noPreventDefault) {
  46543. evt.preventDefault();
  46544. element.focus();
  46545. }
  46546. }
  46547. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46548. try {
  46549. srcElement.releasePointerCapture(evt.pointerId);
  46550. }
  46551. catch (e) {
  46552. //Nothing to do with the error.
  46553. }
  46554. _this.previousPosition = null;
  46555. if (!noPreventDefault) {
  46556. evt.preventDefault();
  46557. }
  46558. }
  46559. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46560. if (!_this.previousPosition || engine.isPointerLock) {
  46561. return;
  46562. }
  46563. var offsetX = evt.clientX - _this.previousPosition.x;
  46564. if (_this.camera.getScene().useRightHandedSystem)
  46565. offsetX *= -1;
  46566. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46567. offsetX *= -1;
  46568. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46569. var offsetY = evt.clientY - _this.previousPosition.y;
  46570. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46571. _this.previousPosition = {
  46572. x: evt.clientX,
  46573. y: evt.clientY
  46574. };
  46575. if (!noPreventDefault) {
  46576. evt.preventDefault();
  46577. }
  46578. }
  46579. };
  46580. }
  46581. this._onMouseMove = function (evt) {
  46582. if (!engine.isPointerLock) {
  46583. return;
  46584. }
  46585. if (engine.isInVRExclusivePointerMode) {
  46586. return;
  46587. }
  46588. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46589. if (_this.camera.getScene().useRightHandedSystem)
  46590. offsetX *= -1;
  46591. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46592. offsetX *= -1;
  46593. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46594. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46595. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46596. _this.previousPosition = null;
  46597. if (!noPreventDefault) {
  46598. evt.preventDefault();
  46599. }
  46600. };
  46601. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46602. element.addEventListener("mousemove", this._onMouseMove, false);
  46603. };
  46604. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46605. if (this._observer && element) {
  46606. this.camera.getScene().onPointerObservable.remove(this._observer);
  46607. if (this._onMouseMove) {
  46608. element.removeEventListener("mousemove", this._onMouseMove);
  46609. }
  46610. this._observer = null;
  46611. this._onMouseMove = null;
  46612. this.previousPosition = null;
  46613. }
  46614. };
  46615. FreeCameraMouseInput.prototype.getClassName = function () {
  46616. return "FreeCameraMouseInput";
  46617. };
  46618. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46619. return "mouse";
  46620. };
  46621. __decorate([
  46622. BABYLON.serialize()
  46623. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46624. __decorate([
  46625. BABYLON.serialize()
  46626. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46627. return FreeCameraMouseInput;
  46628. }());
  46629. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46630. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46631. })(BABYLON || (BABYLON = {}));
  46632. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46633. var BABYLON;
  46634. (function (BABYLON) {
  46635. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46636. function FreeCameraKeyboardMoveInput() {
  46637. this._keys = new Array();
  46638. this.keysUp = [38];
  46639. this.keysDown = [40];
  46640. this.keysLeft = [37];
  46641. this.keysRight = [39];
  46642. }
  46643. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46644. var _this = this;
  46645. if (this._onCanvasBlurObserver) {
  46646. return;
  46647. }
  46648. this._scene = this.camera.getScene();
  46649. this._engine = this._scene.getEngine();
  46650. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46651. _this._keys = [];
  46652. });
  46653. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46654. var evt = info.event;
  46655. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46656. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46657. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46658. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46659. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46660. var index = _this._keys.indexOf(evt.keyCode);
  46661. if (index === -1) {
  46662. _this._keys.push(evt.keyCode);
  46663. }
  46664. if (!noPreventDefault) {
  46665. evt.preventDefault();
  46666. }
  46667. }
  46668. }
  46669. else {
  46670. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46671. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46672. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46673. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46674. var index = _this._keys.indexOf(evt.keyCode);
  46675. if (index >= 0) {
  46676. _this._keys.splice(index, 1);
  46677. }
  46678. if (!noPreventDefault) {
  46679. evt.preventDefault();
  46680. }
  46681. }
  46682. }
  46683. });
  46684. };
  46685. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46686. if (this._scene) {
  46687. if (this._onKeyboardObserver) {
  46688. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46689. }
  46690. if (this._onCanvasBlurObserver) {
  46691. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46692. }
  46693. this._onKeyboardObserver = null;
  46694. this._onCanvasBlurObserver = null;
  46695. }
  46696. this._keys = [];
  46697. };
  46698. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46699. if (this._onKeyboardObserver) {
  46700. var camera = this.camera;
  46701. // Keyboard
  46702. for (var index = 0; index < this._keys.length; index++) {
  46703. var keyCode = this._keys[index];
  46704. var speed = camera._computeLocalCameraSpeed();
  46705. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46706. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46707. }
  46708. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46709. camera._localDirection.copyFromFloats(0, 0, speed);
  46710. }
  46711. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46712. camera._localDirection.copyFromFloats(speed, 0, 0);
  46713. }
  46714. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46715. camera._localDirection.copyFromFloats(0, 0, -speed);
  46716. }
  46717. if (camera.getScene().useRightHandedSystem) {
  46718. camera._localDirection.z *= -1;
  46719. }
  46720. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46721. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46722. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46723. }
  46724. }
  46725. };
  46726. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46727. return "FreeCameraKeyboardMoveInput";
  46728. };
  46729. /** @hidden */
  46730. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46731. this._keys = [];
  46732. };
  46733. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46734. return "keyboard";
  46735. };
  46736. __decorate([
  46737. BABYLON.serialize()
  46738. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46739. __decorate([
  46740. BABYLON.serialize()
  46741. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46742. __decorate([
  46743. BABYLON.serialize()
  46744. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46745. __decorate([
  46746. BABYLON.serialize()
  46747. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46748. return FreeCameraKeyboardMoveInput;
  46749. }());
  46750. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46751. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46752. })(BABYLON || (BABYLON = {}));
  46753. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46754. var BABYLON;
  46755. (function (BABYLON) {
  46756. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46757. __extends(FreeCameraInputsManager, _super);
  46758. function FreeCameraInputsManager(camera) {
  46759. return _super.call(this, camera) || this;
  46760. }
  46761. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46762. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46763. return this;
  46764. };
  46765. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46766. if (touchEnabled === void 0) { touchEnabled = true; }
  46767. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46768. return this;
  46769. };
  46770. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46771. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46772. return this;
  46773. };
  46774. FreeCameraInputsManager.prototype.addTouch = function () {
  46775. this.add(new BABYLON.FreeCameraTouchInput());
  46776. return this;
  46777. };
  46778. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46779. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46780. return this;
  46781. };
  46782. return FreeCameraInputsManager;
  46783. }(BABYLON.CameraInputsManager));
  46784. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46785. })(BABYLON || (BABYLON = {}));
  46786. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46787. var BABYLON;
  46788. (function (BABYLON) {
  46789. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46790. // Forcing to use the Universal camera
  46791. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46792. });
  46793. var FreeCamera = /** @class */ (function (_super) {
  46794. __extends(FreeCamera, _super);
  46795. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46796. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46797. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46798. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46799. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46800. _this.checkCollisions = false;
  46801. _this.applyGravity = false;
  46802. _this._needMoveForGravity = false;
  46803. _this._oldPosition = BABYLON.Vector3.Zero();
  46804. _this._diffPosition = BABYLON.Vector3.Zero();
  46805. _this._newPosition = BABYLON.Vector3.Zero();
  46806. // Collisions
  46807. _this._collisionMask = -1;
  46808. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46809. if (collidedMesh === void 0) { collidedMesh = null; }
  46810. //TODO move this to the collision coordinator!
  46811. if (_this.getScene().workerCollisions)
  46812. newPosition.multiplyInPlace(_this._collider._radius);
  46813. var updatePosition = function (newPos) {
  46814. _this._newPosition.copyFrom(newPos);
  46815. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46816. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46817. _this.position.addInPlace(_this._diffPosition);
  46818. if (_this.onCollide && collidedMesh) {
  46819. _this.onCollide(collidedMesh);
  46820. }
  46821. }
  46822. };
  46823. updatePosition(newPosition);
  46824. };
  46825. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46826. _this.inputs.addKeyboard().addMouse();
  46827. return _this;
  46828. }
  46829. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46830. //-- begin properties for backward compatibility for inputs
  46831. /**
  46832. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46833. * Higher values reduce sensitivity.
  46834. */
  46835. get: function () {
  46836. var mouse = this.inputs.attached["mouse"];
  46837. if (mouse)
  46838. return mouse.angularSensibility;
  46839. return 0;
  46840. },
  46841. /**
  46842. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46843. * Higher values reduce sensitivity.
  46844. */
  46845. set: function (value) {
  46846. var mouse = this.inputs.attached["mouse"];
  46847. if (mouse)
  46848. mouse.angularSensibility = value;
  46849. },
  46850. enumerable: true,
  46851. configurable: true
  46852. });
  46853. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46854. get: function () {
  46855. var keyboard = this.inputs.attached["keyboard"];
  46856. if (keyboard)
  46857. return keyboard.keysUp;
  46858. return [];
  46859. },
  46860. set: function (value) {
  46861. var keyboard = this.inputs.attached["keyboard"];
  46862. if (keyboard)
  46863. keyboard.keysUp = value;
  46864. },
  46865. enumerable: true,
  46866. configurable: true
  46867. });
  46868. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46869. get: function () {
  46870. var keyboard = this.inputs.attached["keyboard"];
  46871. if (keyboard)
  46872. return keyboard.keysDown;
  46873. return [];
  46874. },
  46875. set: function (value) {
  46876. var keyboard = this.inputs.attached["keyboard"];
  46877. if (keyboard)
  46878. keyboard.keysDown = value;
  46879. },
  46880. enumerable: true,
  46881. configurable: true
  46882. });
  46883. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46884. get: function () {
  46885. var keyboard = this.inputs.attached["keyboard"];
  46886. if (keyboard)
  46887. return keyboard.keysLeft;
  46888. return [];
  46889. },
  46890. set: function (value) {
  46891. var keyboard = this.inputs.attached["keyboard"];
  46892. if (keyboard)
  46893. keyboard.keysLeft = value;
  46894. },
  46895. enumerable: true,
  46896. configurable: true
  46897. });
  46898. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46899. get: function () {
  46900. var keyboard = this.inputs.attached["keyboard"];
  46901. if (keyboard)
  46902. return keyboard.keysRight;
  46903. return [];
  46904. },
  46905. set: function (value) {
  46906. var keyboard = this.inputs.attached["keyboard"];
  46907. if (keyboard)
  46908. keyboard.keysRight = value;
  46909. },
  46910. enumerable: true,
  46911. configurable: true
  46912. });
  46913. // Controls
  46914. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46915. this.inputs.attachElement(element, noPreventDefault);
  46916. };
  46917. FreeCamera.prototype.detachControl = function (element) {
  46918. this.inputs.detachElement(element);
  46919. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46920. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46921. };
  46922. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46923. get: function () {
  46924. return this._collisionMask;
  46925. },
  46926. set: function (mask) {
  46927. this._collisionMask = !isNaN(mask) ? mask : -1;
  46928. },
  46929. enumerable: true,
  46930. configurable: true
  46931. });
  46932. /** @hidden */
  46933. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46934. var globalPosition;
  46935. if (this.parent) {
  46936. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46937. }
  46938. else {
  46939. globalPosition = this.position;
  46940. }
  46941. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46942. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46943. if (!this._collider) {
  46944. this._collider = new BABYLON.Collider();
  46945. }
  46946. this._collider._radius = this.ellipsoid;
  46947. this._collider.collisionMask = this._collisionMask;
  46948. //no need for clone, as long as gravity is not on.
  46949. var actualDisplacement = displacement;
  46950. //add gravity to the direction to prevent the dual-collision checking
  46951. if (this.applyGravity) {
  46952. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46953. actualDisplacement = displacement.add(this.getScene().gravity);
  46954. }
  46955. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46956. };
  46957. /** @hidden */
  46958. FreeCamera.prototype._checkInputs = function () {
  46959. if (!this._localDirection) {
  46960. this._localDirection = BABYLON.Vector3.Zero();
  46961. this._transformedDirection = BABYLON.Vector3.Zero();
  46962. }
  46963. this.inputs.checkInputs();
  46964. _super.prototype._checkInputs.call(this);
  46965. };
  46966. /** @hidden */
  46967. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46968. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46969. };
  46970. /** @hidden */
  46971. FreeCamera.prototype._updatePosition = function () {
  46972. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46973. this._collideWithWorld(this.cameraDirection);
  46974. }
  46975. else {
  46976. _super.prototype._updatePosition.call(this);
  46977. }
  46978. };
  46979. FreeCamera.prototype.dispose = function () {
  46980. this.inputs.clear();
  46981. _super.prototype.dispose.call(this);
  46982. };
  46983. FreeCamera.prototype.getClassName = function () {
  46984. return "FreeCamera";
  46985. };
  46986. __decorate([
  46987. BABYLON.serializeAsVector3()
  46988. ], FreeCamera.prototype, "ellipsoid", void 0);
  46989. __decorate([
  46990. BABYLON.serializeAsVector3()
  46991. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46992. __decorate([
  46993. BABYLON.serialize()
  46994. ], FreeCamera.prototype, "checkCollisions", void 0);
  46995. __decorate([
  46996. BABYLON.serialize()
  46997. ], FreeCamera.prototype, "applyGravity", void 0);
  46998. return FreeCamera;
  46999. }(BABYLON.TargetCamera));
  47000. BABYLON.FreeCamera = FreeCamera;
  47001. })(BABYLON || (BABYLON = {}));
  47002. //# sourceMappingURL=babylon.freeCamera.js.map
  47003. var BABYLON;
  47004. (function (BABYLON) {
  47005. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47006. function ArcRotateCameraKeyboardMoveInput() {
  47007. this._keys = new Array();
  47008. this.keysUp = [38];
  47009. this.keysDown = [40];
  47010. this.keysLeft = [37];
  47011. this.keysRight = [39];
  47012. this.keysReset = [220];
  47013. this.panningSensibility = 50.0;
  47014. this.zoomingSensibility = 25.0;
  47015. this.useAltToZoom = true;
  47016. }
  47017. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47018. var _this = this;
  47019. if (this._onCanvasBlurObserver) {
  47020. return;
  47021. }
  47022. this._scene = this.camera.getScene();
  47023. this._engine = this._scene.getEngine();
  47024. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47025. _this._keys = [];
  47026. });
  47027. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47028. var evt = info.event;
  47029. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47030. _this._ctrlPressed = evt.ctrlKey;
  47031. _this._altPressed = evt.altKey;
  47032. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47033. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47034. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47035. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47036. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47037. var index = _this._keys.indexOf(evt.keyCode);
  47038. if (index === -1) {
  47039. _this._keys.push(evt.keyCode);
  47040. }
  47041. if (evt.preventDefault) {
  47042. if (!noPreventDefault) {
  47043. evt.preventDefault();
  47044. }
  47045. }
  47046. }
  47047. }
  47048. else {
  47049. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47050. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47051. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47052. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47053. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47054. var index = _this._keys.indexOf(evt.keyCode);
  47055. if (index >= 0) {
  47056. _this._keys.splice(index, 1);
  47057. }
  47058. if (evt.preventDefault) {
  47059. if (!noPreventDefault) {
  47060. evt.preventDefault();
  47061. }
  47062. }
  47063. }
  47064. }
  47065. });
  47066. };
  47067. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47068. if (this._scene) {
  47069. if (this._onKeyboardObserver) {
  47070. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47071. }
  47072. if (this._onCanvasBlurObserver) {
  47073. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47074. }
  47075. this._onKeyboardObserver = null;
  47076. this._onCanvasBlurObserver = null;
  47077. }
  47078. this._keys = [];
  47079. };
  47080. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47081. if (this._onKeyboardObserver) {
  47082. var camera = this.camera;
  47083. for (var index = 0; index < this._keys.length; index++) {
  47084. var keyCode = this._keys[index];
  47085. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47086. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47087. camera.inertialPanningX -= 1 / this.panningSensibility;
  47088. }
  47089. else {
  47090. camera.inertialAlphaOffset -= 0.01;
  47091. }
  47092. }
  47093. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47094. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47095. camera.inertialPanningY += 1 / this.panningSensibility;
  47096. }
  47097. else if (this._altPressed && this.useAltToZoom) {
  47098. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47099. }
  47100. else {
  47101. camera.inertialBetaOffset -= 0.01;
  47102. }
  47103. }
  47104. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47105. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47106. camera.inertialPanningX += 1 / this.panningSensibility;
  47107. }
  47108. else {
  47109. camera.inertialAlphaOffset += 0.01;
  47110. }
  47111. }
  47112. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47113. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47114. camera.inertialPanningY -= 1 / this.panningSensibility;
  47115. }
  47116. else if (this._altPressed && this.useAltToZoom) {
  47117. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47118. }
  47119. else {
  47120. camera.inertialBetaOffset += 0.01;
  47121. }
  47122. }
  47123. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47124. camera.restoreState();
  47125. }
  47126. }
  47127. }
  47128. };
  47129. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47130. return "ArcRotateCameraKeyboardMoveInput";
  47131. };
  47132. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47133. return "keyboard";
  47134. };
  47135. __decorate([
  47136. BABYLON.serialize()
  47137. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47138. __decorate([
  47139. BABYLON.serialize()
  47140. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47141. __decorate([
  47142. BABYLON.serialize()
  47143. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47144. __decorate([
  47145. BABYLON.serialize()
  47146. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47147. __decorate([
  47148. BABYLON.serialize()
  47149. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47150. __decorate([
  47151. BABYLON.serialize()
  47152. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47153. __decorate([
  47154. BABYLON.serialize()
  47155. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47156. __decorate([
  47157. BABYLON.serialize()
  47158. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47159. return ArcRotateCameraKeyboardMoveInput;
  47160. }());
  47161. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47162. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47163. })(BABYLON || (BABYLON = {}));
  47164. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47165. var BABYLON;
  47166. (function (BABYLON) {
  47167. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47168. function ArcRotateCameraMouseWheelInput() {
  47169. this.wheelPrecision = 3.0;
  47170. /**
  47171. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47172. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47173. */
  47174. this.wheelDeltaPercentage = 0;
  47175. }
  47176. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47177. var _this = this;
  47178. this._wheel = function (p, s) {
  47179. //sanity check - this should be a PointerWheel event.
  47180. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47181. return;
  47182. var event = p.event;
  47183. var delta = 0;
  47184. if (event.wheelDelta) {
  47185. if (_this.wheelDeltaPercentage) {
  47186. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47187. if (event.wheelDelta > 0) {
  47188. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47189. }
  47190. else {
  47191. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47192. }
  47193. }
  47194. else {
  47195. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47196. }
  47197. }
  47198. else if (event.detail) {
  47199. delta = -event.detail / _this.wheelPrecision;
  47200. }
  47201. if (delta)
  47202. _this.camera.inertialRadiusOffset += delta;
  47203. if (event.preventDefault) {
  47204. if (!noPreventDefault) {
  47205. event.preventDefault();
  47206. }
  47207. }
  47208. };
  47209. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47210. };
  47211. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47212. if (this._observer && element) {
  47213. this.camera.getScene().onPointerObservable.remove(this._observer);
  47214. this._observer = null;
  47215. this._wheel = null;
  47216. }
  47217. };
  47218. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47219. return "ArcRotateCameraMouseWheelInput";
  47220. };
  47221. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47222. return "mousewheel";
  47223. };
  47224. __decorate([
  47225. BABYLON.serialize()
  47226. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47227. __decorate([
  47228. BABYLON.serialize()
  47229. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47230. return ArcRotateCameraMouseWheelInput;
  47231. }());
  47232. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47233. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47234. })(BABYLON || (BABYLON = {}));
  47235. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47236. var BABYLON;
  47237. (function (BABYLON) {
  47238. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47239. function ArcRotateCameraPointersInput() {
  47240. this.buttons = [0, 1, 2];
  47241. this.angularSensibilityX = 1000.0;
  47242. this.angularSensibilityY = 1000.0;
  47243. this.pinchPrecision = 12.0;
  47244. /**
  47245. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47246. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47247. */
  47248. this.pinchDeltaPercentage = 0;
  47249. this.panningSensibility = 1000.0;
  47250. this.multiTouchPanning = true;
  47251. this.multiTouchPanAndZoom = true;
  47252. this._isPanClick = false;
  47253. this.pinchInwards = true;
  47254. }
  47255. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47256. var _this = this;
  47257. var engine = this.camera.getEngine();
  47258. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47259. var pointA = null;
  47260. var pointB = null;
  47261. var previousPinchSquaredDistance = 0;
  47262. var initialDistance = 0;
  47263. var twoFingerActivityCount = 0;
  47264. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47265. this._pointerInput = function (p, s) {
  47266. var evt = p.event;
  47267. var isTouch = p.event.pointerType === "touch";
  47268. if (engine.isInVRExclusivePointerMode) {
  47269. return;
  47270. }
  47271. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47272. return;
  47273. }
  47274. var srcElement = (evt.srcElement || evt.target);
  47275. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47276. try {
  47277. srcElement.setPointerCapture(evt.pointerId);
  47278. }
  47279. catch (e) {
  47280. //Nothing to do with the error. Execution will continue.
  47281. }
  47282. // Manage panning with pan button click
  47283. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47284. // manage pointers
  47285. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47286. if (pointA === null) {
  47287. pointA = cacheSoloPointer;
  47288. }
  47289. else if (pointB === null) {
  47290. pointB = cacheSoloPointer;
  47291. }
  47292. if (!noPreventDefault) {
  47293. evt.preventDefault();
  47294. element.focus();
  47295. }
  47296. }
  47297. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47298. _this.camera.restoreState();
  47299. }
  47300. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47301. try {
  47302. srcElement.releasePointerCapture(evt.pointerId);
  47303. }
  47304. catch (e) {
  47305. //Nothing to do with the error.
  47306. }
  47307. cacheSoloPointer = null;
  47308. previousPinchSquaredDistance = 0;
  47309. previousMultiTouchPanPosition.isPaning = false;
  47310. previousMultiTouchPanPosition.isPinching = false;
  47311. twoFingerActivityCount = 0;
  47312. initialDistance = 0;
  47313. if (!isTouch) {
  47314. pointB = null; // Mouse and pen are mono pointer
  47315. }
  47316. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47317. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47318. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47319. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47320. if (engine._badOS) {
  47321. pointA = pointB = null;
  47322. }
  47323. else {
  47324. //only remove the impacted pointer in case of multitouch allowing on most
  47325. //platforms switching from rotate to zoom and pan seamlessly.
  47326. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47327. pointA = pointB;
  47328. pointB = null;
  47329. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47330. }
  47331. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47332. pointB = null;
  47333. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47334. }
  47335. else {
  47336. pointA = pointB = null;
  47337. }
  47338. }
  47339. if (!noPreventDefault) {
  47340. evt.preventDefault();
  47341. }
  47342. }
  47343. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47344. if (!noPreventDefault) {
  47345. evt.preventDefault();
  47346. }
  47347. // One button down
  47348. if (pointA && pointB === null && cacheSoloPointer) {
  47349. if (_this.panningSensibility !== 0 &&
  47350. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47351. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47352. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47353. }
  47354. else {
  47355. var offsetX = evt.clientX - cacheSoloPointer.x;
  47356. var offsetY = evt.clientY - cacheSoloPointer.y;
  47357. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47358. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47359. }
  47360. cacheSoloPointer.x = evt.clientX;
  47361. cacheSoloPointer.y = evt.clientY;
  47362. }
  47363. // Two buttons down: pinch/pan
  47364. else if (pointA && pointB) {
  47365. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47366. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47367. ed.x = evt.clientX;
  47368. ed.y = evt.clientY;
  47369. var direction = _this.pinchInwards ? 1 : -1;
  47370. var distX = pointA.x - pointB.x;
  47371. var distY = pointA.y - pointB.y;
  47372. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47373. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47374. if (previousPinchSquaredDistance === 0) {
  47375. initialDistance = pinchDistance;
  47376. previousPinchSquaredDistance = pinchSquaredDistance;
  47377. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47378. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47379. return;
  47380. }
  47381. if (_this.multiTouchPanAndZoom) {
  47382. if (_this.pinchDeltaPercentage) {
  47383. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47384. }
  47385. else {
  47386. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47387. (_this.pinchPrecision *
  47388. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47389. direction);
  47390. }
  47391. if (_this.panningSensibility !== 0) {
  47392. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47393. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47394. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47395. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47396. previousMultiTouchPanPosition.x = pointersCenterX;
  47397. previousMultiTouchPanPosition.y = pointersCenterY;
  47398. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47399. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47400. }
  47401. }
  47402. else {
  47403. twoFingerActivityCount++;
  47404. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47405. if (_this.pinchDeltaPercentage) {
  47406. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47407. }
  47408. else {
  47409. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47410. (_this.pinchPrecision *
  47411. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47412. direction);
  47413. }
  47414. previousMultiTouchPanPosition.isPaning = false;
  47415. previousMultiTouchPanPosition.isPinching = true;
  47416. }
  47417. else {
  47418. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47419. if (!previousMultiTouchPanPosition.isPaning) {
  47420. previousMultiTouchPanPosition.isPaning = true;
  47421. previousMultiTouchPanPosition.isPinching = false;
  47422. previousMultiTouchPanPosition.x = ed.x;
  47423. previousMultiTouchPanPosition.y = ed.y;
  47424. return;
  47425. }
  47426. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47427. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47428. }
  47429. }
  47430. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47431. previousMultiTouchPanPosition.x = ed.x;
  47432. previousMultiTouchPanPosition.y = ed.y;
  47433. }
  47434. }
  47435. previousPinchSquaredDistance = pinchSquaredDistance;
  47436. }
  47437. }
  47438. };
  47439. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47440. this._onContextMenu = function (evt) {
  47441. evt.preventDefault();
  47442. };
  47443. if (!this.camera._useCtrlForPanning) {
  47444. element.addEventListener("contextmenu", this._onContextMenu, false);
  47445. }
  47446. this._onLostFocus = function () {
  47447. //this._keys = [];
  47448. pointA = pointB = null;
  47449. previousPinchSquaredDistance = 0;
  47450. previousMultiTouchPanPosition.isPaning = false;
  47451. previousMultiTouchPanPosition.isPinching = false;
  47452. twoFingerActivityCount = 0;
  47453. cacheSoloPointer = null;
  47454. initialDistance = 0;
  47455. };
  47456. this._onMouseMove = function (evt) {
  47457. if (!engine.isPointerLock) {
  47458. return;
  47459. }
  47460. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47461. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47462. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47463. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47464. if (!noPreventDefault) {
  47465. evt.preventDefault();
  47466. }
  47467. };
  47468. this._onGestureStart = function (e) {
  47469. if (window.MSGesture === undefined) {
  47470. return;
  47471. }
  47472. if (!_this._MSGestureHandler) {
  47473. _this._MSGestureHandler = new MSGesture();
  47474. _this._MSGestureHandler.target = element;
  47475. }
  47476. _this._MSGestureHandler.addPointer(e.pointerId);
  47477. };
  47478. this._onGesture = function (e) {
  47479. _this.camera.radius *= e.scale;
  47480. if (e.preventDefault) {
  47481. if (!noPreventDefault) {
  47482. e.stopPropagation();
  47483. e.preventDefault();
  47484. }
  47485. }
  47486. };
  47487. element.addEventListener("mousemove", this._onMouseMove, false);
  47488. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47489. element.addEventListener("MSGestureChange", this._onGesture, false);
  47490. BABYLON.Tools.RegisterTopRootEvents([
  47491. { name: "blur", handler: this._onLostFocus }
  47492. ]);
  47493. };
  47494. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47495. if (this._onLostFocus) {
  47496. BABYLON.Tools.UnregisterTopRootEvents([
  47497. { name: "blur", handler: this._onLostFocus }
  47498. ]);
  47499. }
  47500. if (element && this._observer) {
  47501. this.camera.getScene().onPointerObservable.remove(this._observer);
  47502. this._observer = null;
  47503. if (this._onContextMenu) {
  47504. element.removeEventListener("contextmenu", this._onContextMenu);
  47505. }
  47506. if (this._onMouseMove) {
  47507. element.removeEventListener("mousemove", this._onMouseMove);
  47508. }
  47509. if (this._onGestureStart) {
  47510. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47511. }
  47512. if (this._onGesture) {
  47513. element.removeEventListener("MSGestureChange", this._onGesture);
  47514. }
  47515. this._isPanClick = false;
  47516. this.pinchInwards = true;
  47517. this._onMouseMove = null;
  47518. this._onGestureStart = null;
  47519. this._onGesture = null;
  47520. this._MSGestureHandler = null;
  47521. this._onLostFocus = null;
  47522. this._onContextMenu = null;
  47523. }
  47524. };
  47525. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47526. return "ArcRotateCameraPointersInput";
  47527. };
  47528. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47529. return "pointers";
  47530. };
  47531. __decorate([
  47532. BABYLON.serialize()
  47533. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47534. __decorate([
  47535. BABYLON.serialize()
  47536. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47537. __decorate([
  47538. BABYLON.serialize()
  47539. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47540. __decorate([
  47541. BABYLON.serialize()
  47542. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47543. __decorate([
  47544. BABYLON.serialize()
  47545. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47546. __decorate([
  47547. BABYLON.serialize()
  47548. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47549. __decorate([
  47550. BABYLON.serialize()
  47551. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47552. __decorate([
  47553. BABYLON.serialize()
  47554. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47555. return ArcRotateCameraPointersInput;
  47556. }());
  47557. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47558. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47559. })(BABYLON || (BABYLON = {}));
  47560. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47561. var BABYLON;
  47562. (function (BABYLON) {
  47563. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47564. __extends(ArcRotateCameraInputsManager, _super);
  47565. function ArcRotateCameraInputsManager(camera) {
  47566. return _super.call(this, camera) || this;
  47567. }
  47568. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47569. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47570. return this;
  47571. };
  47572. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47573. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47574. return this;
  47575. };
  47576. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47577. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47578. return this;
  47579. };
  47580. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47581. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47582. return this;
  47583. };
  47584. return ArcRotateCameraInputsManager;
  47585. }(BABYLON.CameraInputsManager));
  47586. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47587. })(BABYLON || (BABYLON = {}));
  47588. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47589. var BABYLON;
  47590. (function (BABYLON) {
  47591. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47592. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47593. });
  47594. var ArcRotateCamera = /** @class */ (function (_super) {
  47595. __extends(ArcRotateCamera, _super);
  47596. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47597. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47598. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47599. _this.inertialAlphaOffset = 0;
  47600. _this.inertialBetaOffset = 0;
  47601. _this.inertialRadiusOffset = 0;
  47602. _this.lowerAlphaLimit = null;
  47603. _this.upperAlphaLimit = null;
  47604. _this.lowerBetaLimit = 0.01;
  47605. _this.upperBetaLimit = Math.PI;
  47606. _this.lowerRadiusLimit = null;
  47607. _this.upperRadiusLimit = null;
  47608. _this.inertialPanningX = 0;
  47609. _this.inertialPanningY = 0;
  47610. _this.pinchToPanMaxDistance = 20;
  47611. _this.panningDistanceLimit = null;
  47612. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47613. _this.panningInertia = 0.9;
  47614. //-- end properties for backward compatibility for inputs
  47615. _this.zoomOnFactor = 1;
  47616. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47617. _this.allowUpsideDown = true;
  47618. /** @hidden */
  47619. _this._viewMatrix = new BABYLON.Matrix();
  47620. // Panning
  47621. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47622. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47623. _this.checkCollisions = false;
  47624. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47625. _this._previousPosition = BABYLON.Vector3.Zero();
  47626. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47627. _this._newPosition = BABYLON.Vector3.Zero();
  47628. _this._computationVector = BABYLON.Vector3.Zero();
  47629. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47630. if (collidedMesh === void 0) { collidedMesh = null; }
  47631. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47632. newPosition.multiplyInPlace(_this._collider._radius);
  47633. }
  47634. if (!collidedMesh) {
  47635. _this._previousPosition.copyFrom(_this.position);
  47636. }
  47637. else {
  47638. _this.setPosition(newPosition);
  47639. if (_this.onCollide) {
  47640. _this.onCollide(collidedMesh);
  47641. }
  47642. }
  47643. // Recompute because of constraints
  47644. var cosa = Math.cos(_this.alpha);
  47645. var sina = Math.sin(_this.alpha);
  47646. var cosb = Math.cos(_this.beta);
  47647. var sinb = Math.sin(_this.beta);
  47648. if (sinb === 0) {
  47649. sinb = 0.0001;
  47650. }
  47651. var target = _this._getTargetPosition();
  47652. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47653. target.addToRef(_this._computationVector, _this._newPosition);
  47654. _this.position.copyFrom(_this._newPosition);
  47655. var up = _this.upVector;
  47656. if (_this.allowUpsideDown && _this.beta < 0) {
  47657. up = up.clone();
  47658. up = up.negate();
  47659. }
  47660. _this._computeViewMatrix(_this.position, target, up);
  47661. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47662. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47663. _this._collisionTriggered = false;
  47664. };
  47665. _this._target = BABYLON.Vector3.Zero();
  47666. if (target) {
  47667. _this.setTarget(target);
  47668. }
  47669. _this.alpha = alpha;
  47670. _this.beta = beta;
  47671. _this.radius = radius;
  47672. _this.getViewMatrix();
  47673. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47674. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47675. return _this;
  47676. }
  47677. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47678. get: function () {
  47679. return this._target;
  47680. },
  47681. set: function (value) {
  47682. this.setTarget(value);
  47683. },
  47684. enumerable: true,
  47685. configurable: true
  47686. });
  47687. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47688. //-- begin properties for backward compatibility for inputs
  47689. get: function () {
  47690. var pointers = this.inputs.attached["pointers"];
  47691. if (pointers)
  47692. return pointers.angularSensibilityX;
  47693. return 0;
  47694. },
  47695. set: function (value) {
  47696. var pointers = this.inputs.attached["pointers"];
  47697. if (pointers) {
  47698. pointers.angularSensibilityX = value;
  47699. }
  47700. },
  47701. enumerable: true,
  47702. configurable: true
  47703. });
  47704. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47705. get: function () {
  47706. var pointers = this.inputs.attached["pointers"];
  47707. if (pointers)
  47708. return pointers.angularSensibilityY;
  47709. return 0;
  47710. },
  47711. set: function (value) {
  47712. var pointers = this.inputs.attached["pointers"];
  47713. if (pointers) {
  47714. pointers.angularSensibilityY = value;
  47715. }
  47716. },
  47717. enumerable: true,
  47718. configurable: true
  47719. });
  47720. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47721. get: function () {
  47722. var pointers = this.inputs.attached["pointers"];
  47723. if (pointers)
  47724. return pointers.pinchPrecision;
  47725. return 0;
  47726. },
  47727. set: function (value) {
  47728. var pointers = this.inputs.attached["pointers"];
  47729. if (pointers) {
  47730. pointers.pinchPrecision = value;
  47731. }
  47732. },
  47733. enumerable: true,
  47734. configurable: true
  47735. });
  47736. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47737. get: function () {
  47738. var pointers = this.inputs.attached["pointers"];
  47739. if (pointers)
  47740. return pointers.pinchDeltaPercentage;
  47741. return 0;
  47742. },
  47743. set: function (value) {
  47744. var pointers = this.inputs.attached["pointers"];
  47745. if (pointers) {
  47746. pointers.pinchDeltaPercentage = value;
  47747. }
  47748. },
  47749. enumerable: true,
  47750. configurable: true
  47751. });
  47752. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47753. get: function () {
  47754. var pointers = this.inputs.attached["pointers"];
  47755. if (pointers)
  47756. return pointers.panningSensibility;
  47757. return 0;
  47758. },
  47759. set: function (value) {
  47760. var pointers = this.inputs.attached["pointers"];
  47761. if (pointers) {
  47762. pointers.panningSensibility = value;
  47763. }
  47764. },
  47765. enumerable: true,
  47766. configurable: true
  47767. });
  47768. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47769. get: function () {
  47770. var keyboard = this.inputs.attached["keyboard"];
  47771. if (keyboard)
  47772. return keyboard.keysUp;
  47773. return [];
  47774. },
  47775. set: function (value) {
  47776. var keyboard = this.inputs.attached["keyboard"];
  47777. if (keyboard)
  47778. keyboard.keysUp = value;
  47779. },
  47780. enumerable: true,
  47781. configurable: true
  47782. });
  47783. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47784. get: function () {
  47785. var keyboard = this.inputs.attached["keyboard"];
  47786. if (keyboard)
  47787. return keyboard.keysDown;
  47788. return [];
  47789. },
  47790. set: function (value) {
  47791. var keyboard = this.inputs.attached["keyboard"];
  47792. if (keyboard)
  47793. keyboard.keysDown = value;
  47794. },
  47795. enumerable: true,
  47796. configurable: true
  47797. });
  47798. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47799. get: function () {
  47800. var keyboard = this.inputs.attached["keyboard"];
  47801. if (keyboard)
  47802. return keyboard.keysLeft;
  47803. return [];
  47804. },
  47805. set: function (value) {
  47806. var keyboard = this.inputs.attached["keyboard"];
  47807. if (keyboard)
  47808. keyboard.keysLeft = value;
  47809. },
  47810. enumerable: true,
  47811. configurable: true
  47812. });
  47813. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47814. get: function () {
  47815. var keyboard = this.inputs.attached["keyboard"];
  47816. if (keyboard)
  47817. return keyboard.keysRight;
  47818. return [];
  47819. },
  47820. set: function (value) {
  47821. var keyboard = this.inputs.attached["keyboard"];
  47822. if (keyboard)
  47823. keyboard.keysRight = value;
  47824. },
  47825. enumerable: true,
  47826. configurable: true
  47827. });
  47828. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47829. get: function () {
  47830. var mousewheel = this.inputs.attached["mousewheel"];
  47831. if (mousewheel)
  47832. return mousewheel.wheelPrecision;
  47833. return 0;
  47834. },
  47835. set: function (value) {
  47836. var mousewheel = this.inputs.attached["mousewheel"];
  47837. if (mousewheel)
  47838. mousewheel.wheelPrecision = value;
  47839. },
  47840. enumerable: true,
  47841. configurable: true
  47842. });
  47843. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47844. get: function () {
  47845. var mousewheel = this.inputs.attached["mousewheel"];
  47846. if (mousewheel)
  47847. return mousewheel.wheelDeltaPercentage;
  47848. return 0;
  47849. },
  47850. set: function (value) {
  47851. var mousewheel = this.inputs.attached["mousewheel"];
  47852. if (mousewheel)
  47853. mousewheel.wheelDeltaPercentage = value;
  47854. },
  47855. enumerable: true,
  47856. configurable: true
  47857. });
  47858. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47859. get: function () {
  47860. return this._bouncingBehavior;
  47861. },
  47862. enumerable: true,
  47863. configurable: true
  47864. });
  47865. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47866. get: function () {
  47867. return this._bouncingBehavior != null;
  47868. },
  47869. set: function (value) {
  47870. if (value === this.useBouncingBehavior) {
  47871. return;
  47872. }
  47873. if (value) {
  47874. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47875. this.addBehavior(this._bouncingBehavior);
  47876. }
  47877. else if (this._bouncingBehavior) {
  47878. this.removeBehavior(this._bouncingBehavior);
  47879. this._bouncingBehavior = null;
  47880. }
  47881. },
  47882. enumerable: true,
  47883. configurable: true
  47884. });
  47885. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47886. get: function () {
  47887. return this._framingBehavior;
  47888. },
  47889. enumerable: true,
  47890. configurable: true
  47891. });
  47892. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47893. get: function () {
  47894. return this._framingBehavior != null;
  47895. },
  47896. set: function (value) {
  47897. if (value === this.useFramingBehavior) {
  47898. return;
  47899. }
  47900. if (value) {
  47901. this._framingBehavior = new BABYLON.FramingBehavior();
  47902. this.addBehavior(this._framingBehavior);
  47903. }
  47904. else if (this._framingBehavior) {
  47905. this.removeBehavior(this._framingBehavior);
  47906. this._framingBehavior = null;
  47907. }
  47908. },
  47909. enumerable: true,
  47910. configurable: true
  47911. });
  47912. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47913. get: function () {
  47914. return this._autoRotationBehavior;
  47915. },
  47916. enumerable: true,
  47917. configurable: true
  47918. });
  47919. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47920. get: function () {
  47921. return this._autoRotationBehavior != null;
  47922. },
  47923. set: function (value) {
  47924. if (value === this.useAutoRotationBehavior) {
  47925. return;
  47926. }
  47927. if (value) {
  47928. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47929. this.addBehavior(this._autoRotationBehavior);
  47930. }
  47931. else if (this._autoRotationBehavior) {
  47932. this.removeBehavior(this._autoRotationBehavior);
  47933. this._autoRotationBehavior = null;
  47934. }
  47935. },
  47936. enumerable: true,
  47937. configurable: true
  47938. });
  47939. // Cache
  47940. /** @hidden */
  47941. ArcRotateCamera.prototype._initCache = function () {
  47942. _super.prototype._initCache.call(this);
  47943. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47944. this._cache.alpha = undefined;
  47945. this._cache.beta = undefined;
  47946. this._cache.radius = undefined;
  47947. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47948. };
  47949. /** @hidden */
  47950. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47951. if (!ignoreParentClass) {
  47952. _super.prototype._updateCache.call(this);
  47953. }
  47954. this._cache._target.copyFrom(this._getTargetPosition());
  47955. this._cache.alpha = this.alpha;
  47956. this._cache.beta = this.beta;
  47957. this._cache.radius = this.radius;
  47958. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47959. };
  47960. ArcRotateCamera.prototype._getTargetPosition = function () {
  47961. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47962. var pos = this._targetHost.getAbsolutePosition();
  47963. if (this._targetBoundingCenter) {
  47964. pos.addToRef(this._targetBoundingCenter, this._target);
  47965. }
  47966. else {
  47967. this._target.copyFrom(pos);
  47968. }
  47969. }
  47970. var lockedTargetPosition = this._getLockedTargetPosition();
  47971. if (lockedTargetPosition) {
  47972. return lockedTargetPosition;
  47973. }
  47974. return this._target;
  47975. };
  47976. ArcRotateCamera.prototype.storeState = function () {
  47977. this._storedAlpha = this.alpha;
  47978. this._storedBeta = this.beta;
  47979. this._storedRadius = this.radius;
  47980. this._storedTarget = this._getTargetPosition().clone();
  47981. return _super.prototype.storeState.call(this);
  47982. };
  47983. /**
  47984. * @hidden
  47985. * Restored camera state. You must call storeState() first
  47986. */
  47987. ArcRotateCamera.prototype._restoreStateValues = function () {
  47988. if (!_super.prototype._restoreStateValues.call(this)) {
  47989. return false;
  47990. }
  47991. this.alpha = this._storedAlpha;
  47992. this.beta = this._storedBeta;
  47993. this.radius = this._storedRadius;
  47994. this.setTarget(this._storedTarget.clone());
  47995. this.inertialAlphaOffset = 0;
  47996. this.inertialBetaOffset = 0;
  47997. this.inertialRadiusOffset = 0;
  47998. this.inertialPanningX = 0;
  47999. this.inertialPanningY = 0;
  48000. return true;
  48001. };
  48002. // Synchronized
  48003. /** @hidden */
  48004. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48005. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48006. return false;
  48007. return this._cache._target.equals(this._getTargetPosition())
  48008. && this._cache.alpha === this.alpha
  48009. && this._cache.beta === this.beta
  48010. && this._cache.radius === this.radius
  48011. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48012. };
  48013. // Methods
  48014. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48015. var _this = this;
  48016. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48017. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48018. this._useCtrlForPanning = useCtrlForPanning;
  48019. this._panningMouseButton = panningMouseButton;
  48020. this.inputs.attachElement(element, noPreventDefault);
  48021. this._reset = function () {
  48022. _this.inertialAlphaOffset = 0;
  48023. _this.inertialBetaOffset = 0;
  48024. _this.inertialRadiusOffset = 0;
  48025. _this.inertialPanningX = 0;
  48026. _this.inertialPanningY = 0;
  48027. };
  48028. };
  48029. ArcRotateCamera.prototype.detachControl = function (element) {
  48030. this.inputs.detachElement(element);
  48031. if (this._reset) {
  48032. this._reset();
  48033. }
  48034. };
  48035. /** @hidden */
  48036. ArcRotateCamera.prototype._checkInputs = function () {
  48037. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48038. if (this._collisionTriggered) {
  48039. return;
  48040. }
  48041. this.inputs.checkInputs();
  48042. // Inertia
  48043. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48044. var inertialAlphaOffset = this.inertialAlphaOffset;
  48045. if (this.beta <= 0)
  48046. inertialAlphaOffset *= -1;
  48047. if (this.getScene().useRightHandedSystem)
  48048. inertialAlphaOffset *= -1;
  48049. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48050. inertialAlphaOffset *= -1;
  48051. this.alpha += inertialAlphaOffset;
  48052. this.beta += this.inertialBetaOffset;
  48053. this.radius -= this.inertialRadiusOffset;
  48054. this.inertialAlphaOffset *= this.inertia;
  48055. this.inertialBetaOffset *= this.inertia;
  48056. this.inertialRadiusOffset *= this.inertia;
  48057. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48058. this.inertialAlphaOffset = 0;
  48059. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48060. this.inertialBetaOffset = 0;
  48061. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48062. this.inertialRadiusOffset = 0;
  48063. }
  48064. // Panning inertia
  48065. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48066. if (!this._localDirection) {
  48067. this._localDirection = BABYLON.Vector3.Zero();
  48068. this._transformedDirection = BABYLON.Vector3.Zero();
  48069. }
  48070. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48071. this._localDirection.multiplyInPlace(this.panningAxis);
  48072. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48073. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48074. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48075. if (!this.panningAxis.y) {
  48076. this._transformedDirection.y = 0;
  48077. }
  48078. if (!this._targetHost) {
  48079. if (this.panningDistanceLimit) {
  48080. this._transformedDirection.addInPlace(this._target);
  48081. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48082. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48083. this._target.copyFrom(this._transformedDirection);
  48084. }
  48085. }
  48086. else {
  48087. this._target.addInPlace(this._transformedDirection);
  48088. }
  48089. }
  48090. this.inertialPanningX *= this.panningInertia;
  48091. this.inertialPanningY *= this.panningInertia;
  48092. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48093. this.inertialPanningX = 0;
  48094. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48095. this.inertialPanningY = 0;
  48096. }
  48097. // Limits
  48098. this._checkLimits();
  48099. _super.prototype._checkInputs.call(this);
  48100. };
  48101. ArcRotateCamera.prototype._checkLimits = function () {
  48102. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48103. if (this.allowUpsideDown && this.beta > Math.PI) {
  48104. this.beta = this.beta - (2 * Math.PI);
  48105. }
  48106. }
  48107. else {
  48108. if (this.beta < this.lowerBetaLimit) {
  48109. this.beta = this.lowerBetaLimit;
  48110. }
  48111. }
  48112. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48113. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48114. this.beta = this.beta + (2 * Math.PI);
  48115. }
  48116. }
  48117. else {
  48118. if (this.beta > this.upperBetaLimit) {
  48119. this.beta = this.upperBetaLimit;
  48120. }
  48121. }
  48122. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48123. this.alpha = this.lowerAlphaLimit;
  48124. }
  48125. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48126. this.alpha = this.upperAlphaLimit;
  48127. }
  48128. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48129. this.radius = this.lowerRadiusLimit;
  48130. }
  48131. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48132. this.radius = this.upperRadiusLimit;
  48133. }
  48134. };
  48135. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48136. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48137. this.radius = this._computationVector.length();
  48138. if (this.radius === 0) {
  48139. this.radius = 0.0001; // Just to avoid division by zero
  48140. }
  48141. // Alpha
  48142. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48143. if (this._computationVector.z < 0) {
  48144. this.alpha = 2 * Math.PI - this.alpha;
  48145. }
  48146. // Beta
  48147. this.beta = Math.acos(this._computationVector.y / this.radius);
  48148. this._checkLimits();
  48149. };
  48150. ArcRotateCamera.prototype.setPosition = function (position) {
  48151. if (this.position.equals(position)) {
  48152. return;
  48153. }
  48154. this.position.copyFrom(position);
  48155. this.rebuildAnglesAndRadius();
  48156. };
  48157. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48158. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48159. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48160. if (target.getBoundingInfo) {
  48161. if (toBoundingCenter) {
  48162. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48163. }
  48164. else {
  48165. this._targetBoundingCenter = null;
  48166. }
  48167. this._targetHost = target;
  48168. this._target = this._getTargetPosition();
  48169. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48170. }
  48171. else {
  48172. var newTarget = target;
  48173. var currentTarget = this._getTargetPosition();
  48174. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48175. return;
  48176. }
  48177. this._targetHost = null;
  48178. this._target = newTarget;
  48179. this._targetBoundingCenter = null;
  48180. this.onMeshTargetChangedObservable.notifyObservers(null);
  48181. }
  48182. this.rebuildAnglesAndRadius();
  48183. };
  48184. /** @hidden */
  48185. ArcRotateCamera.prototype._getViewMatrix = function () {
  48186. // Compute
  48187. var cosa = Math.cos(this.alpha);
  48188. var sina = Math.sin(this.alpha);
  48189. var cosb = Math.cos(this.beta);
  48190. var sinb = Math.sin(this.beta);
  48191. if (sinb === 0) {
  48192. sinb = 0.0001;
  48193. }
  48194. var target = this._getTargetPosition();
  48195. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48196. target.addToRef(this._computationVector, this._newPosition);
  48197. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48198. if (!this._collider) {
  48199. this._collider = new BABYLON.Collider();
  48200. }
  48201. this._collider._radius = this.collisionRadius;
  48202. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48203. this._collisionTriggered = true;
  48204. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48205. }
  48206. else {
  48207. this.position.copyFrom(this._newPosition);
  48208. var up = this.upVector;
  48209. if (this.allowUpsideDown && sinb < 0) {
  48210. up = up.clone();
  48211. up = up.negate();
  48212. }
  48213. this._computeViewMatrix(this.position, target, up);
  48214. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48215. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48216. }
  48217. this._currentTarget = target;
  48218. return this._viewMatrix;
  48219. };
  48220. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48221. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48222. meshes = meshes || this.getScene().meshes;
  48223. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48224. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48225. this.radius = distance * this.zoomOnFactor;
  48226. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48227. };
  48228. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48229. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48230. var meshesOrMinMaxVector;
  48231. var distance;
  48232. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48233. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48234. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48235. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48236. }
  48237. else { //minMaxVector and distance
  48238. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48239. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48240. distance = minMaxVectorAndDistance.distance;
  48241. }
  48242. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48243. if (!doNotUpdateMaxZ) {
  48244. this.maxZ = distance * 2;
  48245. }
  48246. };
  48247. /**
  48248. * @override
  48249. * Override Camera.createRigCamera
  48250. */
  48251. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48252. var alphaShift = 0;
  48253. switch (this.cameraRigMode) {
  48254. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48255. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48256. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48257. case BABYLON.Camera.RIG_MODE_VR:
  48258. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48259. break;
  48260. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48261. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48262. break;
  48263. }
  48264. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48265. rigCam._cameraRigParams = {};
  48266. return rigCam;
  48267. };
  48268. /**
  48269. * @hidden
  48270. * @override
  48271. * Override Camera._updateRigCameras
  48272. */
  48273. ArcRotateCamera.prototype._updateRigCameras = function () {
  48274. var camLeft = this._rigCameras[0];
  48275. var camRight = this._rigCameras[1];
  48276. camLeft.beta = camRight.beta = this.beta;
  48277. camLeft.radius = camRight.radius = this.radius;
  48278. switch (this.cameraRigMode) {
  48279. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48280. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48281. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48282. case BABYLON.Camera.RIG_MODE_VR:
  48283. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48284. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48285. break;
  48286. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48287. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48288. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48289. break;
  48290. }
  48291. _super.prototype._updateRigCameras.call(this);
  48292. };
  48293. ArcRotateCamera.prototype.dispose = function () {
  48294. this.inputs.clear();
  48295. _super.prototype.dispose.call(this);
  48296. };
  48297. ArcRotateCamera.prototype.getClassName = function () {
  48298. return "ArcRotateCamera";
  48299. };
  48300. __decorate([
  48301. BABYLON.serialize()
  48302. ], ArcRotateCamera.prototype, "alpha", void 0);
  48303. __decorate([
  48304. BABYLON.serialize()
  48305. ], ArcRotateCamera.prototype, "beta", void 0);
  48306. __decorate([
  48307. BABYLON.serialize()
  48308. ], ArcRotateCamera.prototype, "radius", void 0);
  48309. __decorate([
  48310. BABYLON.serializeAsVector3("target")
  48311. ], ArcRotateCamera.prototype, "_target", void 0);
  48312. __decorate([
  48313. BABYLON.serialize()
  48314. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48315. __decorate([
  48316. BABYLON.serialize()
  48317. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48318. __decorate([
  48319. BABYLON.serialize()
  48320. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48321. __decorate([
  48322. BABYLON.serialize()
  48323. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48324. __decorate([
  48325. BABYLON.serialize()
  48326. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48327. __decorate([
  48328. BABYLON.serialize()
  48329. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48330. __decorate([
  48331. BABYLON.serialize()
  48332. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48333. __decorate([
  48334. BABYLON.serialize()
  48335. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48336. __decorate([
  48337. BABYLON.serialize()
  48338. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48339. __decorate([
  48340. BABYLON.serialize()
  48341. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48342. __decorate([
  48343. BABYLON.serialize()
  48344. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48345. __decorate([
  48346. BABYLON.serialize()
  48347. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48348. __decorate([
  48349. BABYLON.serialize()
  48350. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48351. __decorate([
  48352. BABYLON.serializeAsVector3()
  48353. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48354. __decorate([
  48355. BABYLON.serialize()
  48356. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48357. __decorate([
  48358. BABYLON.serialize()
  48359. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48360. __decorate([
  48361. BABYLON.serialize()
  48362. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48363. return ArcRotateCamera;
  48364. }(BABYLON.TargetCamera));
  48365. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48366. })(BABYLON || (BABYLON = {}));
  48367. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48368. var BABYLON;
  48369. (function (BABYLON) {
  48370. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48371. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48372. });
  48373. /**
  48374. * The HemisphericLight simulates the ambient environment light,
  48375. * so the passed direction is the light reflection direction, not the incoming direction.
  48376. */
  48377. var HemisphericLight = /** @class */ (function (_super) {
  48378. __extends(HemisphericLight, _super);
  48379. /**
  48380. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48381. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48382. * The HemisphericLight can't cast shadows.
  48383. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48384. * @param name The friendly name of the light
  48385. * @param direction The direction of the light reflection
  48386. * @param scene The scene the light belongs to
  48387. */
  48388. function HemisphericLight(name, direction, scene) {
  48389. var _this = _super.call(this, name, scene) || this;
  48390. /**
  48391. * The groundColor is the light in the opposite direction to the one specified during creation.
  48392. * 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.
  48393. */
  48394. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48395. _this.direction = direction || BABYLON.Vector3.Up();
  48396. return _this;
  48397. }
  48398. HemisphericLight.prototype._buildUniformLayout = function () {
  48399. this._uniformBuffer.addUniform("vLightData", 4);
  48400. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48401. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48402. this._uniformBuffer.addUniform("vLightGround", 3);
  48403. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48404. this._uniformBuffer.addUniform("depthValues", 2);
  48405. this._uniformBuffer.create();
  48406. };
  48407. /**
  48408. * Returns the string "HemisphericLight".
  48409. * @return The class name
  48410. */
  48411. HemisphericLight.prototype.getClassName = function () {
  48412. return "HemisphericLight";
  48413. };
  48414. /**
  48415. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48416. * Returns the updated direction.
  48417. * @param target The target the direction should point to
  48418. * @return The computed direction
  48419. */
  48420. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48421. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48422. return this.direction;
  48423. };
  48424. /**
  48425. * Returns the shadow generator associated to the light.
  48426. * @returns Always null for hemispheric lights because it does not support shadows.
  48427. */
  48428. HemisphericLight.prototype.getShadowGenerator = function () {
  48429. return null;
  48430. };
  48431. /**
  48432. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48433. * @param effect The effect to update
  48434. * @param lightIndex The index of the light in the effect to update
  48435. * @returns The hemispheric light
  48436. */
  48437. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48438. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48439. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48440. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48441. return this;
  48442. };
  48443. /**
  48444. * Computes the world matrix of the node
  48445. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  48446. * @param useWasUpdatedFlag defines a reserved property
  48447. * @returns the world matrix
  48448. */
  48449. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  48450. if (!this._worldMatrix) {
  48451. this._worldMatrix = BABYLON.Matrix.Identity();
  48452. }
  48453. return this._worldMatrix;
  48454. };
  48455. /**
  48456. * Returns the integer 3.
  48457. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48458. */
  48459. HemisphericLight.prototype.getTypeID = function () {
  48460. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48461. };
  48462. /**
  48463. * Prepares the list of defines specific to the light type.
  48464. * @param defines the list of defines
  48465. * @param lightIndex defines the index of the light for the effect
  48466. */
  48467. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48468. defines["HEMILIGHT" + lightIndex] = true;
  48469. };
  48470. __decorate([
  48471. BABYLON.serializeAsColor3()
  48472. ], HemisphericLight.prototype, "groundColor", void 0);
  48473. __decorate([
  48474. BABYLON.serializeAsVector3()
  48475. ], HemisphericLight.prototype, "direction", void 0);
  48476. return HemisphericLight;
  48477. }(BABYLON.Light));
  48478. BABYLON.HemisphericLight = HemisphericLight;
  48479. })(BABYLON || (BABYLON = {}));
  48480. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48481. var BABYLON;
  48482. (function (BABYLON) {
  48483. /**
  48484. * Base implementation IShadowLight
  48485. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48486. */
  48487. var ShadowLight = /** @class */ (function (_super) {
  48488. __extends(ShadowLight, _super);
  48489. function ShadowLight() {
  48490. var _this = _super !== null && _super.apply(this, arguments) || this;
  48491. _this._needProjectionMatrixCompute = true;
  48492. return _this;
  48493. }
  48494. ShadowLight.prototype._setPosition = function (value) {
  48495. this._position = value;
  48496. };
  48497. Object.defineProperty(ShadowLight.prototype, "position", {
  48498. /**
  48499. * Sets the position the shadow will be casted from. Also use as the light position for both
  48500. * point and spot lights.
  48501. */
  48502. get: function () {
  48503. return this._position;
  48504. },
  48505. /**
  48506. * Sets the position the shadow will be casted from. Also use as the light position for both
  48507. * point and spot lights.
  48508. */
  48509. set: function (value) {
  48510. this._setPosition(value);
  48511. },
  48512. enumerable: true,
  48513. configurable: true
  48514. });
  48515. ShadowLight.prototype._setDirection = function (value) {
  48516. this._direction = value;
  48517. };
  48518. Object.defineProperty(ShadowLight.prototype, "direction", {
  48519. /**
  48520. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48521. * Also use as the light direction on spot and directional lights.
  48522. */
  48523. get: function () {
  48524. return this._direction;
  48525. },
  48526. /**
  48527. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48528. * Also use as the light direction on spot and directional lights.
  48529. */
  48530. set: function (value) {
  48531. this._setDirection(value);
  48532. },
  48533. enumerable: true,
  48534. configurable: true
  48535. });
  48536. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48537. /**
  48538. * Gets the shadow projection clipping minimum z value.
  48539. */
  48540. get: function () {
  48541. return this._shadowMinZ;
  48542. },
  48543. /**
  48544. * Sets the shadow projection clipping minimum z value.
  48545. */
  48546. set: function (value) {
  48547. this._shadowMinZ = value;
  48548. this.forceProjectionMatrixCompute();
  48549. },
  48550. enumerable: true,
  48551. configurable: true
  48552. });
  48553. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48554. /**
  48555. * Sets the shadow projection clipping maximum z value.
  48556. */
  48557. get: function () {
  48558. return this._shadowMaxZ;
  48559. },
  48560. /**
  48561. * Gets the shadow projection clipping maximum z value.
  48562. */
  48563. set: function (value) {
  48564. this._shadowMaxZ = value;
  48565. this.forceProjectionMatrixCompute();
  48566. },
  48567. enumerable: true,
  48568. configurable: true
  48569. });
  48570. /**
  48571. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48572. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48573. */
  48574. ShadowLight.prototype.computeTransformedInformation = function () {
  48575. if (this.parent && this.parent.getWorldMatrix) {
  48576. if (!this.transformedPosition) {
  48577. this.transformedPosition = BABYLON.Vector3.Zero();
  48578. }
  48579. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48580. // In case the direction is present.
  48581. if (this.direction) {
  48582. if (!this.transformedDirection) {
  48583. this.transformedDirection = BABYLON.Vector3.Zero();
  48584. }
  48585. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48586. }
  48587. return true;
  48588. }
  48589. return false;
  48590. };
  48591. /**
  48592. * Return the depth scale used for the shadow map.
  48593. * @returns the depth scale.
  48594. */
  48595. ShadowLight.prototype.getDepthScale = function () {
  48596. return 50.0;
  48597. };
  48598. /**
  48599. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48600. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48601. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48602. */
  48603. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48604. return this.transformedDirection ? this.transformedDirection : this.direction;
  48605. };
  48606. /**
  48607. * Returns the ShadowLight absolute position in the World.
  48608. * @returns the position vector in world space
  48609. */
  48610. ShadowLight.prototype.getAbsolutePosition = function () {
  48611. return this.transformedPosition ? this.transformedPosition : this.position;
  48612. };
  48613. /**
  48614. * Sets the ShadowLight direction toward the passed target.
  48615. * @param target The point tot target in local space
  48616. * @returns the updated ShadowLight direction
  48617. */
  48618. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48619. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48620. return this.direction;
  48621. };
  48622. /**
  48623. * Returns the light rotation in euler definition.
  48624. * @returns the x y z rotation in local space.
  48625. */
  48626. ShadowLight.prototype.getRotation = function () {
  48627. this.direction.normalize();
  48628. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48629. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48630. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48631. };
  48632. /**
  48633. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48634. * @returns true if a cube texture needs to be use
  48635. */
  48636. ShadowLight.prototype.needCube = function () {
  48637. return false;
  48638. };
  48639. /**
  48640. * Detects if the projection matrix requires to be recomputed this frame.
  48641. * @returns true if it requires to be recomputed otherwise, false.
  48642. */
  48643. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48644. return this._needProjectionMatrixCompute;
  48645. };
  48646. /**
  48647. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48648. */
  48649. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48650. this._needProjectionMatrixCompute = true;
  48651. };
  48652. /** @hidden */
  48653. ShadowLight.prototype._initCache = function () {
  48654. _super.prototype._initCache.call(this);
  48655. this._cache.position = BABYLON.Vector3.Zero();
  48656. };
  48657. /** @hidden */
  48658. ShadowLight.prototype._isSynchronized = function () {
  48659. if (!this._cache.position.equals(this.position))
  48660. return false;
  48661. return true;
  48662. };
  48663. /**
  48664. * Computes the world matrix of the node
  48665. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  48666. * @returns the world matrix
  48667. */
  48668. ShadowLight.prototype.computeWorldMatrix = function (force) {
  48669. if (!force && this.isSynchronized()) {
  48670. this._currentRenderId = this.getScene().getRenderId();
  48671. return this._worldMatrix;
  48672. }
  48673. this._updateCache();
  48674. this._cache.position.copyFrom(this.position);
  48675. if (!this._worldMatrix) {
  48676. this._worldMatrix = BABYLON.Matrix.Identity();
  48677. }
  48678. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48679. if (this.parent && this.parent.getWorldMatrix) {
  48680. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  48681. this._markSyncedWithParent();
  48682. }
  48683. // Cache the determinant
  48684. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  48685. return this._worldMatrix;
  48686. };
  48687. /**
  48688. * Gets the minZ used for shadow according to both the scene and the light.
  48689. * @param activeCamera The camera we are returning the min for
  48690. * @returns the depth min z
  48691. */
  48692. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48693. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48694. };
  48695. /**
  48696. * Gets the maxZ used for shadow according to both the scene and the light.
  48697. * @param activeCamera The camera we are returning the max for
  48698. * @returns the depth max z
  48699. */
  48700. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48701. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48702. };
  48703. /**
  48704. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48705. * @param matrix The materix to updated with the projection information
  48706. * @param viewMatrix The transform matrix of the light
  48707. * @param renderList The list of mesh to render in the map
  48708. * @returns The current light
  48709. */
  48710. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48711. if (this.customProjectionMatrixBuilder) {
  48712. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48713. }
  48714. else {
  48715. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48716. }
  48717. return this;
  48718. };
  48719. __decorate([
  48720. BABYLON.serializeAsVector3()
  48721. ], ShadowLight.prototype, "position", null);
  48722. __decorate([
  48723. BABYLON.serializeAsVector3()
  48724. ], ShadowLight.prototype, "direction", null);
  48725. __decorate([
  48726. BABYLON.serialize()
  48727. ], ShadowLight.prototype, "shadowMinZ", null);
  48728. __decorate([
  48729. BABYLON.serialize()
  48730. ], ShadowLight.prototype, "shadowMaxZ", null);
  48731. return ShadowLight;
  48732. }(BABYLON.Light));
  48733. BABYLON.ShadowLight = ShadowLight;
  48734. })(BABYLON || (BABYLON = {}));
  48735. //# sourceMappingURL=babylon.shadowLight.js.map
  48736. var BABYLON;
  48737. (function (BABYLON) {
  48738. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48739. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48740. });
  48741. /**
  48742. * A point light is a light defined by an unique point in world space.
  48743. * The light is emitted in every direction from this point.
  48744. * A good example of a point light is a standard light bulb.
  48745. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48746. */
  48747. var PointLight = /** @class */ (function (_super) {
  48748. __extends(PointLight, _super);
  48749. /**
  48750. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48751. * A PointLight emits the light in every direction.
  48752. * It can cast shadows.
  48753. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48754. * ```javascript
  48755. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48756. * ```
  48757. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48758. * @param name The light friendly name
  48759. * @param position The position of the point light in the scene
  48760. * @param scene The scene the lights belongs to
  48761. */
  48762. function PointLight(name, position, scene) {
  48763. var _this = _super.call(this, name, scene) || this;
  48764. _this._shadowAngle = Math.PI / 2;
  48765. _this.position = position;
  48766. return _this;
  48767. }
  48768. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48769. /**
  48770. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48771. * This specifies what angle the shadow will use to be created.
  48772. *
  48773. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48774. */
  48775. get: function () {
  48776. return this._shadowAngle;
  48777. },
  48778. /**
  48779. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48780. * This specifies what angle the shadow will use to be created.
  48781. *
  48782. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48783. */
  48784. set: function (value) {
  48785. this._shadowAngle = value;
  48786. this.forceProjectionMatrixCompute();
  48787. },
  48788. enumerable: true,
  48789. configurable: true
  48790. });
  48791. Object.defineProperty(PointLight.prototype, "direction", {
  48792. /**
  48793. * Gets the direction if it has been set.
  48794. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48795. */
  48796. get: function () {
  48797. return this._direction;
  48798. },
  48799. /**
  48800. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48801. */
  48802. set: function (value) {
  48803. var previousNeedCube = this.needCube();
  48804. this._direction = value;
  48805. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48806. this._shadowGenerator.recreateShadowMap();
  48807. }
  48808. },
  48809. enumerable: true,
  48810. configurable: true
  48811. });
  48812. /**
  48813. * Returns the string "PointLight"
  48814. * @returns the class name
  48815. */
  48816. PointLight.prototype.getClassName = function () {
  48817. return "PointLight";
  48818. };
  48819. /**
  48820. * Returns the integer 0.
  48821. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48822. */
  48823. PointLight.prototype.getTypeID = function () {
  48824. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48825. };
  48826. /**
  48827. * Specifies wether or not the shadowmap should be a cube texture.
  48828. * @returns true if the shadowmap needs to be a cube texture.
  48829. */
  48830. PointLight.prototype.needCube = function () {
  48831. return !this.direction;
  48832. };
  48833. /**
  48834. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48835. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48836. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48837. */
  48838. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48839. if (this.direction) {
  48840. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48841. }
  48842. else {
  48843. switch (faceIndex) {
  48844. case 0:
  48845. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48846. case 1:
  48847. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48848. case 2:
  48849. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48850. case 3:
  48851. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48852. case 4:
  48853. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48854. case 5:
  48855. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48856. }
  48857. }
  48858. return BABYLON.Vector3.Zero();
  48859. };
  48860. /**
  48861. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48862. * - fov = PI / 2
  48863. * - aspect ratio : 1.0
  48864. * - z-near and far equal to the active camera minZ and maxZ.
  48865. * Returns the PointLight.
  48866. */
  48867. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48868. var activeCamera = this.getScene().activeCamera;
  48869. if (!activeCamera) {
  48870. return;
  48871. }
  48872. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48873. };
  48874. PointLight.prototype._buildUniformLayout = function () {
  48875. this._uniformBuffer.addUniform("vLightData", 4);
  48876. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48877. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48878. this._uniformBuffer.addUniform("vLightFalloff", 4);
  48879. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48880. this._uniformBuffer.addUniform("depthValues", 2);
  48881. this._uniformBuffer.create();
  48882. };
  48883. /**
  48884. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48885. * @param effect The effect to update
  48886. * @param lightIndex The index of the light in the effect to update
  48887. * @returns The point light
  48888. */
  48889. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48890. if (this.computeTransformedInformation()) {
  48891. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48892. }
  48893. else {
  48894. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48895. }
  48896. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  48897. return this;
  48898. };
  48899. /**
  48900. * Prepares the list of defines specific to the light type.
  48901. * @param defines the list of defines
  48902. * @param lightIndex defines the index of the light for the effect
  48903. */
  48904. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48905. defines["POINTLIGHT" + lightIndex] = true;
  48906. };
  48907. __decorate([
  48908. BABYLON.serialize()
  48909. ], PointLight.prototype, "shadowAngle", null);
  48910. return PointLight;
  48911. }(BABYLON.ShadowLight));
  48912. BABYLON.PointLight = PointLight;
  48913. })(BABYLON || (BABYLON = {}));
  48914. //# sourceMappingURL=babylon.pointLight.js.map
  48915. var BABYLON;
  48916. (function (BABYLON) {
  48917. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48918. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48919. });
  48920. /**
  48921. * A directional light is defined by a direction (what a surprise!).
  48922. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48923. * 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.
  48924. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48925. */
  48926. var DirectionalLight = /** @class */ (function (_super) {
  48927. __extends(DirectionalLight, _super);
  48928. /**
  48929. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48930. * The directional light is emitted from everywhere in the given direction.
  48931. * It can cast shawdows.
  48932. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48933. * @param name The friendly name of the light
  48934. * @param direction The direction of the light
  48935. * @param scene The scene the light belongs to
  48936. */
  48937. function DirectionalLight(name, direction, scene) {
  48938. var _this = _super.call(this, name, scene) || this;
  48939. _this._shadowFrustumSize = 0;
  48940. _this._shadowOrthoScale = 0.1;
  48941. /**
  48942. * Automatically compute the projection matrix to best fit (including all the casters)
  48943. * on each frame.
  48944. */
  48945. _this.autoUpdateExtends = true;
  48946. // Cache
  48947. _this._orthoLeft = Number.MAX_VALUE;
  48948. _this._orthoRight = Number.MIN_VALUE;
  48949. _this._orthoTop = Number.MIN_VALUE;
  48950. _this._orthoBottom = Number.MAX_VALUE;
  48951. _this.position = direction.scale(-1.0);
  48952. _this.direction = direction;
  48953. return _this;
  48954. }
  48955. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48956. /**
  48957. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48958. */
  48959. get: function () {
  48960. return this._shadowFrustumSize;
  48961. },
  48962. /**
  48963. * Specifies a fix frustum size for the shadow generation.
  48964. */
  48965. set: function (value) {
  48966. this._shadowFrustumSize = value;
  48967. this.forceProjectionMatrixCompute();
  48968. },
  48969. enumerable: true,
  48970. configurable: true
  48971. });
  48972. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48973. /**
  48974. * Gets the shadow projection scale against the optimal computed one.
  48975. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48976. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48977. */
  48978. get: function () {
  48979. return this._shadowOrthoScale;
  48980. },
  48981. /**
  48982. * Sets the shadow projection scale against the optimal computed one.
  48983. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48984. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48985. */
  48986. set: function (value) {
  48987. this._shadowOrthoScale = value;
  48988. this.forceProjectionMatrixCompute();
  48989. },
  48990. enumerable: true,
  48991. configurable: true
  48992. });
  48993. /**
  48994. * Returns the string "DirectionalLight".
  48995. * @return The class name
  48996. */
  48997. DirectionalLight.prototype.getClassName = function () {
  48998. return "DirectionalLight";
  48999. };
  49000. /**
  49001. * Returns the integer 1.
  49002. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49003. */
  49004. DirectionalLight.prototype.getTypeID = function () {
  49005. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49006. };
  49007. /**
  49008. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49009. * Returns the DirectionalLight Shadow projection matrix.
  49010. */
  49011. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49012. if (this.shadowFrustumSize > 0) {
  49013. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49014. }
  49015. else {
  49016. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49017. }
  49018. };
  49019. /**
  49020. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49021. * Returns the DirectionalLight Shadow projection matrix.
  49022. */
  49023. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49024. var activeCamera = this.getScene().activeCamera;
  49025. if (!activeCamera) {
  49026. return;
  49027. }
  49028. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49029. };
  49030. /**
  49031. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49032. * Returns the DirectionalLight Shadow projection matrix.
  49033. */
  49034. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49035. var activeCamera = this.getScene().activeCamera;
  49036. if (!activeCamera) {
  49037. return;
  49038. }
  49039. // Check extends
  49040. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49041. var tempVector3 = BABYLON.Vector3.Zero();
  49042. this._orthoLeft = Number.MAX_VALUE;
  49043. this._orthoRight = Number.MIN_VALUE;
  49044. this._orthoTop = Number.MIN_VALUE;
  49045. this._orthoBottom = Number.MAX_VALUE;
  49046. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49047. var mesh = renderList[meshIndex];
  49048. if (!mesh) {
  49049. continue;
  49050. }
  49051. var boundingInfo = mesh.getBoundingInfo();
  49052. var boundingBox = boundingInfo.boundingBox;
  49053. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49054. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49055. if (tempVector3.x < this._orthoLeft)
  49056. this._orthoLeft = tempVector3.x;
  49057. if (tempVector3.y < this._orthoBottom)
  49058. this._orthoBottom = tempVector3.y;
  49059. if (tempVector3.x > this._orthoRight)
  49060. this._orthoRight = tempVector3.x;
  49061. if (tempVector3.y > this._orthoTop)
  49062. this._orthoTop = tempVector3.y;
  49063. }
  49064. }
  49065. }
  49066. var xOffset = this._orthoRight - this._orthoLeft;
  49067. var yOffset = this._orthoTop - this._orthoBottom;
  49068. 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);
  49069. };
  49070. DirectionalLight.prototype._buildUniformLayout = function () {
  49071. this._uniformBuffer.addUniform("vLightData", 4);
  49072. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49073. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49074. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49075. this._uniformBuffer.addUniform("depthValues", 2);
  49076. this._uniformBuffer.create();
  49077. };
  49078. /**
  49079. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49080. * @param effect The effect to update
  49081. * @param lightIndex The index of the light in the effect to update
  49082. * @returns The directional light
  49083. */
  49084. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49085. if (this.computeTransformedInformation()) {
  49086. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49087. return this;
  49088. }
  49089. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49090. return this;
  49091. };
  49092. /**
  49093. * Gets the minZ used for shadow according to both the scene and the light.
  49094. *
  49095. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49096. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49097. * @param activeCamera The camera we are returning the min for
  49098. * @returns the depth min z
  49099. */
  49100. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49101. return 1;
  49102. };
  49103. /**
  49104. * Gets the maxZ used for shadow according to both the scene and the light.
  49105. *
  49106. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49107. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49108. * @param activeCamera The camera we are returning the max for
  49109. * @returns the depth max z
  49110. */
  49111. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49112. return 1;
  49113. };
  49114. /**
  49115. * Prepares the list of defines specific to the light type.
  49116. * @param defines the list of defines
  49117. * @param lightIndex defines the index of the light for the effect
  49118. */
  49119. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49120. defines["DIRLIGHT" + lightIndex] = true;
  49121. };
  49122. __decorate([
  49123. BABYLON.serialize()
  49124. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49125. __decorate([
  49126. BABYLON.serialize()
  49127. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49128. __decorate([
  49129. BABYLON.serialize()
  49130. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49131. return DirectionalLight;
  49132. }(BABYLON.ShadowLight));
  49133. BABYLON.DirectionalLight = DirectionalLight;
  49134. })(BABYLON || (BABYLON = {}));
  49135. //# sourceMappingURL=babylon.directionalLight.js.map
  49136. var BABYLON;
  49137. (function (BABYLON) {
  49138. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49139. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49140. });
  49141. /**
  49142. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49143. * These values define a cone of light starting from the position, emitting toward the direction.
  49144. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49145. * and the exponent defines the speed of the decay of the light with distance (reach).
  49146. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49147. */
  49148. var SpotLight = /** @class */ (function (_super) {
  49149. __extends(SpotLight, _super);
  49150. /**
  49151. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49152. * It can cast shadows.
  49153. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49154. * @param name The light friendly name
  49155. * @param position The position of the spot light in the scene
  49156. * @param direction The direction of the light in the scene
  49157. * @param angle The cone angle of the light in Radians
  49158. * @param exponent The light decay speed with the distance from the emission spot
  49159. * @param scene The scene the lights belongs to
  49160. */
  49161. function SpotLight(name, position, direction, angle, exponent, scene) {
  49162. var _this = _super.call(this, name, scene) || this;
  49163. _this._innerAngle = 0;
  49164. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49165. _this._projectionTextureLightNear = 1e-6;
  49166. _this._projectionTextureLightFar = 1000.0;
  49167. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49168. _this._projectionTextureViewLightDirty = true;
  49169. _this._projectionTextureProjectionLightDirty = true;
  49170. _this._projectionTextureDirty = true;
  49171. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49172. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49173. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49174. _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);
  49175. _this.position = position;
  49176. _this.direction = direction;
  49177. _this.angle = angle;
  49178. _this.exponent = exponent;
  49179. return _this;
  49180. }
  49181. Object.defineProperty(SpotLight.prototype, "angle", {
  49182. /**
  49183. * Gets the cone angle of the spot light in Radians.
  49184. */
  49185. get: function () {
  49186. return this._angle;
  49187. },
  49188. /**
  49189. * Sets the cone angle of the spot light in Radians.
  49190. */
  49191. set: function (value) {
  49192. this._angle = value;
  49193. this._cosHalfAngle = Math.cos(value * 0.5);
  49194. this._projectionTextureProjectionLightDirty = true;
  49195. this.forceProjectionMatrixCompute();
  49196. this._computeAngleValues();
  49197. },
  49198. enumerable: true,
  49199. configurable: true
  49200. });
  49201. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49202. /**
  49203. * Only used in gltf falloff mode, this defines the angle where
  49204. * the directional falloff will start before cutting at angle which could be seen
  49205. * as outer angle.
  49206. */
  49207. get: function () {
  49208. return this._angle;
  49209. },
  49210. /**
  49211. * Only used in gltf falloff mode, this defines the angle where
  49212. * the directional falloff will start before cutting at angle which could be seen
  49213. * as outer angle.
  49214. */
  49215. set: function (value) {
  49216. this._innerAngle = value;
  49217. this._computeAngleValues();
  49218. },
  49219. enumerable: true,
  49220. configurable: true
  49221. });
  49222. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49223. /**
  49224. * Allows scaling the angle of the light for shadow generation only.
  49225. */
  49226. get: function () {
  49227. return this._shadowAngleScale;
  49228. },
  49229. /**
  49230. * Allows scaling the angle of the light for shadow generation only.
  49231. */
  49232. set: function (value) {
  49233. this._shadowAngleScale = value;
  49234. this.forceProjectionMatrixCompute();
  49235. },
  49236. enumerable: true,
  49237. configurable: true
  49238. });
  49239. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49240. /**
  49241. * Allows reading the projecton texture
  49242. */
  49243. get: function () {
  49244. return this._projectionTextureMatrix;
  49245. },
  49246. enumerable: true,
  49247. configurable: true
  49248. });
  49249. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49250. /**
  49251. * Gets the near clip of the Spotlight for texture projection.
  49252. */
  49253. get: function () {
  49254. return this._projectionTextureLightNear;
  49255. },
  49256. /**
  49257. * Sets the near clip of the Spotlight for texture projection.
  49258. */
  49259. set: function (value) {
  49260. this._projectionTextureLightNear = value;
  49261. this._projectionTextureProjectionLightDirty = true;
  49262. },
  49263. enumerable: true,
  49264. configurable: true
  49265. });
  49266. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49267. /**
  49268. * Gets the far clip of the Spotlight for texture projection.
  49269. */
  49270. get: function () {
  49271. return this._projectionTextureLightFar;
  49272. },
  49273. /**
  49274. * Sets the far clip of the Spotlight for texture projection.
  49275. */
  49276. set: function (value) {
  49277. this._projectionTextureLightFar = value;
  49278. this._projectionTextureProjectionLightDirty = true;
  49279. },
  49280. enumerable: true,
  49281. configurable: true
  49282. });
  49283. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49284. /**
  49285. * Gets the Up vector of the Spotlight for texture projection.
  49286. */
  49287. get: function () {
  49288. return this._projectionTextureUpDirection;
  49289. },
  49290. /**
  49291. * Sets the Up vector of the Spotlight for texture projection.
  49292. */
  49293. set: function (value) {
  49294. this._projectionTextureUpDirection = value;
  49295. this._projectionTextureProjectionLightDirty = true;
  49296. },
  49297. enumerable: true,
  49298. configurable: true
  49299. });
  49300. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49301. /**
  49302. * Gets the projection texture of the light.
  49303. */
  49304. get: function () {
  49305. return this._projectionTexture;
  49306. },
  49307. /**
  49308. * Sets the projection texture of the light.
  49309. */
  49310. set: function (value) {
  49311. this._projectionTexture = value;
  49312. this._projectionTextureDirty = true;
  49313. },
  49314. enumerable: true,
  49315. configurable: true
  49316. });
  49317. /**
  49318. * Returns the string "SpotLight".
  49319. * @returns the class name
  49320. */
  49321. SpotLight.prototype.getClassName = function () {
  49322. return "SpotLight";
  49323. };
  49324. /**
  49325. * Returns the integer 2.
  49326. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49327. */
  49328. SpotLight.prototype.getTypeID = function () {
  49329. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49330. };
  49331. /**
  49332. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49333. */
  49334. SpotLight.prototype._setDirection = function (value) {
  49335. _super.prototype._setDirection.call(this, value);
  49336. this._projectionTextureViewLightDirty = true;
  49337. };
  49338. /**
  49339. * Overrides the position setter to recompute the projection texture view light Matrix.
  49340. */
  49341. SpotLight.prototype._setPosition = function (value) {
  49342. _super.prototype._setPosition.call(this, value);
  49343. this._projectionTextureViewLightDirty = true;
  49344. };
  49345. /**
  49346. * 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.
  49347. * Returns the SpotLight.
  49348. */
  49349. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49350. var activeCamera = this.getScene().activeCamera;
  49351. if (!activeCamera) {
  49352. return;
  49353. }
  49354. this._shadowAngleScale = this._shadowAngleScale || 1;
  49355. var angle = this._shadowAngleScale * this._angle;
  49356. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49357. };
  49358. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49359. this._projectionTextureViewLightDirty = false;
  49360. this._projectionTextureDirty = true;
  49361. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49362. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49363. };
  49364. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49365. this._projectionTextureProjectionLightDirty = false;
  49366. this._projectionTextureDirty = true;
  49367. var light_far = this.projectionTextureLightFar;
  49368. var light_near = this.projectionTextureLightNear;
  49369. var P = light_far / (light_far - light_near);
  49370. var Q = -P * light_near;
  49371. var S = 1.0 / Math.tan(this._angle / 2.0);
  49372. var A = 1.0;
  49373. 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);
  49374. };
  49375. /**
  49376. * Main function for light texture projection matrix computing.
  49377. */
  49378. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49379. this._projectionTextureDirty = false;
  49380. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49381. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49382. };
  49383. SpotLight.prototype._buildUniformLayout = function () {
  49384. this._uniformBuffer.addUniform("vLightData", 4);
  49385. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49386. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49387. this._uniformBuffer.addUniform("vLightDirection", 3);
  49388. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49389. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49390. this._uniformBuffer.addUniform("depthValues", 2);
  49391. this._uniformBuffer.create();
  49392. };
  49393. SpotLight.prototype._computeAngleValues = function () {
  49394. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49395. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49396. };
  49397. /**
  49398. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49399. * @param effect The effect to update
  49400. * @param lightIndex The index of the light in the effect to update
  49401. * @returns The spot light
  49402. */
  49403. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49404. var normalizeDirection;
  49405. if (this.computeTransformedInformation()) {
  49406. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49407. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49408. }
  49409. else {
  49410. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49411. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49412. }
  49413. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49414. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49415. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49416. if (this._projectionTextureViewLightDirty) {
  49417. this._computeProjectionTextureViewLightMatrix();
  49418. }
  49419. if (this._projectionTextureProjectionLightDirty) {
  49420. this._computeProjectionTextureProjectionLightMatrix();
  49421. }
  49422. if (this._projectionTextureDirty) {
  49423. this._computeProjectionTextureMatrix();
  49424. }
  49425. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49426. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49427. }
  49428. return this;
  49429. };
  49430. /**
  49431. * Disposes the light and the associated resources.
  49432. */
  49433. SpotLight.prototype.dispose = function () {
  49434. _super.prototype.dispose.call(this);
  49435. if (this._projectionTexture) {
  49436. this._projectionTexture.dispose();
  49437. }
  49438. };
  49439. /**
  49440. * Prepares the list of defines specific to the light type.
  49441. * @param defines the list of defines
  49442. * @param lightIndex defines the index of the light for the effect
  49443. */
  49444. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49445. defines["SPOTLIGHT" + lightIndex] = true;
  49446. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49447. };
  49448. __decorate([
  49449. BABYLON.serialize()
  49450. ], SpotLight.prototype, "angle", null);
  49451. __decorate([
  49452. BABYLON.serialize()
  49453. ], SpotLight.prototype, "innerAngle", null);
  49454. __decorate([
  49455. BABYLON.serialize()
  49456. ], SpotLight.prototype, "shadowAngleScale", null);
  49457. __decorate([
  49458. BABYLON.serialize()
  49459. ], SpotLight.prototype, "exponent", void 0);
  49460. __decorate([
  49461. BABYLON.serialize()
  49462. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49463. __decorate([
  49464. BABYLON.serialize()
  49465. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49466. __decorate([
  49467. BABYLON.serialize()
  49468. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49469. __decorate([
  49470. BABYLON.serializeAsTexture("projectedLightTexture")
  49471. ], SpotLight.prototype, "_projectionTexture", void 0);
  49472. return SpotLight;
  49473. }(BABYLON.ShadowLight));
  49474. BABYLON.SpotLight = SpotLight;
  49475. })(BABYLON || (BABYLON = {}));
  49476. //# sourceMappingURL=babylon.spotLight.js.map
  49477. var BABYLON;
  49478. (function (BABYLON) {
  49479. /**
  49480. * Class used to override all child animations of a given target
  49481. */
  49482. var AnimationPropertiesOverride = /** @class */ (function () {
  49483. function AnimationPropertiesOverride() {
  49484. /**
  49485. * Gets or sets a value indicating if animation blending must be used
  49486. */
  49487. this.enableBlending = false;
  49488. /**
  49489. * Gets or sets the blending speed to use when enableBlending is true
  49490. */
  49491. this.blendingSpeed = 0.01;
  49492. /**
  49493. * Gets or sets the default loop mode to use
  49494. */
  49495. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49496. }
  49497. return AnimationPropertiesOverride;
  49498. }());
  49499. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49500. })(BABYLON || (BABYLON = {}));
  49501. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49502. var BABYLON;
  49503. (function (BABYLON) {
  49504. /**
  49505. * Represents the range of an animation
  49506. */
  49507. var AnimationRange = /** @class */ (function () {
  49508. /**
  49509. * Initializes the range of an animation
  49510. * @param name The name of the animation range
  49511. * @param from The starting frame of the animation
  49512. * @param to The ending frame of the animation
  49513. */
  49514. function AnimationRange(
  49515. /**The name of the animation range**/
  49516. name,
  49517. /**The starting frame of the animation */
  49518. from,
  49519. /**The ending frame of the animation*/
  49520. to) {
  49521. this.name = name;
  49522. this.from = from;
  49523. this.to = to;
  49524. }
  49525. /**
  49526. * Makes a copy of the animation range
  49527. * @returns A copy of the animation range
  49528. */
  49529. AnimationRange.prototype.clone = function () {
  49530. return new AnimationRange(this.name, this.from, this.to);
  49531. };
  49532. return AnimationRange;
  49533. }());
  49534. BABYLON.AnimationRange = AnimationRange;
  49535. /**
  49536. * Composed of a frame, and an action function
  49537. */
  49538. var AnimationEvent = /** @class */ (function () {
  49539. /**
  49540. * Initializes the animation event
  49541. * @param frame The frame for which the event is triggered
  49542. * @param action The event to perform when triggered
  49543. * @param onlyOnce Specifies if the event should be triggered only once
  49544. */
  49545. function AnimationEvent(
  49546. /** The frame for which the event is triggered **/
  49547. frame,
  49548. /** The event to perform when triggered **/
  49549. action,
  49550. /** Specifies if the event should be triggered only once**/
  49551. onlyOnce) {
  49552. this.frame = frame;
  49553. this.action = action;
  49554. this.onlyOnce = onlyOnce;
  49555. /**
  49556. * Specifies if the animation event is done
  49557. */
  49558. this.isDone = false;
  49559. }
  49560. /** @hidden */
  49561. AnimationEvent.prototype._clone = function () {
  49562. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49563. };
  49564. return AnimationEvent;
  49565. }());
  49566. BABYLON.AnimationEvent = AnimationEvent;
  49567. /**
  49568. * A cursor which tracks a point on a path
  49569. */
  49570. var PathCursor = /** @class */ (function () {
  49571. /**
  49572. * Initializes the path cursor
  49573. * @param path The path to track
  49574. */
  49575. function PathCursor(path) {
  49576. this.path = path;
  49577. /**
  49578. * Stores path cursor callbacks for when an onchange event is triggered
  49579. */
  49580. this._onchange = new Array();
  49581. /**
  49582. * The value of the path cursor
  49583. */
  49584. this.value = 0;
  49585. /**
  49586. * The animation array of the path cursor
  49587. */
  49588. this.animations = new Array();
  49589. }
  49590. /**
  49591. * Gets the cursor point on the path
  49592. * @returns A point on the path cursor at the cursor location
  49593. */
  49594. PathCursor.prototype.getPoint = function () {
  49595. var point = this.path.getPointAtLengthPosition(this.value);
  49596. return new BABYLON.Vector3(point.x, 0, point.y);
  49597. };
  49598. /**
  49599. * Moves the cursor ahead by the step amount
  49600. * @param step The amount to move the cursor forward
  49601. * @returns This path cursor
  49602. */
  49603. PathCursor.prototype.moveAhead = function (step) {
  49604. if (step === void 0) { step = 0.002; }
  49605. this.move(step);
  49606. return this;
  49607. };
  49608. /**
  49609. * Moves the cursor behind by the step amount
  49610. * @param step The amount to move the cursor back
  49611. * @returns This path cursor
  49612. */
  49613. PathCursor.prototype.moveBack = function (step) {
  49614. if (step === void 0) { step = 0.002; }
  49615. this.move(-step);
  49616. return this;
  49617. };
  49618. /**
  49619. * Moves the cursor by the step amount
  49620. * If the step amount is greater than one, an exception is thrown
  49621. * @param step The amount to move the cursor
  49622. * @returns This path cursor
  49623. */
  49624. PathCursor.prototype.move = function (step) {
  49625. if (Math.abs(step) > 1) {
  49626. throw "step size should be less than 1.";
  49627. }
  49628. this.value += step;
  49629. this.ensureLimits();
  49630. this.raiseOnChange();
  49631. return this;
  49632. };
  49633. /**
  49634. * Ensures that the value is limited between zero and one
  49635. * @returns This path cursor
  49636. */
  49637. PathCursor.prototype.ensureLimits = function () {
  49638. while (this.value > 1) {
  49639. this.value -= 1;
  49640. }
  49641. while (this.value < 0) {
  49642. this.value += 1;
  49643. }
  49644. return this;
  49645. };
  49646. /**
  49647. * Runs onchange callbacks on change (used by the animation engine)
  49648. * @returns This path cursor
  49649. */
  49650. PathCursor.prototype.raiseOnChange = function () {
  49651. var _this = this;
  49652. this._onchange.forEach(function (f) { return f(_this); });
  49653. return this;
  49654. };
  49655. /**
  49656. * Executes a function on change
  49657. * @param f A path cursor onchange callback
  49658. * @returns This path cursor
  49659. */
  49660. PathCursor.prototype.onchange = function (f) {
  49661. this._onchange.push(f);
  49662. return this;
  49663. };
  49664. return PathCursor;
  49665. }());
  49666. BABYLON.PathCursor = PathCursor;
  49667. /**
  49668. * Enum for the animation key frame interpolation type
  49669. */
  49670. var AnimationKeyInterpolation;
  49671. (function (AnimationKeyInterpolation) {
  49672. /**
  49673. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49674. */
  49675. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49676. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49677. /**
  49678. * Class used to store any kind of animation
  49679. */
  49680. var Animation = /** @class */ (function () {
  49681. /**
  49682. * Initializes the animation
  49683. * @param name Name of the animation
  49684. * @param targetProperty Property to animate
  49685. * @param framePerSecond The frames per second of the animation
  49686. * @param dataType The data type of the animation
  49687. * @param loopMode The loop mode of the animation
  49688. * @param enableBlendings Specifies if blending should be enabled
  49689. */
  49690. function Animation(
  49691. /**Name of the animation */
  49692. name,
  49693. /**Property to animate */
  49694. targetProperty,
  49695. /**The frames per second of the animation */
  49696. framePerSecond,
  49697. /**The data type of the animation */
  49698. dataType,
  49699. /**The loop mode of the animation */
  49700. loopMode,
  49701. /**Specifies if blending should be enabled */
  49702. enableBlending) {
  49703. this.name = name;
  49704. this.targetProperty = targetProperty;
  49705. this.framePerSecond = framePerSecond;
  49706. this.dataType = dataType;
  49707. this.loopMode = loopMode;
  49708. this.enableBlending = enableBlending;
  49709. /**
  49710. * @hidden Internal use only
  49711. */
  49712. this._runtimeAnimations = new Array();
  49713. /**
  49714. * The set of event that will be linked to this animation
  49715. */
  49716. this._events = new Array();
  49717. /**
  49718. * Stores the blending speed of the animation
  49719. */
  49720. this.blendingSpeed = 0.01;
  49721. /**
  49722. * Stores the animation ranges for the animation
  49723. */
  49724. this._ranges = {};
  49725. this.targetPropertyPath = targetProperty.split(".");
  49726. this.dataType = dataType;
  49727. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49728. }
  49729. /**
  49730. * @hidden Internal use
  49731. */
  49732. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49733. var dataType = undefined;
  49734. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49735. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49736. }
  49737. else if (from instanceof BABYLON.Quaternion) {
  49738. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49739. }
  49740. else if (from instanceof BABYLON.Vector3) {
  49741. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49742. }
  49743. else if (from instanceof BABYLON.Vector2) {
  49744. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49745. }
  49746. else if (from instanceof BABYLON.Color3) {
  49747. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49748. }
  49749. else if (from instanceof BABYLON.Size) {
  49750. dataType = Animation.ANIMATIONTYPE_SIZE;
  49751. }
  49752. if (dataType == undefined) {
  49753. return null;
  49754. }
  49755. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49756. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49757. animation.setKeys(keys);
  49758. if (easingFunction !== undefined) {
  49759. animation.setEasingFunction(easingFunction);
  49760. }
  49761. return animation;
  49762. };
  49763. /**
  49764. * Sets up an animation
  49765. * @param property The property to animate
  49766. * @param animationType The animation type to apply
  49767. * @param framePerSecond The frames per second of the animation
  49768. * @param easingFunction The easing function used in the animation
  49769. * @returns The created animation
  49770. */
  49771. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49772. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49773. animation.setEasingFunction(easingFunction);
  49774. return animation;
  49775. };
  49776. /**
  49777. * Create and start an animation on a node
  49778. * @param name defines the name of the global animation that will be run on all nodes
  49779. * @param node defines the root node where the animation will take place
  49780. * @param targetProperty defines property to animate
  49781. * @param framePerSecond defines the number of frame per second yo use
  49782. * @param totalFrame defines the number of frames in total
  49783. * @param from defines the initial value
  49784. * @param to defines the final value
  49785. * @param loopMode defines which loop mode you want to use (off by default)
  49786. * @param easingFunction defines the easing function to use (linear by default)
  49787. * @param onAnimationEnd defines the callback to call when animation end
  49788. * @returns the animatable created for this animation
  49789. */
  49790. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49791. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49792. if (!animation) {
  49793. return null;
  49794. }
  49795. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49796. };
  49797. /**
  49798. * Create and start an animation on a node and its descendants
  49799. * @param name defines the name of the global animation that will be run on all nodes
  49800. * @param node defines the root node where the animation will take place
  49801. * @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
  49802. * @param targetProperty defines property to animate
  49803. * @param framePerSecond defines the number of frame per second to use
  49804. * @param totalFrame defines the number of frames in total
  49805. * @param from defines the initial value
  49806. * @param to defines the final value
  49807. * @param loopMode defines which loop mode you want to use (off by default)
  49808. * @param easingFunction defines the easing function to use (linear by default)
  49809. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49810. * @returns the list of animatables created for all nodes
  49811. * @example https://www.babylonjs-playground.com/#MH0VLI
  49812. */
  49813. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49814. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49815. if (!animation) {
  49816. return null;
  49817. }
  49818. var scene = node.getScene();
  49819. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49820. };
  49821. /**
  49822. * Creates a new animation, merges it with the existing animations and starts it
  49823. * @param name Name of the animation
  49824. * @param node Node which contains the scene that begins the animations
  49825. * @param targetProperty Specifies which property to animate
  49826. * @param framePerSecond The frames per second of the animation
  49827. * @param totalFrame The total number of frames
  49828. * @param from The frame at the beginning of the animation
  49829. * @param to The frame at the end of the animation
  49830. * @param loopMode Specifies the loop mode of the animation
  49831. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49832. * @param onAnimationEnd Callback to run once the animation is complete
  49833. * @returns Nullable animation
  49834. */
  49835. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49836. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49837. if (!animation) {
  49838. return null;
  49839. }
  49840. node.animations.push(animation);
  49841. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49842. };
  49843. /**
  49844. * Transition property of an host to the target Value
  49845. * @param property The property to transition
  49846. * @param targetValue The target Value of the property
  49847. * @param host The object where the property to animate belongs
  49848. * @param scene Scene used to run the animation
  49849. * @param frameRate Framerate (in frame/s) to use
  49850. * @param transition The transition type we want to use
  49851. * @param duration The duration of the animation, in milliseconds
  49852. * @param onAnimationEnd Callback trigger at the end of the animation
  49853. * @returns Nullable animation
  49854. */
  49855. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49856. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49857. if (duration <= 0) {
  49858. host[property] = targetValue;
  49859. if (onAnimationEnd) {
  49860. onAnimationEnd();
  49861. }
  49862. return null;
  49863. }
  49864. var endFrame = frameRate * (duration / 1000);
  49865. transition.setKeys([{
  49866. frame: 0,
  49867. value: host[property].clone ? host[property].clone() : host[property]
  49868. },
  49869. {
  49870. frame: endFrame,
  49871. value: targetValue
  49872. }]);
  49873. if (!host.animations) {
  49874. host.animations = [];
  49875. }
  49876. host.animations.push(transition);
  49877. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49878. animation.onAnimationEnd = onAnimationEnd;
  49879. return animation;
  49880. };
  49881. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49882. /**
  49883. * Return the array of runtime animations currently using this animation
  49884. */
  49885. get: function () {
  49886. return this._runtimeAnimations;
  49887. },
  49888. enumerable: true,
  49889. configurable: true
  49890. });
  49891. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49892. /**
  49893. * Specifies if any of the runtime animations are currently running
  49894. */
  49895. get: function () {
  49896. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49897. var runtimeAnimation = _a[_i];
  49898. if (!runtimeAnimation.isStopped) {
  49899. return true;
  49900. }
  49901. }
  49902. return false;
  49903. },
  49904. enumerable: true,
  49905. configurable: true
  49906. });
  49907. // Methods
  49908. /**
  49909. * Converts the animation to a string
  49910. * @param fullDetails support for multiple levels of logging within scene loading
  49911. * @returns String form of the animation
  49912. */
  49913. Animation.prototype.toString = function (fullDetails) {
  49914. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49915. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49916. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49917. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49918. if (fullDetails) {
  49919. ret += ", Ranges: {";
  49920. var first = true;
  49921. for (var name in this._ranges) {
  49922. if (first) {
  49923. ret += ", ";
  49924. first = false;
  49925. }
  49926. ret += name;
  49927. }
  49928. ret += "}";
  49929. }
  49930. return ret;
  49931. };
  49932. /**
  49933. * Add an event to this animation
  49934. * @param event Event to add
  49935. */
  49936. Animation.prototype.addEvent = function (event) {
  49937. this._events.push(event);
  49938. };
  49939. /**
  49940. * Remove all events found at the given frame
  49941. * @param frame The frame to remove events from
  49942. */
  49943. Animation.prototype.removeEvents = function (frame) {
  49944. for (var index = 0; index < this._events.length; index++) {
  49945. if (this._events[index].frame === frame) {
  49946. this._events.splice(index, 1);
  49947. index--;
  49948. }
  49949. }
  49950. };
  49951. /**
  49952. * Retrieves all the events from the animation
  49953. * @returns Events from the animation
  49954. */
  49955. Animation.prototype.getEvents = function () {
  49956. return this._events;
  49957. };
  49958. /**
  49959. * Creates an animation range
  49960. * @param name Name of the animation range
  49961. * @param from Starting frame of the animation range
  49962. * @param to Ending frame of the animation
  49963. */
  49964. Animation.prototype.createRange = function (name, from, to) {
  49965. // check name not already in use; could happen for bones after serialized
  49966. if (!this._ranges[name]) {
  49967. this._ranges[name] = new AnimationRange(name, from, to);
  49968. }
  49969. };
  49970. /**
  49971. * Deletes an animation range by name
  49972. * @param name Name of the animation range to delete
  49973. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49974. */
  49975. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49976. if (deleteFrames === void 0) { deleteFrames = true; }
  49977. var range = this._ranges[name];
  49978. if (!range) {
  49979. return;
  49980. }
  49981. if (deleteFrames) {
  49982. var from = range.from;
  49983. var to = range.to;
  49984. // this loop MUST go high to low for multiple splices to work
  49985. for (var key = this._keys.length - 1; key >= 0; key--) {
  49986. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49987. this._keys.splice(key, 1);
  49988. }
  49989. }
  49990. }
  49991. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49992. };
  49993. /**
  49994. * Gets the animation range by name, or null if not defined
  49995. * @param name Name of the animation range
  49996. * @returns Nullable animation range
  49997. */
  49998. Animation.prototype.getRange = function (name) {
  49999. return this._ranges[name];
  50000. };
  50001. /**
  50002. * Gets the key frames from the animation
  50003. * @returns The key frames of the animation
  50004. */
  50005. Animation.prototype.getKeys = function () {
  50006. return this._keys;
  50007. };
  50008. /**
  50009. * Gets the highest frame rate of the animation
  50010. * @returns Highest frame rate of the animation
  50011. */
  50012. Animation.prototype.getHighestFrame = function () {
  50013. var ret = 0;
  50014. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50015. if (ret < this._keys[key].frame) {
  50016. ret = this._keys[key].frame;
  50017. }
  50018. }
  50019. return ret;
  50020. };
  50021. /**
  50022. * Gets the easing function of the animation
  50023. * @returns Easing function of the animation
  50024. */
  50025. Animation.prototype.getEasingFunction = function () {
  50026. return this._easingFunction;
  50027. };
  50028. /**
  50029. * Sets the easing function of the animation
  50030. * @param easingFunction A custom mathematical formula for animation
  50031. */
  50032. Animation.prototype.setEasingFunction = function (easingFunction) {
  50033. this._easingFunction = easingFunction;
  50034. };
  50035. /**
  50036. * Interpolates a scalar linearly
  50037. * @param startValue Start value of the animation curve
  50038. * @param endValue End value of the animation curve
  50039. * @param gradient Scalar amount to interpolate
  50040. * @returns Interpolated scalar value
  50041. */
  50042. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50043. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50044. };
  50045. /**
  50046. * Interpolates a scalar cubically
  50047. * @param startValue Start value of the animation curve
  50048. * @param outTangent End tangent of the animation
  50049. * @param endValue End value of the animation curve
  50050. * @param inTangent Start tangent of the animation curve
  50051. * @param gradient Scalar amount to interpolate
  50052. * @returns Interpolated scalar value
  50053. */
  50054. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50055. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50056. };
  50057. /**
  50058. * Interpolates a quaternion using a spherical linear interpolation
  50059. * @param startValue Start value of the animation curve
  50060. * @param endValue End value of the animation curve
  50061. * @param gradient Scalar amount to interpolate
  50062. * @returns Interpolated quaternion value
  50063. */
  50064. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50065. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50066. };
  50067. /**
  50068. * Interpolates a quaternion cubically
  50069. * @param startValue Start value of the animation curve
  50070. * @param outTangent End tangent of the animation curve
  50071. * @param endValue End value of the animation curve
  50072. * @param inTangent Start tangent of the animation curve
  50073. * @param gradient Scalar amount to interpolate
  50074. * @returns Interpolated quaternion value
  50075. */
  50076. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50077. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50078. };
  50079. /**
  50080. * Interpolates a Vector3 linearl
  50081. * @param startValue Start value of the animation curve
  50082. * @param endValue End value of the animation curve
  50083. * @param gradient Scalar amount to interpolate
  50084. * @returns Interpolated scalar value
  50085. */
  50086. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50087. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50088. };
  50089. /**
  50090. * Interpolates a Vector3 cubically
  50091. * @param startValue Start value of the animation curve
  50092. * @param outTangent End tangent of the animation
  50093. * @param endValue End value of the animation curve
  50094. * @param inTangent Start tangent of the animation curve
  50095. * @param gradient Scalar amount to interpolate
  50096. * @returns InterpolatedVector3 value
  50097. */
  50098. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50099. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50100. };
  50101. /**
  50102. * Interpolates a Vector2 linearly
  50103. * @param startValue Start value of the animation curve
  50104. * @param endValue End value of the animation curve
  50105. * @param gradient Scalar amount to interpolate
  50106. * @returns Interpolated Vector2 value
  50107. */
  50108. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50109. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50110. };
  50111. /**
  50112. * Interpolates a Vector2 cubically
  50113. * @param startValue Start value of the animation curve
  50114. * @param outTangent End tangent of the animation
  50115. * @param endValue End value of the animation curve
  50116. * @param inTangent Start tangent of the animation curve
  50117. * @param gradient Scalar amount to interpolate
  50118. * @returns Interpolated Vector2 value
  50119. */
  50120. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50121. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50122. };
  50123. /**
  50124. * Interpolates a size linearly
  50125. * @param startValue Start value of the animation curve
  50126. * @param endValue End value of the animation curve
  50127. * @param gradient Scalar amount to interpolate
  50128. * @returns Interpolated Size value
  50129. */
  50130. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50131. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50132. };
  50133. /**
  50134. * Interpolates a Color3 linearly
  50135. * @param startValue Start value of the animation curve
  50136. * @param endValue End value of the animation curve
  50137. * @param gradient Scalar amount to interpolate
  50138. * @returns Interpolated Color3 value
  50139. */
  50140. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50141. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50142. };
  50143. /**
  50144. * @hidden Internal use only
  50145. */
  50146. Animation.prototype._getKeyValue = function (value) {
  50147. if (typeof value === "function") {
  50148. return value();
  50149. }
  50150. return value;
  50151. };
  50152. /**
  50153. * @hidden Internal use only
  50154. */
  50155. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50156. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50157. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50158. }
  50159. var keys = this.getKeys();
  50160. // Try to get a hash to find the right key
  50161. 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));
  50162. if (keys[startKeyIndex].frame >= currentFrame) {
  50163. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50164. startKeyIndex--;
  50165. }
  50166. }
  50167. for (var key = startKeyIndex; key < keys.length; key++) {
  50168. var endKey = keys[key + 1];
  50169. if (endKey.frame >= currentFrame) {
  50170. var startKey = keys[key];
  50171. var startValue = this._getKeyValue(startKey.value);
  50172. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50173. return startValue;
  50174. }
  50175. var endValue = this._getKeyValue(endKey.value);
  50176. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50177. var frameDelta = endKey.frame - startKey.frame;
  50178. // gradient : percent of currentFrame between the frame inf and the frame sup
  50179. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50180. // check for easingFunction and correction of gradient
  50181. var easingFunction = this.getEasingFunction();
  50182. if (easingFunction != null) {
  50183. gradient = easingFunction.ease(gradient);
  50184. }
  50185. switch (this.dataType) {
  50186. // Float
  50187. case Animation.ANIMATIONTYPE_FLOAT:
  50188. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50189. switch (loopMode) {
  50190. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50191. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50192. return floatValue;
  50193. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50194. return offsetValue * repeatCount + floatValue;
  50195. }
  50196. break;
  50197. // Quaternion
  50198. case Animation.ANIMATIONTYPE_QUATERNION:
  50199. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50200. switch (loopMode) {
  50201. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50202. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50203. return quatValue;
  50204. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50205. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50206. }
  50207. return quatValue;
  50208. // Vector3
  50209. case Animation.ANIMATIONTYPE_VECTOR3:
  50210. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50211. switch (loopMode) {
  50212. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50213. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50214. return vec3Value;
  50215. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50216. return vec3Value.add(offsetValue.scale(repeatCount));
  50217. }
  50218. // Vector2
  50219. case Animation.ANIMATIONTYPE_VECTOR2:
  50220. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50221. switch (loopMode) {
  50222. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50223. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50224. return vec2Value;
  50225. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50226. return vec2Value.add(offsetValue.scale(repeatCount));
  50227. }
  50228. // Size
  50229. case Animation.ANIMATIONTYPE_SIZE:
  50230. switch (loopMode) {
  50231. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50232. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50233. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50234. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50235. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50236. }
  50237. // Color3
  50238. case Animation.ANIMATIONTYPE_COLOR3:
  50239. switch (loopMode) {
  50240. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50241. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50242. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50243. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50244. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50245. }
  50246. // Matrix
  50247. case Animation.ANIMATIONTYPE_MATRIX:
  50248. switch (loopMode) {
  50249. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50250. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50251. if (Animation.AllowMatricesInterpolation) {
  50252. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50253. }
  50254. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50255. return startValue;
  50256. }
  50257. default:
  50258. break;
  50259. }
  50260. break;
  50261. }
  50262. }
  50263. return this._getKeyValue(keys[keys.length - 1].value);
  50264. };
  50265. /**
  50266. * Defines the function to use to interpolate matrices
  50267. * @param startValue defines the start matrix
  50268. * @param endValue defines the end matrix
  50269. * @param gradient defines the gradient between both matrices
  50270. * @param result defines an optional target matrix where to store the interpolation
  50271. * @returns the interpolated matrix
  50272. */
  50273. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50274. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50275. if (result) {
  50276. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50277. return result;
  50278. }
  50279. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50280. }
  50281. if (result) {
  50282. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50283. return result;
  50284. }
  50285. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50286. };
  50287. /**
  50288. * Makes a copy of the animation
  50289. * @returns Cloned animation
  50290. */
  50291. Animation.prototype.clone = function () {
  50292. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50293. clone.enableBlending = this.enableBlending;
  50294. clone.blendingSpeed = this.blendingSpeed;
  50295. if (this._keys) {
  50296. clone.setKeys(this._keys);
  50297. }
  50298. if (this._ranges) {
  50299. clone._ranges = {};
  50300. for (var name in this._ranges) {
  50301. var range = this._ranges[name];
  50302. if (!range) {
  50303. continue;
  50304. }
  50305. clone._ranges[name] = range.clone();
  50306. }
  50307. }
  50308. return clone;
  50309. };
  50310. /**
  50311. * Sets the key frames of the animation
  50312. * @param values The animation key frames to set
  50313. */
  50314. Animation.prototype.setKeys = function (values) {
  50315. this._keys = values.slice(0);
  50316. };
  50317. /**
  50318. * Serializes the animation to an object
  50319. * @returns Serialized object
  50320. */
  50321. Animation.prototype.serialize = function () {
  50322. var serializationObject = {};
  50323. serializationObject.name = this.name;
  50324. serializationObject.property = this.targetProperty;
  50325. serializationObject.framePerSecond = this.framePerSecond;
  50326. serializationObject.dataType = this.dataType;
  50327. serializationObject.loopBehavior = this.loopMode;
  50328. serializationObject.enableBlending = this.enableBlending;
  50329. serializationObject.blendingSpeed = this.blendingSpeed;
  50330. var dataType = this.dataType;
  50331. serializationObject.keys = [];
  50332. var keys = this.getKeys();
  50333. for (var index = 0; index < keys.length; index++) {
  50334. var animationKey = keys[index];
  50335. var key = {};
  50336. key.frame = animationKey.frame;
  50337. switch (dataType) {
  50338. case Animation.ANIMATIONTYPE_FLOAT:
  50339. key.values = [animationKey.value];
  50340. break;
  50341. case Animation.ANIMATIONTYPE_QUATERNION:
  50342. case Animation.ANIMATIONTYPE_MATRIX:
  50343. case Animation.ANIMATIONTYPE_VECTOR3:
  50344. case Animation.ANIMATIONTYPE_COLOR3:
  50345. key.values = animationKey.value.asArray();
  50346. break;
  50347. }
  50348. serializationObject.keys.push(key);
  50349. }
  50350. serializationObject.ranges = [];
  50351. for (var name in this._ranges) {
  50352. var source = this._ranges[name];
  50353. if (!source) {
  50354. continue;
  50355. }
  50356. var range = {};
  50357. range.name = name;
  50358. range.from = source.from;
  50359. range.to = source.to;
  50360. serializationObject.ranges.push(range);
  50361. }
  50362. return serializationObject;
  50363. };
  50364. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50365. /**
  50366. * Get the float animation type
  50367. */
  50368. get: function () {
  50369. return Animation._ANIMATIONTYPE_FLOAT;
  50370. },
  50371. enumerable: true,
  50372. configurable: true
  50373. });
  50374. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50375. /**
  50376. * Get the Vector3 animation type
  50377. */
  50378. get: function () {
  50379. return Animation._ANIMATIONTYPE_VECTOR3;
  50380. },
  50381. enumerable: true,
  50382. configurable: true
  50383. });
  50384. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50385. /**
  50386. * Get the Vector2 animation type
  50387. */
  50388. get: function () {
  50389. return Animation._ANIMATIONTYPE_VECTOR2;
  50390. },
  50391. enumerable: true,
  50392. configurable: true
  50393. });
  50394. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50395. /**
  50396. * Get the Size animation type
  50397. */
  50398. get: function () {
  50399. return Animation._ANIMATIONTYPE_SIZE;
  50400. },
  50401. enumerable: true,
  50402. configurable: true
  50403. });
  50404. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50405. /**
  50406. * Get the Quaternion animation type
  50407. */
  50408. get: function () {
  50409. return Animation._ANIMATIONTYPE_QUATERNION;
  50410. },
  50411. enumerable: true,
  50412. configurable: true
  50413. });
  50414. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50415. /**
  50416. * Get the Matrix animation type
  50417. */
  50418. get: function () {
  50419. return Animation._ANIMATIONTYPE_MATRIX;
  50420. },
  50421. enumerable: true,
  50422. configurable: true
  50423. });
  50424. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50425. /**
  50426. * Get the Color3 animation type
  50427. */
  50428. get: function () {
  50429. return Animation._ANIMATIONTYPE_COLOR3;
  50430. },
  50431. enumerable: true,
  50432. configurable: true
  50433. });
  50434. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50435. /**
  50436. * Get the Relative Loop Mode
  50437. */
  50438. get: function () {
  50439. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50440. },
  50441. enumerable: true,
  50442. configurable: true
  50443. });
  50444. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50445. /**
  50446. * Get the Cycle Loop Mode
  50447. */
  50448. get: function () {
  50449. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50450. },
  50451. enumerable: true,
  50452. configurable: true
  50453. });
  50454. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50455. /**
  50456. * Get the Constant Loop Mode
  50457. */
  50458. get: function () {
  50459. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50460. },
  50461. enumerable: true,
  50462. configurable: true
  50463. });
  50464. /** @hidden */
  50465. Animation._UniversalLerp = function (left, right, amount) {
  50466. var constructor = left.constructor;
  50467. if (constructor.Lerp) { // Lerp supported
  50468. return constructor.Lerp(left, right, amount);
  50469. }
  50470. else if (constructor.Slerp) { // Slerp supported
  50471. return constructor.Slerp(left, right, amount);
  50472. }
  50473. else if (left.toFixed) { // Number
  50474. return left * (1.0 - amount) + amount * right;
  50475. }
  50476. else { // Blending not supported
  50477. return right;
  50478. }
  50479. };
  50480. /**
  50481. * Parses an animation object and creates an animation
  50482. * @param parsedAnimation Parsed animation object
  50483. * @returns Animation object
  50484. */
  50485. Animation.Parse = function (parsedAnimation) {
  50486. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50487. var dataType = parsedAnimation.dataType;
  50488. var keys = [];
  50489. var data;
  50490. var index;
  50491. if (parsedAnimation.enableBlending) {
  50492. animation.enableBlending = parsedAnimation.enableBlending;
  50493. }
  50494. if (parsedAnimation.blendingSpeed) {
  50495. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50496. }
  50497. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50498. var key = parsedAnimation.keys[index];
  50499. var inTangent;
  50500. var outTangent;
  50501. switch (dataType) {
  50502. case Animation.ANIMATIONTYPE_FLOAT:
  50503. data = key.values[0];
  50504. if (key.values.length >= 1) {
  50505. inTangent = key.values[1];
  50506. }
  50507. if (key.values.length >= 2) {
  50508. outTangent = key.values[2];
  50509. }
  50510. break;
  50511. case Animation.ANIMATIONTYPE_QUATERNION:
  50512. data = BABYLON.Quaternion.FromArray(key.values);
  50513. if (key.values.length >= 8) {
  50514. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50515. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50516. inTangent = _inTangent;
  50517. }
  50518. }
  50519. if (key.values.length >= 12) {
  50520. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50521. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50522. outTangent = _outTangent;
  50523. }
  50524. }
  50525. break;
  50526. case Animation.ANIMATIONTYPE_MATRIX:
  50527. data = BABYLON.Matrix.FromArray(key.values);
  50528. break;
  50529. case Animation.ANIMATIONTYPE_COLOR3:
  50530. data = BABYLON.Color3.FromArray(key.values);
  50531. break;
  50532. case Animation.ANIMATIONTYPE_VECTOR3:
  50533. default:
  50534. data = BABYLON.Vector3.FromArray(key.values);
  50535. break;
  50536. }
  50537. var keyData = {};
  50538. keyData.frame = key.frame;
  50539. keyData.value = data;
  50540. if (inTangent != undefined) {
  50541. keyData.inTangent = inTangent;
  50542. }
  50543. if (outTangent != undefined) {
  50544. keyData.outTangent = outTangent;
  50545. }
  50546. keys.push(keyData);
  50547. }
  50548. animation.setKeys(keys);
  50549. if (parsedAnimation.ranges) {
  50550. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50551. data = parsedAnimation.ranges[index];
  50552. animation.createRange(data.name, data.from, data.to);
  50553. }
  50554. }
  50555. return animation;
  50556. };
  50557. /**
  50558. * Appends the serialized animations from the source animations
  50559. * @param source Source containing the animations
  50560. * @param destination Target to store the animations
  50561. */
  50562. Animation.AppendSerializedAnimations = function (source, destination) {
  50563. if (source.animations) {
  50564. destination.animations = [];
  50565. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50566. var animation = source.animations[animationIndex];
  50567. destination.animations.push(animation.serialize());
  50568. }
  50569. }
  50570. };
  50571. /**
  50572. * Use matrix interpolation instead of using direct key value when animating matrices
  50573. */
  50574. Animation.AllowMatricesInterpolation = false;
  50575. /**
  50576. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50577. */
  50578. Animation.AllowMatrixDecomposeForInterpolation = true;
  50579. // Statics
  50580. /**
  50581. * Float animation type
  50582. */
  50583. Animation._ANIMATIONTYPE_FLOAT = 0;
  50584. /**
  50585. * Vector3 animation type
  50586. */
  50587. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50588. /**
  50589. * Quaternion animation type
  50590. */
  50591. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50592. /**
  50593. * Matrix animation type
  50594. */
  50595. Animation._ANIMATIONTYPE_MATRIX = 3;
  50596. /**
  50597. * Color3 animation type
  50598. */
  50599. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50600. /**
  50601. * Vector2 animation type
  50602. */
  50603. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50604. /**
  50605. * Size animation type
  50606. */
  50607. Animation._ANIMATIONTYPE_SIZE = 6;
  50608. /**
  50609. * Relative Loop Mode
  50610. */
  50611. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50612. /**
  50613. * Cycle Loop Mode
  50614. */
  50615. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50616. /**
  50617. * Constant Loop Mode
  50618. */
  50619. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50620. return Animation;
  50621. }());
  50622. BABYLON.Animation = Animation;
  50623. })(BABYLON || (BABYLON = {}));
  50624. //# sourceMappingURL=babylon.animation.js.map
  50625. var BABYLON;
  50626. (function (BABYLON) {
  50627. /**
  50628. * This class defines the direct association between an animation and a target
  50629. */
  50630. var TargetedAnimation = /** @class */ (function () {
  50631. function TargetedAnimation() {
  50632. }
  50633. return TargetedAnimation;
  50634. }());
  50635. BABYLON.TargetedAnimation = TargetedAnimation;
  50636. /**
  50637. * Use this class to create coordinated animations on multiple targets
  50638. */
  50639. var AnimationGroup = /** @class */ (function () {
  50640. function AnimationGroup(name, scene) {
  50641. if (scene === void 0) { scene = null; }
  50642. this.name = name;
  50643. this._targetedAnimations = new Array();
  50644. this._animatables = new Array();
  50645. this._from = Number.MAX_VALUE;
  50646. this._to = -Number.MAX_VALUE;
  50647. this._speedRatio = 1;
  50648. this.onAnimationEndObservable = new BABYLON.Observable();
  50649. /**
  50650. * This observable will notify when all animations have ended.
  50651. */
  50652. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50653. /**
  50654. * This observable will notify when all animations have paused.
  50655. */
  50656. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50657. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50658. this._scene.animationGroups.push(this);
  50659. }
  50660. Object.defineProperty(AnimationGroup.prototype, "from", {
  50661. /**
  50662. * Gets the first frame
  50663. */
  50664. get: function () {
  50665. return this._from;
  50666. },
  50667. enumerable: true,
  50668. configurable: true
  50669. });
  50670. Object.defineProperty(AnimationGroup.prototype, "to", {
  50671. /**
  50672. * Gets the last frame
  50673. */
  50674. get: function () {
  50675. return this._to;
  50676. },
  50677. enumerable: true,
  50678. configurable: true
  50679. });
  50680. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50681. /**
  50682. * Define if the animations are started
  50683. */
  50684. get: function () {
  50685. return this._isStarted;
  50686. },
  50687. enumerable: true,
  50688. configurable: true
  50689. });
  50690. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50691. /**
  50692. * Gets or sets the speed ratio to use for all animations
  50693. */
  50694. get: function () {
  50695. return this._speedRatio;
  50696. },
  50697. /**
  50698. * Gets or sets the speed ratio to use for all animations
  50699. */
  50700. set: function (value) {
  50701. if (this._speedRatio === value) {
  50702. return;
  50703. }
  50704. this._speedRatio = value;
  50705. for (var index = 0; index < this._animatables.length; index++) {
  50706. var animatable = this._animatables[index];
  50707. animatable.speedRatio = this._speedRatio;
  50708. }
  50709. },
  50710. enumerable: true,
  50711. configurable: true
  50712. });
  50713. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50714. /**
  50715. * Gets the targeted animations for this animation group
  50716. */
  50717. get: function () {
  50718. return this._targetedAnimations;
  50719. },
  50720. enumerable: true,
  50721. configurable: true
  50722. });
  50723. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50724. /**
  50725. * returning the list of animatables controlled by this animation group.
  50726. */
  50727. get: function () {
  50728. return this._animatables;
  50729. },
  50730. enumerable: true,
  50731. configurable: true
  50732. });
  50733. /**
  50734. * Add an animation (with its target) in the group
  50735. * @param animation defines the animation we want to add
  50736. * @param target defines the target of the animation
  50737. * @returns the {BABYLON.TargetedAnimation} object
  50738. */
  50739. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50740. var targetedAnimation = {
  50741. animation: animation,
  50742. target: target
  50743. };
  50744. var keys = animation.getKeys();
  50745. if (this._from > keys[0].frame) {
  50746. this._from = keys[0].frame;
  50747. }
  50748. if (this._to < keys[keys.length - 1].frame) {
  50749. this._to = keys[keys.length - 1].frame;
  50750. }
  50751. this._targetedAnimations.push(targetedAnimation);
  50752. return targetedAnimation;
  50753. };
  50754. /**
  50755. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50756. * It can add constant keys at begin or end
  50757. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50758. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50759. */
  50760. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50761. if (beginFrame === void 0) { beginFrame = null; }
  50762. if (endFrame === void 0) { endFrame = null; }
  50763. if (beginFrame == null)
  50764. beginFrame = this._from;
  50765. if (endFrame == null)
  50766. endFrame = this._to;
  50767. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50768. var targetedAnimation = this._targetedAnimations[index];
  50769. var keys = targetedAnimation.animation.getKeys();
  50770. var startKey = keys[0];
  50771. var endKey = keys[keys.length - 1];
  50772. if (startKey.frame > beginFrame) {
  50773. var newKey = {
  50774. frame: beginFrame,
  50775. value: startKey.value,
  50776. inTangent: startKey.inTangent,
  50777. outTangent: startKey.outTangent,
  50778. interpolation: startKey.interpolation
  50779. };
  50780. keys.splice(0, 0, newKey);
  50781. }
  50782. if (endKey.frame < endFrame) {
  50783. var newKey = {
  50784. frame: endFrame,
  50785. value: endKey.value,
  50786. inTangent: endKey.outTangent,
  50787. outTangent: endKey.outTangent,
  50788. interpolation: endKey.interpolation
  50789. };
  50790. keys.push(newKey);
  50791. }
  50792. }
  50793. this._from = beginFrame;
  50794. this._to = endFrame;
  50795. return this;
  50796. };
  50797. /**
  50798. * Start all animations on given targets
  50799. * @param loop defines if animations must loop
  50800. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50801. * @param from defines the from key (optional)
  50802. * @param to defines the to key (optional)
  50803. * @returns the current animation group
  50804. */
  50805. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50806. var _this = this;
  50807. if (loop === void 0) { loop = false; }
  50808. if (speedRatio === void 0) { speedRatio = 1; }
  50809. if (this._isStarted || this._targetedAnimations.length === 0) {
  50810. return this;
  50811. }
  50812. var _loop_1 = function (targetedAnimation) {
  50813. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50814. animatable.onAnimationEnd = function () {
  50815. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50816. _this._checkAnimationGroupEnded(animatable);
  50817. };
  50818. this_1._animatables.push(animatable);
  50819. };
  50820. var this_1 = this;
  50821. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50822. var targetedAnimation = _a[_i];
  50823. _loop_1(targetedAnimation);
  50824. }
  50825. this._speedRatio = speedRatio;
  50826. this._isStarted = true;
  50827. return this;
  50828. };
  50829. /**
  50830. * Pause all animations
  50831. */
  50832. AnimationGroup.prototype.pause = function () {
  50833. if (!this._isStarted) {
  50834. return this;
  50835. }
  50836. for (var index = 0; index < this._animatables.length; index++) {
  50837. var animatable = this._animatables[index];
  50838. animatable.pause();
  50839. }
  50840. this.onAnimationGroupPauseObservable.notifyObservers(this);
  50841. return this;
  50842. };
  50843. /**
  50844. * Play all animations to initial state
  50845. * This function will start() the animations if they were not started or will restart() them if they were paused
  50846. * @param loop defines if animations must loop
  50847. */
  50848. AnimationGroup.prototype.play = function (loop) {
  50849. // only if all animatables are ready and exist
  50850. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50851. if (loop !== undefined) {
  50852. for (var index = 0; index < this._animatables.length; index++) {
  50853. var animatable = this._animatables[index];
  50854. animatable.loopAnimation = loop;
  50855. }
  50856. }
  50857. this.restart();
  50858. }
  50859. else {
  50860. this.stop();
  50861. this.start(loop, this._speedRatio);
  50862. }
  50863. return this;
  50864. };
  50865. /**
  50866. * Reset all animations to initial state
  50867. */
  50868. AnimationGroup.prototype.reset = function () {
  50869. if (!this._isStarted) {
  50870. return this;
  50871. }
  50872. for (var index = 0; index < this._animatables.length; index++) {
  50873. var animatable = this._animatables[index];
  50874. animatable.reset();
  50875. }
  50876. return this;
  50877. };
  50878. /**
  50879. * Restart animations from key 0
  50880. */
  50881. AnimationGroup.prototype.restart = function () {
  50882. if (!this._isStarted) {
  50883. return this;
  50884. }
  50885. for (var index = 0; index < this._animatables.length; index++) {
  50886. var animatable = this._animatables[index];
  50887. animatable.restart();
  50888. }
  50889. return this;
  50890. };
  50891. /**
  50892. * Stop all animations
  50893. */
  50894. AnimationGroup.prototype.stop = function () {
  50895. if (!this._isStarted) {
  50896. return this;
  50897. }
  50898. var list = this._animatables.slice();
  50899. for (var index = 0; index < list.length; index++) {
  50900. list[index].stop();
  50901. }
  50902. this._isStarted = false;
  50903. return this;
  50904. };
  50905. /**
  50906. * Set animation weight for all animatables
  50907. * @param weight defines the weight to use
  50908. * @return the animationGroup
  50909. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50910. */
  50911. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50912. for (var index = 0; index < this._animatables.length; index++) {
  50913. var animatable = this._animatables[index];
  50914. animatable.weight = weight;
  50915. }
  50916. return this;
  50917. };
  50918. /**
  50919. * Synchronize and normalize all animatables with a source animatable
  50920. * @param root defines the root animatable to synchronize with
  50921. * @return the animationGroup
  50922. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50923. */
  50924. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50925. for (var index = 0; index < this._animatables.length; index++) {
  50926. var animatable = this._animatables[index];
  50927. animatable.syncWith(root);
  50928. }
  50929. return this;
  50930. };
  50931. /**
  50932. * Goes to a specific frame in this animation group
  50933. * @param frame the frame number to go to
  50934. * @return the animationGroup
  50935. */
  50936. AnimationGroup.prototype.goToFrame = function (frame) {
  50937. if (!this._isStarted) {
  50938. return this;
  50939. }
  50940. for (var index = 0; index < this._animatables.length; index++) {
  50941. var animatable = this._animatables[index];
  50942. animatable.goToFrame(frame);
  50943. }
  50944. return this;
  50945. };
  50946. /**
  50947. * Dispose all associated resources
  50948. */
  50949. AnimationGroup.prototype.dispose = function () {
  50950. this._targetedAnimations = [];
  50951. this._animatables = [];
  50952. var index = this._scene.animationGroups.indexOf(this);
  50953. if (index > -1) {
  50954. this._scene.animationGroups.splice(index, 1);
  50955. }
  50956. };
  50957. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50958. // animatable should be taken out of the array
  50959. var idx = this._animatables.indexOf(animatable);
  50960. if (idx > -1) {
  50961. this._animatables.splice(idx, 1);
  50962. }
  50963. // all animatables were removed? animation group ended!
  50964. if (this._animatables.length === 0) {
  50965. this._isStarted = false;
  50966. this.onAnimationGroupEndObservable.notifyObservers(this);
  50967. }
  50968. };
  50969. return AnimationGroup;
  50970. }());
  50971. BABYLON.AnimationGroup = AnimationGroup;
  50972. })(BABYLON || (BABYLON = {}));
  50973. //# sourceMappingURL=babylon.animationGroup.js.map
  50974. var BABYLON;
  50975. (function (BABYLON) {
  50976. // Static values to help the garbage collector
  50977. // Quaternion
  50978. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  50979. // Vector3
  50980. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  50981. // Vector2
  50982. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  50983. // Size
  50984. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  50985. // Color3
  50986. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  50987. /**
  50988. * Defines a runtime animation
  50989. */
  50990. var RuntimeAnimation = /** @class */ (function () {
  50991. /**
  50992. * Create a new RuntimeAnimation object
  50993. * @param target defines the target of the animation
  50994. * @param animation defines the source animation object
  50995. * @param scene defines the hosting scene
  50996. * @param host defines the initiating Animatable
  50997. */
  50998. function RuntimeAnimation(target, animation, scene, host) {
  50999. var _this = this;
  51000. this._events = new Array();
  51001. /**
  51002. * The current frame of the runtime animation
  51003. */
  51004. this._currentFrame = 0;
  51005. /**
  51006. * The original value of the runtime animation
  51007. */
  51008. this._originalValue = new Array();
  51009. /**
  51010. * The offsets cache of the runtime animation
  51011. */
  51012. this._offsetsCache = {};
  51013. /**
  51014. * The high limits cache of the runtime animation
  51015. */
  51016. this._highLimitsCache = {};
  51017. /**
  51018. * Specifies if the runtime animation has been stopped
  51019. */
  51020. this._stopped = false;
  51021. /**
  51022. * The blending factor of the runtime animation
  51023. */
  51024. this._blendingFactor = 0;
  51025. /**
  51026. * The target path of the runtime animation
  51027. */
  51028. this._targetPath = "";
  51029. /**
  51030. * The weight of the runtime animation
  51031. */
  51032. this._weight = 1.0;
  51033. /**
  51034. * The ratio offset of the runtime animation
  51035. */
  51036. this._ratioOffset = 0;
  51037. /**
  51038. * The previous delay of the runtime animation
  51039. */
  51040. this._previousDelay = 0;
  51041. /**
  51042. * The previous ratio of the runtime animation
  51043. */
  51044. this._previousRatio = 0;
  51045. this._animation = animation;
  51046. this._target = target;
  51047. this._scene = scene;
  51048. this._host = host;
  51049. animation._runtimeAnimations.push(this);
  51050. // Cloning events locally
  51051. var events = animation.getEvents();
  51052. if (events && events.length > 0) {
  51053. events.forEach(function (e) {
  51054. _this._events.push(e._clone());
  51055. });
  51056. }
  51057. }
  51058. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51059. /**
  51060. * Gets the current frame of the runtime animation
  51061. */
  51062. get: function () {
  51063. return this._currentFrame;
  51064. },
  51065. enumerable: true,
  51066. configurable: true
  51067. });
  51068. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51069. /**
  51070. * Gets the weight of the runtime animation
  51071. */
  51072. get: function () {
  51073. return this._weight;
  51074. },
  51075. enumerable: true,
  51076. configurable: true
  51077. });
  51078. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51079. /**
  51080. * Gets the current value of the runtime animation
  51081. */
  51082. get: function () {
  51083. return this._currentValue;
  51084. },
  51085. enumerable: true,
  51086. configurable: true
  51087. });
  51088. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51089. /**
  51090. * Gets the target path of the runtime animation
  51091. */
  51092. get: function () {
  51093. return this._targetPath;
  51094. },
  51095. enumerable: true,
  51096. configurable: true
  51097. });
  51098. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51099. /**
  51100. * Gets the actual target of the runtime animation
  51101. */
  51102. get: function () {
  51103. return this._activeTarget;
  51104. },
  51105. enumerable: true,
  51106. configurable: true
  51107. });
  51108. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51109. /**
  51110. * Gets the animation from the runtime animation
  51111. */
  51112. get: function () {
  51113. return this._animation;
  51114. },
  51115. enumerable: true,
  51116. configurable: true
  51117. });
  51118. /**
  51119. * Resets the runtime animation to the beginning
  51120. * @param restoreOriginal defines whether to restore the target property to the original value
  51121. */
  51122. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51123. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51124. if (restoreOriginal) {
  51125. if (this._target instanceof Array) {
  51126. var index = 0;
  51127. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51128. var target = _a[_i];
  51129. if (this._originalValue[index] !== undefined) {
  51130. this._setValue(target, this._originalValue[index], -1);
  51131. }
  51132. index++;
  51133. }
  51134. }
  51135. else {
  51136. if (this._originalValue[0] !== undefined) {
  51137. this._setValue(this._target, this._originalValue[0], -1);
  51138. }
  51139. }
  51140. }
  51141. this._offsetsCache = {};
  51142. this._highLimitsCache = {};
  51143. this._currentFrame = 0;
  51144. this._blendingFactor = 0;
  51145. this._originalValue = new Array();
  51146. // Events
  51147. for (var index = 0; index < this._events.length; index++) {
  51148. this._events[index].isDone = false;
  51149. }
  51150. };
  51151. /**
  51152. * Specifies if the runtime animation is stopped
  51153. * @returns Boolean specifying if the runtime animation is stopped
  51154. */
  51155. RuntimeAnimation.prototype.isStopped = function () {
  51156. return this._stopped;
  51157. };
  51158. /**
  51159. * Disposes of the runtime animation
  51160. */
  51161. RuntimeAnimation.prototype.dispose = function () {
  51162. var index = this._animation.runtimeAnimations.indexOf(this);
  51163. if (index > -1) {
  51164. this._animation.runtimeAnimations.splice(index, 1);
  51165. }
  51166. };
  51167. /**
  51168. * Interpolates the animation from the current frame
  51169. * @param currentFrame The frame to interpolate the animation to
  51170. * @param repeatCount The number of times that the animation should loop
  51171. * @param loopMode The type of looping mode to use
  51172. * @param offsetValue Animation offset value
  51173. * @param highLimitValue The high limit value
  51174. * @returns The interpolated value
  51175. */
  51176. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51177. this._currentFrame = currentFrame;
  51178. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51179. this._workValue = BABYLON.Matrix.Zero();
  51180. }
  51181. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51182. };
  51183. /**
  51184. * Apply the interpolated value to the target
  51185. * @param currentValue defines the value computed by the animation
  51186. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51187. */
  51188. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51189. if (weight === void 0) { weight = 1.0; }
  51190. if (this._target instanceof Array) {
  51191. var index = 0;
  51192. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51193. var target = _a[_i];
  51194. this._setValue(target, currentValue, weight, index);
  51195. index++;
  51196. }
  51197. }
  51198. else {
  51199. this._setValue(this._target, currentValue, weight);
  51200. }
  51201. };
  51202. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51203. if (targetIndex === void 0) { targetIndex = 0; }
  51204. // Set value
  51205. var path;
  51206. var destination;
  51207. var targetPropertyPath = this._animation.targetPropertyPath;
  51208. if (targetPropertyPath.length > 1) {
  51209. var property = target[targetPropertyPath[0]];
  51210. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51211. property = property[targetPropertyPath[index]];
  51212. }
  51213. path = targetPropertyPath[targetPropertyPath.length - 1];
  51214. destination = property;
  51215. }
  51216. else {
  51217. path = targetPropertyPath[0];
  51218. destination = target;
  51219. }
  51220. this._targetPath = path;
  51221. this._activeTarget = destination;
  51222. this._weight = weight;
  51223. if (this._originalValue[targetIndex] === undefined) {
  51224. var originalValue = void 0;
  51225. if (destination.getRestPose && path === "_matrix") { // For bones
  51226. originalValue = destination.getRestPose();
  51227. }
  51228. else {
  51229. originalValue = destination[path];
  51230. }
  51231. if (originalValue && originalValue.clone) {
  51232. this._originalValue[targetIndex] = originalValue.clone();
  51233. }
  51234. else {
  51235. this._originalValue[targetIndex] = originalValue;
  51236. }
  51237. }
  51238. // Blending
  51239. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51240. if (enableBlending && this._blendingFactor <= 1.0) {
  51241. if (!this._originalBlendValue) {
  51242. var originalValue = destination[path];
  51243. if (originalValue.clone) {
  51244. this._originalBlendValue = originalValue.clone();
  51245. }
  51246. else {
  51247. this._originalBlendValue = originalValue;
  51248. }
  51249. }
  51250. if (this._originalBlendValue.m) { // Matrix
  51251. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51252. if (this._currentValue) {
  51253. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51254. }
  51255. else {
  51256. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51257. }
  51258. }
  51259. else {
  51260. if (this._currentValue) {
  51261. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51262. }
  51263. else {
  51264. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51265. }
  51266. }
  51267. }
  51268. else {
  51269. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51270. }
  51271. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51272. this._blendingFactor += blendingSpeed;
  51273. }
  51274. else {
  51275. this._currentValue = currentValue;
  51276. }
  51277. if (weight !== -1.0) {
  51278. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51279. }
  51280. else {
  51281. destination[path] = this._currentValue;
  51282. }
  51283. if (target.markAsDirty) {
  51284. target.markAsDirty(this._animation.targetProperty);
  51285. }
  51286. };
  51287. /**
  51288. * Gets the loop pmode of the runtime animation
  51289. * @returns Loop Mode
  51290. */
  51291. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51292. if (this._target && this._target.animationPropertiesOverride) {
  51293. return this._target.animationPropertiesOverride.loopMode;
  51294. }
  51295. return this._animation.loopMode;
  51296. };
  51297. /**
  51298. * Move the current animation to a given frame
  51299. * @param frame defines the frame to move to
  51300. */
  51301. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51302. var keys = this._animation.getKeys();
  51303. if (frame < keys[0].frame) {
  51304. frame = keys[0].frame;
  51305. }
  51306. else if (frame > keys[keys.length - 1].frame) {
  51307. frame = keys[keys.length - 1].frame;
  51308. }
  51309. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51310. this.setValue(currentValue, -1);
  51311. };
  51312. /**
  51313. * @hidden Internal use only
  51314. */
  51315. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51316. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51317. this._ratioOffset = this._previousRatio - newRatio;
  51318. };
  51319. /**
  51320. * Execute the current animation
  51321. * @param delay defines the delay to add to the current frame
  51322. * @param from defines the lower bound of the animation range
  51323. * @param to defines the upper bound of the animation range
  51324. * @param loop defines if the current animation must loop
  51325. * @param speedRatio defines the current speed ratio
  51326. * @param weight defines the weight of the animation (default is -1 so no weight)
  51327. * @returns a boolean indicating if the animation is running
  51328. */
  51329. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51330. if (weight === void 0) { weight = -1.0; }
  51331. var targetPropertyPath = this._animation.targetPropertyPath;
  51332. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51333. this._stopped = true;
  51334. return false;
  51335. }
  51336. var returnValue = true;
  51337. var keys = this._animation.getKeys();
  51338. // Adding a start key at frame 0 if missing
  51339. if (keys[0].frame !== 0) {
  51340. var newKey = { frame: 0, value: keys[0].value };
  51341. keys.splice(0, 0, newKey);
  51342. }
  51343. // Adding a duplicate key when there is only one key at frame zero
  51344. else if (keys.length === 1) {
  51345. var newKey = { frame: 0.001, value: keys[0].value };
  51346. keys.push(newKey);
  51347. }
  51348. // Check limits
  51349. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51350. from = keys[0].frame;
  51351. }
  51352. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51353. to = keys[keys.length - 1].frame;
  51354. }
  51355. //to and from cannot be the same key
  51356. if (from === to) {
  51357. if (from > keys[0].frame) {
  51358. from--;
  51359. }
  51360. else if (to < keys[keys.length - 1].frame) {
  51361. to++;
  51362. }
  51363. }
  51364. // Compute ratio
  51365. var range = to - from;
  51366. var offsetValue;
  51367. // ratio represents the frame delta between from and to
  51368. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51369. var highLimitValue = 0;
  51370. this._previousDelay = delay;
  51371. this._previousRatio = ratio;
  51372. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51373. returnValue = false;
  51374. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51375. }
  51376. else {
  51377. // Get max value if required
  51378. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51379. var keyOffset = to.toString() + from.toString();
  51380. if (!this._offsetsCache[keyOffset]) {
  51381. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51382. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51383. switch (this._animation.dataType) {
  51384. // Float
  51385. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51386. this._offsetsCache[keyOffset] = toValue - fromValue;
  51387. break;
  51388. // Quaternion
  51389. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51390. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51391. break;
  51392. // Vector3
  51393. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51394. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51395. // Vector2
  51396. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51397. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51398. // Size
  51399. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51400. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51401. // Color3
  51402. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51403. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51404. default:
  51405. break;
  51406. }
  51407. this._highLimitsCache[keyOffset] = toValue;
  51408. }
  51409. highLimitValue = this._highLimitsCache[keyOffset];
  51410. offsetValue = this._offsetsCache[keyOffset];
  51411. }
  51412. }
  51413. if (offsetValue === undefined) {
  51414. switch (this._animation.dataType) {
  51415. // Float
  51416. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51417. offsetValue = 0;
  51418. break;
  51419. // Quaternion
  51420. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51421. offsetValue = _staticOffsetValueQuaternion;
  51422. break;
  51423. // Vector3
  51424. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51425. offsetValue = _staticOffsetValueVector3;
  51426. break;
  51427. // Vector2
  51428. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51429. offsetValue = _staticOffsetValueVector2;
  51430. break;
  51431. // Size
  51432. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51433. offsetValue = _staticOffsetValueSize;
  51434. break;
  51435. // Color3
  51436. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51437. offsetValue = _staticOffsetValueColor3;
  51438. }
  51439. }
  51440. // Compute value
  51441. var repeatCount = (ratio / range) >> 0;
  51442. var currentFrame = returnValue ? from + ratio % range : to;
  51443. // Need to normalize?
  51444. if (this._host && this._host.syncRoot) {
  51445. var syncRoot = this._host.syncRoot;
  51446. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51447. currentFrame = from + (to - from) * hostNormalizedFrame;
  51448. }
  51449. // Reset events if looping
  51450. var events = this._events;
  51451. if (range > 0 && this.currentFrame > currentFrame ||
  51452. range < 0 && this.currentFrame < currentFrame) {
  51453. // Need to reset animation events
  51454. for (var index = 0; index < events.length; index++) {
  51455. if (!events[index].onlyOnce) {
  51456. // reset event, the animation is looping
  51457. events[index].isDone = false;
  51458. }
  51459. }
  51460. }
  51461. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51462. // Set value
  51463. this.setValue(currentValue, weight);
  51464. // Check events
  51465. for (var index = 0; index < events.length; index++) {
  51466. // Make sure current frame has passed event frame and that event frame is within the current range
  51467. // Also, handle both forward and reverse animations
  51468. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51469. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51470. var event = events[index];
  51471. if (!event.isDone) {
  51472. // If event should be done only once, remove it.
  51473. if (event.onlyOnce) {
  51474. events.splice(index, 1);
  51475. index--;
  51476. }
  51477. event.isDone = true;
  51478. event.action(currentFrame);
  51479. } // Don't do anything if the event has already be done.
  51480. }
  51481. }
  51482. if (!returnValue) {
  51483. this._stopped = true;
  51484. }
  51485. return returnValue;
  51486. };
  51487. return RuntimeAnimation;
  51488. }());
  51489. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51490. })(BABYLON || (BABYLON = {}));
  51491. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51492. var BABYLON;
  51493. (function (BABYLON) {
  51494. /**
  51495. * Class used to store an actual running animation
  51496. */
  51497. var Animatable = /** @class */ (function () {
  51498. /**
  51499. * Creates a new Animatable
  51500. * @param scene defines the hosting scene
  51501. * @param target defines the target object
  51502. * @param fromFrame defines the starting frame number (default is 0)
  51503. * @param toFrame defines the ending frame number (default is 100)
  51504. * @param loopAnimation defines if the animation must loop (default is false)
  51505. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51506. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51507. * @param animations defines a group of animation to add to the new Animatable
  51508. */
  51509. function Animatable(scene,
  51510. /** defines the target object */
  51511. target,
  51512. /** defines the starting frame number (default is 0) */
  51513. fromFrame,
  51514. /** defines the ending frame number (default is 100) */
  51515. toFrame,
  51516. /** defines if the animation must loop (default is false) */
  51517. loopAnimation, speedRatio,
  51518. /** defines a callback to call when animation ends if it is not looping */
  51519. onAnimationEnd, animations) {
  51520. if (fromFrame === void 0) { fromFrame = 0; }
  51521. if (toFrame === void 0) { toFrame = 100; }
  51522. if (loopAnimation === void 0) { loopAnimation = false; }
  51523. if (speedRatio === void 0) { speedRatio = 1.0; }
  51524. this.target = target;
  51525. this.fromFrame = fromFrame;
  51526. this.toFrame = toFrame;
  51527. this.loopAnimation = loopAnimation;
  51528. this.onAnimationEnd = onAnimationEnd;
  51529. this._localDelayOffset = null;
  51530. this._pausedDelay = null;
  51531. this._runtimeAnimations = new Array();
  51532. this._paused = false;
  51533. this._speedRatio = 1;
  51534. this._weight = -1.0;
  51535. /**
  51536. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51537. * This will only apply for non looping animation (default is true)
  51538. */
  51539. this.disposeOnEnd = true;
  51540. /**
  51541. * Gets a boolean indicating if the animation has started
  51542. */
  51543. this.animationStarted = false;
  51544. /**
  51545. * Observer raised when the animation ends
  51546. */
  51547. this.onAnimationEndObservable = new BABYLON.Observable();
  51548. this._scene = scene;
  51549. if (animations) {
  51550. this.appendAnimations(target, animations);
  51551. }
  51552. this._speedRatio = speedRatio;
  51553. scene._activeAnimatables.push(this);
  51554. }
  51555. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51556. /**
  51557. * Gets the root Animatable used to synchronize and normalize animations
  51558. */
  51559. get: function () {
  51560. return this._syncRoot;
  51561. },
  51562. enumerable: true,
  51563. configurable: true
  51564. });
  51565. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51566. /**
  51567. * Gets the current frame of the first RuntimeAnimation
  51568. * Used to synchronize Animatables
  51569. */
  51570. get: function () {
  51571. if (this._runtimeAnimations.length === 0) {
  51572. return 0;
  51573. }
  51574. return this._runtimeAnimations[0].currentFrame;
  51575. },
  51576. enumerable: true,
  51577. configurable: true
  51578. });
  51579. Object.defineProperty(Animatable.prototype, "weight", {
  51580. /**
  51581. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51582. */
  51583. get: function () {
  51584. return this._weight;
  51585. },
  51586. set: function (value) {
  51587. if (value === -1) { // -1 is ok and means no weight
  51588. this._weight = -1;
  51589. return;
  51590. }
  51591. // Else weight must be in [0, 1] range
  51592. this._weight = Math.min(Math.max(value, 0), 1.0);
  51593. },
  51594. enumerable: true,
  51595. configurable: true
  51596. });
  51597. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51598. /**
  51599. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51600. */
  51601. get: function () {
  51602. return this._speedRatio;
  51603. },
  51604. set: function (value) {
  51605. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51606. var animation = this._runtimeAnimations[index];
  51607. animation._prepareForSpeedRatioChange(value);
  51608. }
  51609. this._speedRatio = value;
  51610. },
  51611. enumerable: true,
  51612. configurable: true
  51613. });
  51614. // Methods
  51615. /**
  51616. * Synchronize and normalize current Animatable with a source Animatable
  51617. * This is useful when using animation weights and when animations are not of the same length
  51618. * @param root defines the root Animatable to synchronize with
  51619. * @returns the current Animatable
  51620. */
  51621. Animatable.prototype.syncWith = function (root) {
  51622. this._syncRoot = root;
  51623. if (root) {
  51624. // Make sure this animatable will animate after the root
  51625. var index = this._scene._activeAnimatables.indexOf(this);
  51626. if (index > -1) {
  51627. this._scene._activeAnimatables.splice(index, 1);
  51628. this._scene._activeAnimatables.push(this);
  51629. }
  51630. }
  51631. return this;
  51632. };
  51633. /**
  51634. * Gets the list of runtime animations
  51635. * @returns an array of RuntimeAnimation
  51636. */
  51637. Animatable.prototype.getAnimations = function () {
  51638. return this._runtimeAnimations;
  51639. };
  51640. /**
  51641. * Adds more animations to the current animatable
  51642. * @param target defines the target of the animations
  51643. * @param animations defines the new animations to add
  51644. */
  51645. Animatable.prototype.appendAnimations = function (target, animations) {
  51646. for (var index = 0; index < animations.length; index++) {
  51647. var animation = animations[index];
  51648. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51649. }
  51650. };
  51651. /**
  51652. * Gets the source animation for a specific property
  51653. * @param property defines the propertyu to look for
  51654. * @returns null or the source animation for the given property
  51655. */
  51656. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51657. var runtimeAnimations = this._runtimeAnimations;
  51658. for (var index = 0; index < runtimeAnimations.length; index++) {
  51659. if (runtimeAnimations[index].animation.targetProperty === property) {
  51660. return runtimeAnimations[index].animation;
  51661. }
  51662. }
  51663. return null;
  51664. };
  51665. /**
  51666. * Gets the runtime animation for a specific property
  51667. * @param property defines the propertyu to look for
  51668. * @returns null or the runtime animation for the given property
  51669. */
  51670. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51671. var runtimeAnimations = this._runtimeAnimations;
  51672. for (var index = 0; index < runtimeAnimations.length; index++) {
  51673. if (runtimeAnimations[index].animation.targetProperty === property) {
  51674. return runtimeAnimations[index];
  51675. }
  51676. }
  51677. return null;
  51678. };
  51679. /**
  51680. * Resets the animatable to its original state
  51681. */
  51682. Animatable.prototype.reset = function () {
  51683. var runtimeAnimations = this._runtimeAnimations;
  51684. for (var index = 0; index < runtimeAnimations.length; index++) {
  51685. runtimeAnimations[index].reset(true);
  51686. }
  51687. this._localDelayOffset = null;
  51688. this._pausedDelay = null;
  51689. };
  51690. /**
  51691. * Allows the animatable to blend with current running animations
  51692. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51693. * @param blendingSpeed defines the blending speed to use
  51694. */
  51695. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51696. var runtimeAnimations = this._runtimeAnimations;
  51697. for (var index = 0; index < runtimeAnimations.length; index++) {
  51698. runtimeAnimations[index].animation.enableBlending = true;
  51699. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51700. }
  51701. };
  51702. /**
  51703. * Disable animation blending
  51704. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51705. */
  51706. Animatable.prototype.disableBlending = function () {
  51707. var runtimeAnimations = this._runtimeAnimations;
  51708. for (var index = 0; index < runtimeAnimations.length; index++) {
  51709. runtimeAnimations[index].animation.enableBlending = false;
  51710. }
  51711. };
  51712. /**
  51713. * Jump directly to a given frame
  51714. * @param frame defines the frame to jump to
  51715. */
  51716. Animatable.prototype.goToFrame = function (frame) {
  51717. var runtimeAnimations = this._runtimeAnimations;
  51718. if (runtimeAnimations[0]) {
  51719. var fps = runtimeAnimations[0].animation.framePerSecond;
  51720. var currentFrame = runtimeAnimations[0].currentFrame;
  51721. var adjustTime = frame - currentFrame;
  51722. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51723. if (this._localDelayOffset === null) {
  51724. this._localDelayOffset = 0;
  51725. }
  51726. this._localDelayOffset -= delay;
  51727. }
  51728. for (var index = 0; index < runtimeAnimations.length; index++) {
  51729. runtimeAnimations[index].goToFrame(frame);
  51730. }
  51731. };
  51732. /**
  51733. * Pause the animation
  51734. */
  51735. Animatable.prototype.pause = function () {
  51736. if (this._paused) {
  51737. return;
  51738. }
  51739. this._paused = true;
  51740. };
  51741. /**
  51742. * Restart the animation
  51743. */
  51744. Animatable.prototype.restart = function () {
  51745. this._paused = false;
  51746. };
  51747. Animatable.prototype._raiseOnAnimationEnd = function () {
  51748. if (this.onAnimationEnd) {
  51749. this.onAnimationEnd();
  51750. }
  51751. this.onAnimationEndObservable.notifyObservers(this);
  51752. };
  51753. /**
  51754. * Stop and delete the current animation
  51755. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51756. * @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)
  51757. */
  51758. Animatable.prototype.stop = function (animationName, targetMask) {
  51759. if (animationName || targetMask) {
  51760. var idx = this._scene._activeAnimatables.indexOf(this);
  51761. if (idx > -1) {
  51762. var runtimeAnimations = this._runtimeAnimations;
  51763. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51764. var runtimeAnimation = runtimeAnimations[index];
  51765. if (animationName && runtimeAnimation.animation.name != animationName) {
  51766. continue;
  51767. }
  51768. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51769. continue;
  51770. }
  51771. runtimeAnimation.dispose();
  51772. runtimeAnimations.splice(index, 1);
  51773. }
  51774. if (runtimeAnimations.length == 0) {
  51775. this._scene._activeAnimatables.splice(idx, 1);
  51776. this._raiseOnAnimationEnd();
  51777. }
  51778. }
  51779. }
  51780. else {
  51781. var index = this._scene._activeAnimatables.indexOf(this);
  51782. if (index > -1) {
  51783. this._scene._activeAnimatables.splice(index, 1);
  51784. var runtimeAnimations = this._runtimeAnimations;
  51785. for (var index = 0; index < runtimeAnimations.length; index++) {
  51786. runtimeAnimations[index].dispose();
  51787. }
  51788. this._raiseOnAnimationEnd();
  51789. }
  51790. }
  51791. };
  51792. /**
  51793. * Wait asynchronously for the animation to end
  51794. * @returns a promise which will be fullfilled when the animation ends
  51795. */
  51796. Animatable.prototype.waitAsync = function () {
  51797. var _this = this;
  51798. return new Promise(function (resolve, reject) {
  51799. _this.onAnimationEndObservable.add(function () {
  51800. resolve(_this);
  51801. }, undefined, undefined, _this, true);
  51802. });
  51803. };
  51804. /** @hidden */
  51805. Animatable.prototype._animate = function (delay) {
  51806. if (this._paused) {
  51807. this.animationStarted = false;
  51808. if (this._pausedDelay === null) {
  51809. this._pausedDelay = delay;
  51810. }
  51811. return true;
  51812. }
  51813. if (this._localDelayOffset === null) {
  51814. this._localDelayOffset = delay;
  51815. this._pausedDelay = null;
  51816. }
  51817. else if (this._pausedDelay !== null) {
  51818. this._localDelayOffset += delay - this._pausedDelay;
  51819. this._pausedDelay = null;
  51820. }
  51821. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51822. return true;
  51823. }
  51824. // Animating
  51825. var running = false;
  51826. var runtimeAnimations = this._runtimeAnimations;
  51827. var index;
  51828. for (index = 0; index < runtimeAnimations.length; index++) {
  51829. var animation = runtimeAnimations[index];
  51830. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51831. running = running || isRunning;
  51832. }
  51833. this.animationStarted = running;
  51834. if (!running) {
  51835. if (this.disposeOnEnd) {
  51836. // Remove from active animatables
  51837. index = this._scene._activeAnimatables.indexOf(this);
  51838. this._scene._activeAnimatables.splice(index, 1);
  51839. // Dispose all runtime animations
  51840. for (index = 0; index < runtimeAnimations.length; index++) {
  51841. runtimeAnimations[index].dispose();
  51842. }
  51843. }
  51844. this._raiseOnAnimationEnd();
  51845. if (this.disposeOnEnd) {
  51846. this.onAnimationEnd = null;
  51847. this.onAnimationEndObservable.clear();
  51848. }
  51849. }
  51850. return running;
  51851. };
  51852. return Animatable;
  51853. }());
  51854. BABYLON.Animatable = Animatable;
  51855. })(BABYLON || (BABYLON = {}));
  51856. //# sourceMappingURL=babylon.animatable.js.map
  51857. var BABYLON;
  51858. (function (BABYLON) {
  51859. var EasingFunction = /** @class */ (function () {
  51860. function EasingFunction() {
  51861. // Properties
  51862. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51863. }
  51864. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51865. get: function () {
  51866. return EasingFunction._EASINGMODE_EASEIN;
  51867. },
  51868. enumerable: true,
  51869. configurable: true
  51870. });
  51871. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51872. get: function () {
  51873. return EasingFunction._EASINGMODE_EASEOUT;
  51874. },
  51875. enumerable: true,
  51876. configurable: true
  51877. });
  51878. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51879. get: function () {
  51880. return EasingFunction._EASINGMODE_EASEINOUT;
  51881. },
  51882. enumerable: true,
  51883. configurable: true
  51884. });
  51885. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51886. var n = Math.min(Math.max(easingMode, 0), 2);
  51887. this._easingMode = n;
  51888. };
  51889. EasingFunction.prototype.getEasingMode = function () {
  51890. return this._easingMode;
  51891. };
  51892. EasingFunction.prototype.easeInCore = function (gradient) {
  51893. throw new Error('You must implement this method');
  51894. };
  51895. EasingFunction.prototype.ease = function (gradient) {
  51896. switch (this._easingMode) {
  51897. case EasingFunction.EASINGMODE_EASEIN:
  51898. return this.easeInCore(gradient);
  51899. case EasingFunction.EASINGMODE_EASEOUT:
  51900. return (1 - this.easeInCore(1 - gradient));
  51901. }
  51902. if (gradient >= 0.5) {
  51903. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51904. }
  51905. return (this.easeInCore(gradient * 2) * 0.5);
  51906. };
  51907. //Statics
  51908. EasingFunction._EASINGMODE_EASEIN = 0;
  51909. EasingFunction._EASINGMODE_EASEOUT = 1;
  51910. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51911. return EasingFunction;
  51912. }());
  51913. BABYLON.EasingFunction = EasingFunction;
  51914. var CircleEase = /** @class */ (function (_super) {
  51915. __extends(CircleEase, _super);
  51916. function CircleEase() {
  51917. return _super !== null && _super.apply(this, arguments) || this;
  51918. }
  51919. CircleEase.prototype.easeInCore = function (gradient) {
  51920. gradient = Math.max(0, Math.min(1, gradient));
  51921. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51922. };
  51923. return CircleEase;
  51924. }(EasingFunction));
  51925. BABYLON.CircleEase = CircleEase;
  51926. var BackEase = /** @class */ (function (_super) {
  51927. __extends(BackEase, _super);
  51928. function BackEase(amplitude) {
  51929. if (amplitude === void 0) { amplitude = 1; }
  51930. var _this = _super.call(this) || this;
  51931. _this.amplitude = amplitude;
  51932. return _this;
  51933. }
  51934. BackEase.prototype.easeInCore = function (gradient) {
  51935. var num = Math.max(0, this.amplitude);
  51936. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51937. };
  51938. return BackEase;
  51939. }(EasingFunction));
  51940. BABYLON.BackEase = BackEase;
  51941. var BounceEase = /** @class */ (function (_super) {
  51942. __extends(BounceEase, _super);
  51943. function BounceEase(bounces, bounciness) {
  51944. if (bounces === void 0) { bounces = 3; }
  51945. if (bounciness === void 0) { bounciness = 2; }
  51946. var _this = _super.call(this) || this;
  51947. _this.bounces = bounces;
  51948. _this.bounciness = bounciness;
  51949. return _this;
  51950. }
  51951. BounceEase.prototype.easeInCore = function (gradient) {
  51952. var y = Math.max(0.0, this.bounces);
  51953. var bounciness = this.bounciness;
  51954. if (bounciness <= 1.0) {
  51955. bounciness = 1.001;
  51956. }
  51957. var num9 = Math.pow(bounciness, y);
  51958. var num5 = 1.0 - bounciness;
  51959. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51960. var num15 = gradient * num4;
  51961. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51962. var num3 = Math.floor(num65);
  51963. var num13 = num3 + 1.0;
  51964. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51965. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51966. var num7 = (num8 + num12) * 0.5;
  51967. var num6 = gradient - num7;
  51968. var num2 = num7 - num8;
  51969. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51970. };
  51971. return BounceEase;
  51972. }(EasingFunction));
  51973. BABYLON.BounceEase = BounceEase;
  51974. var CubicEase = /** @class */ (function (_super) {
  51975. __extends(CubicEase, _super);
  51976. function CubicEase() {
  51977. return _super !== null && _super.apply(this, arguments) || this;
  51978. }
  51979. CubicEase.prototype.easeInCore = function (gradient) {
  51980. return (gradient * gradient * gradient);
  51981. };
  51982. return CubicEase;
  51983. }(EasingFunction));
  51984. BABYLON.CubicEase = CubicEase;
  51985. var ElasticEase = /** @class */ (function (_super) {
  51986. __extends(ElasticEase, _super);
  51987. function ElasticEase(oscillations, springiness) {
  51988. if (oscillations === void 0) { oscillations = 3; }
  51989. if (springiness === void 0) { springiness = 3; }
  51990. var _this = _super.call(this) || this;
  51991. _this.oscillations = oscillations;
  51992. _this.springiness = springiness;
  51993. return _this;
  51994. }
  51995. ElasticEase.prototype.easeInCore = function (gradient) {
  51996. var num2;
  51997. var num3 = Math.max(0.0, this.oscillations);
  51998. var num = Math.max(0.0, this.springiness);
  51999. if (num == 0) {
  52000. num2 = gradient;
  52001. }
  52002. else {
  52003. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52004. }
  52005. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52006. };
  52007. return ElasticEase;
  52008. }(EasingFunction));
  52009. BABYLON.ElasticEase = ElasticEase;
  52010. var ExponentialEase = /** @class */ (function (_super) {
  52011. __extends(ExponentialEase, _super);
  52012. function ExponentialEase(exponent) {
  52013. if (exponent === void 0) { exponent = 2; }
  52014. var _this = _super.call(this) || this;
  52015. _this.exponent = exponent;
  52016. return _this;
  52017. }
  52018. ExponentialEase.prototype.easeInCore = function (gradient) {
  52019. if (this.exponent <= 0) {
  52020. return gradient;
  52021. }
  52022. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52023. };
  52024. return ExponentialEase;
  52025. }(EasingFunction));
  52026. BABYLON.ExponentialEase = ExponentialEase;
  52027. var PowerEase = /** @class */ (function (_super) {
  52028. __extends(PowerEase, _super);
  52029. function PowerEase(power) {
  52030. if (power === void 0) { power = 2; }
  52031. var _this = _super.call(this) || this;
  52032. _this.power = power;
  52033. return _this;
  52034. }
  52035. PowerEase.prototype.easeInCore = function (gradient) {
  52036. var y = Math.max(0.0, this.power);
  52037. return Math.pow(gradient, y);
  52038. };
  52039. return PowerEase;
  52040. }(EasingFunction));
  52041. BABYLON.PowerEase = PowerEase;
  52042. var QuadraticEase = /** @class */ (function (_super) {
  52043. __extends(QuadraticEase, _super);
  52044. function QuadraticEase() {
  52045. return _super !== null && _super.apply(this, arguments) || this;
  52046. }
  52047. QuadraticEase.prototype.easeInCore = function (gradient) {
  52048. return (gradient * gradient);
  52049. };
  52050. return QuadraticEase;
  52051. }(EasingFunction));
  52052. BABYLON.QuadraticEase = QuadraticEase;
  52053. var QuarticEase = /** @class */ (function (_super) {
  52054. __extends(QuarticEase, _super);
  52055. function QuarticEase() {
  52056. return _super !== null && _super.apply(this, arguments) || this;
  52057. }
  52058. QuarticEase.prototype.easeInCore = function (gradient) {
  52059. return (gradient * gradient * gradient * gradient);
  52060. };
  52061. return QuarticEase;
  52062. }(EasingFunction));
  52063. BABYLON.QuarticEase = QuarticEase;
  52064. var QuinticEase = /** @class */ (function (_super) {
  52065. __extends(QuinticEase, _super);
  52066. function QuinticEase() {
  52067. return _super !== null && _super.apply(this, arguments) || this;
  52068. }
  52069. QuinticEase.prototype.easeInCore = function (gradient) {
  52070. return (gradient * gradient * gradient * gradient * gradient);
  52071. };
  52072. return QuinticEase;
  52073. }(EasingFunction));
  52074. BABYLON.QuinticEase = QuinticEase;
  52075. var SineEase = /** @class */ (function (_super) {
  52076. __extends(SineEase, _super);
  52077. function SineEase() {
  52078. return _super !== null && _super.apply(this, arguments) || this;
  52079. }
  52080. SineEase.prototype.easeInCore = function (gradient) {
  52081. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52082. };
  52083. return SineEase;
  52084. }(EasingFunction));
  52085. BABYLON.SineEase = SineEase;
  52086. var BezierCurveEase = /** @class */ (function (_super) {
  52087. __extends(BezierCurveEase, _super);
  52088. function BezierCurveEase(x1, y1, x2, y2) {
  52089. if (x1 === void 0) { x1 = 0; }
  52090. if (y1 === void 0) { y1 = 0; }
  52091. if (x2 === void 0) { x2 = 1; }
  52092. if (y2 === void 0) { y2 = 1; }
  52093. var _this = _super.call(this) || this;
  52094. _this.x1 = x1;
  52095. _this.y1 = y1;
  52096. _this.x2 = x2;
  52097. _this.y2 = y2;
  52098. return _this;
  52099. }
  52100. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52101. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52102. };
  52103. return BezierCurveEase;
  52104. }(EasingFunction));
  52105. BABYLON.BezierCurveEase = BezierCurveEase;
  52106. })(BABYLON || (BABYLON = {}));
  52107. //# sourceMappingURL=babylon.easing.js.map
  52108. var BABYLON;
  52109. (function (BABYLON) {
  52110. /**
  52111. * A Condition applied to an Action
  52112. */
  52113. var Condition = /** @class */ (function () {
  52114. /**
  52115. * Creates a new Condition
  52116. * @param actionManager the manager of the action the condition is applied to
  52117. */
  52118. function Condition(actionManager) {
  52119. this._actionManager = actionManager;
  52120. }
  52121. /**
  52122. * Check if the current condition is valid
  52123. * @returns a boolean
  52124. */
  52125. Condition.prototype.isValid = function () {
  52126. return true;
  52127. };
  52128. /**
  52129. * Internal only
  52130. * @hidden
  52131. */
  52132. Condition.prototype._getProperty = function (propertyPath) {
  52133. return this._actionManager._getProperty(propertyPath);
  52134. };
  52135. /**
  52136. * Internal only
  52137. * @hidden
  52138. */
  52139. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52140. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52141. };
  52142. /**
  52143. * Serialize placeholder for child classes
  52144. * @returns the serialized object
  52145. */
  52146. Condition.prototype.serialize = function () {
  52147. };
  52148. /**
  52149. * Internal only
  52150. * @hidden
  52151. */
  52152. Condition.prototype._serialize = function (serializedCondition) {
  52153. return {
  52154. type: 2,
  52155. children: [],
  52156. name: serializedCondition.name,
  52157. properties: serializedCondition.properties
  52158. };
  52159. };
  52160. return Condition;
  52161. }());
  52162. BABYLON.Condition = Condition;
  52163. /**
  52164. * Defines specific conditional operators as extensions of Condition
  52165. */
  52166. var ValueCondition = /** @class */ (function (_super) {
  52167. __extends(ValueCondition, _super);
  52168. /**
  52169. * Creates a new ValueCondition
  52170. * @param actionManager manager for the action the condition applies to
  52171. * @param target for the action
  52172. * @param propertyPath path to specify the property of the target the conditional operator uses
  52173. * @param value the value compared by the conditional operator against the current value of the property
  52174. * @param operator the conditional operator, default ValueCondition.IsEqual
  52175. */
  52176. function ValueCondition(actionManager, target,
  52177. /** path to specify the property of the target the conditional operator uses */
  52178. propertyPath,
  52179. /** the value compared by the conditional operator against the current value of the property */
  52180. value,
  52181. /** the conditional operator, default ValueCondition.IsEqual */
  52182. operator) {
  52183. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52184. var _this = _super.call(this, actionManager) || this;
  52185. _this.propertyPath = propertyPath;
  52186. _this.value = value;
  52187. _this.operator = operator;
  52188. _this._target = target;
  52189. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52190. _this._property = _this._getProperty(_this.propertyPath);
  52191. return _this;
  52192. }
  52193. Object.defineProperty(ValueCondition, "IsEqual", {
  52194. /**
  52195. * returns the number for IsEqual
  52196. */
  52197. get: function () {
  52198. return ValueCondition._IsEqual;
  52199. },
  52200. enumerable: true,
  52201. configurable: true
  52202. });
  52203. Object.defineProperty(ValueCondition, "IsDifferent", {
  52204. /**
  52205. * Returns the number for IsDifferent
  52206. */
  52207. get: function () {
  52208. return ValueCondition._IsDifferent;
  52209. },
  52210. enumerable: true,
  52211. configurable: true
  52212. });
  52213. Object.defineProperty(ValueCondition, "IsGreater", {
  52214. /**
  52215. * Returns the number for IsGreater
  52216. */
  52217. get: function () {
  52218. return ValueCondition._IsGreater;
  52219. },
  52220. enumerable: true,
  52221. configurable: true
  52222. });
  52223. Object.defineProperty(ValueCondition, "IsLesser", {
  52224. /**
  52225. * Returns the number for IsLesser
  52226. */
  52227. get: function () {
  52228. return ValueCondition._IsLesser;
  52229. },
  52230. enumerable: true,
  52231. configurable: true
  52232. });
  52233. /**
  52234. * Compares the given value with the property value for the specified conditional operator
  52235. * @returns the result of the comparison
  52236. */
  52237. ValueCondition.prototype.isValid = function () {
  52238. switch (this.operator) {
  52239. case ValueCondition.IsGreater:
  52240. return this._effectiveTarget[this._property] > this.value;
  52241. case ValueCondition.IsLesser:
  52242. return this._effectiveTarget[this._property] < this.value;
  52243. case ValueCondition.IsEqual:
  52244. case ValueCondition.IsDifferent:
  52245. var check;
  52246. if (this.value.equals) {
  52247. check = this.value.equals(this._effectiveTarget[this._property]);
  52248. }
  52249. else {
  52250. check = this.value === this._effectiveTarget[this._property];
  52251. }
  52252. return this.operator === ValueCondition.IsEqual ? check : !check;
  52253. }
  52254. return false;
  52255. };
  52256. /**
  52257. * Serialize the ValueCondition into a JSON compatible object
  52258. * @returns serialization object
  52259. */
  52260. ValueCondition.prototype.serialize = function () {
  52261. return this._serialize({
  52262. name: "ValueCondition",
  52263. properties: [
  52264. BABYLON.Action._GetTargetProperty(this._target),
  52265. { name: "propertyPath", value: this.propertyPath },
  52266. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52267. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52268. ]
  52269. });
  52270. };
  52271. /**
  52272. * Gets the name of the conditional operator for the ValueCondition
  52273. * @param operator the conditional operator
  52274. * @returns the name
  52275. */
  52276. ValueCondition.GetOperatorName = function (operator) {
  52277. switch (operator) {
  52278. case ValueCondition._IsEqual: return "IsEqual";
  52279. case ValueCondition._IsDifferent: return "IsDifferent";
  52280. case ValueCondition._IsGreater: return "IsGreater";
  52281. case ValueCondition._IsLesser: return "IsLesser";
  52282. default: return "";
  52283. }
  52284. };
  52285. /**
  52286. * Internal only
  52287. * @hidden
  52288. */
  52289. ValueCondition._IsEqual = 0;
  52290. /**
  52291. * Internal only
  52292. * @hidden
  52293. */
  52294. ValueCondition._IsDifferent = 1;
  52295. /**
  52296. * Internal only
  52297. * @hidden
  52298. */
  52299. ValueCondition._IsGreater = 2;
  52300. /**
  52301. * Internal only
  52302. * @hidden
  52303. */
  52304. ValueCondition._IsLesser = 3;
  52305. return ValueCondition;
  52306. }(Condition));
  52307. BABYLON.ValueCondition = ValueCondition;
  52308. /**
  52309. * Defines a predicate condition as an extension of Condition
  52310. */
  52311. var PredicateCondition = /** @class */ (function (_super) {
  52312. __extends(PredicateCondition, _super);
  52313. /**
  52314. * Creates a new PredicateCondition
  52315. * @param actionManager manager for the action the condition applies to
  52316. * @param predicate defines the predicate function used to validate the condition
  52317. */
  52318. function PredicateCondition(actionManager,
  52319. /** defines the predicate function used to validate the condition */
  52320. predicate) {
  52321. var _this = _super.call(this, actionManager) || this;
  52322. _this.predicate = predicate;
  52323. return _this;
  52324. }
  52325. /**
  52326. * @returns the validity of the predicate condition
  52327. */
  52328. PredicateCondition.prototype.isValid = function () {
  52329. return this.predicate();
  52330. };
  52331. return PredicateCondition;
  52332. }(Condition));
  52333. BABYLON.PredicateCondition = PredicateCondition;
  52334. /**
  52335. * Defines a state condition as an extension of Condition
  52336. */
  52337. var StateCondition = /** @class */ (function (_super) {
  52338. __extends(StateCondition, _super);
  52339. /**
  52340. * Creates a new StateCondition
  52341. * @param actionManager manager for the action the condition applies to
  52342. * @param target of the condition
  52343. * @param value to compare with target state
  52344. */
  52345. function StateCondition(actionManager, target, value) {
  52346. var _this = _super.call(this, actionManager) || this;
  52347. _this.value = value;
  52348. _this._target = target;
  52349. return _this;
  52350. }
  52351. /**
  52352. * @returns the validity of the state
  52353. */
  52354. StateCondition.prototype.isValid = function () {
  52355. return this._target.state === this.value;
  52356. };
  52357. /**
  52358. * Serialize the StateCondition into a JSON compatible object
  52359. * @returns serialization object
  52360. */
  52361. StateCondition.prototype.serialize = function () {
  52362. return this._serialize({
  52363. name: "StateCondition",
  52364. properties: [
  52365. BABYLON.Action._GetTargetProperty(this._target),
  52366. { name: "value", value: this.value }
  52367. ]
  52368. });
  52369. };
  52370. return StateCondition;
  52371. }(Condition));
  52372. BABYLON.StateCondition = StateCondition;
  52373. })(BABYLON || (BABYLON = {}));
  52374. //# sourceMappingURL=babylon.condition.js.map
  52375. var BABYLON;
  52376. (function (BABYLON) {
  52377. /**
  52378. * The action to be carried out following a trigger
  52379. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52380. */
  52381. var Action = /** @class */ (function () {
  52382. /**
  52383. * Creates a new Action
  52384. * @param triggerOptions the trigger, with or without parameters, for the action
  52385. * @param condition an optional determinant of action
  52386. */
  52387. function Action(
  52388. /** the trigger, with or without parameters, for the action */
  52389. triggerOptions, condition) {
  52390. this.triggerOptions = triggerOptions;
  52391. /**
  52392. * An event triggered prior to action being executed.
  52393. */
  52394. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52395. if (triggerOptions.parameter) {
  52396. this.trigger = triggerOptions.trigger;
  52397. this._triggerParameter = triggerOptions.parameter;
  52398. }
  52399. else if (triggerOptions.trigger) {
  52400. this.trigger = triggerOptions.trigger;
  52401. }
  52402. else {
  52403. this.trigger = triggerOptions;
  52404. }
  52405. this._nextActiveAction = this;
  52406. this._condition = condition;
  52407. }
  52408. /**
  52409. * Internal only
  52410. * @hidden
  52411. */
  52412. Action.prototype._prepare = function () {
  52413. };
  52414. /**
  52415. * Gets the trigger parameters
  52416. * @returns the trigger parameters
  52417. */
  52418. Action.prototype.getTriggerParameter = function () {
  52419. return this._triggerParameter;
  52420. };
  52421. /**
  52422. * Internal only - executes current action event
  52423. * @hidden
  52424. */
  52425. Action.prototype._executeCurrent = function (evt) {
  52426. if (this._nextActiveAction._condition) {
  52427. var condition = this._nextActiveAction._condition;
  52428. var currentRenderId = this._actionManager.getScene().getRenderId();
  52429. // We cache the current evaluation for the current frame
  52430. if (condition._evaluationId === currentRenderId) {
  52431. if (!condition._currentResult) {
  52432. return;
  52433. }
  52434. }
  52435. else {
  52436. condition._evaluationId = currentRenderId;
  52437. if (!condition.isValid()) {
  52438. condition._currentResult = false;
  52439. return;
  52440. }
  52441. condition._currentResult = true;
  52442. }
  52443. }
  52444. this.onBeforeExecuteObservable.notifyObservers(this);
  52445. this._nextActiveAction.execute(evt);
  52446. this.skipToNextActiveAction();
  52447. };
  52448. /**
  52449. * Execute placeholder for child classes
  52450. * @param evt optional action event
  52451. */
  52452. Action.prototype.execute = function (evt) {
  52453. };
  52454. /**
  52455. * Skips to next active action
  52456. */
  52457. Action.prototype.skipToNextActiveAction = function () {
  52458. if (this._nextActiveAction._child) {
  52459. if (!this._nextActiveAction._child._actionManager) {
  52460. this._nextActiveAction._child._actionManager = this._actionManager;
  52461. }
  52462. this._nextActiveAction = this._nextActiveAction._child;
  52463. }
  52464. else {
  52465. this._nextActiveAction = this;
  52466. }
  52467. };
  52468. /**
  52469. * Adds action to chain of actions, may be a DoNothingAction
  52470. * @param action defines the next action to execute
  52471. * @returns The action passed in
  52472. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52473. */
  52474. Action.prototype.then = function (action) {
  52475. this._child = action;
  52476. action._actionManager = this._actionManager;
  52477. action._prepare();
  52478. return action;
  52479. };
  52480. /**
  52481. * Internal only
  52482. * @hidden
  52483. */
  52484. Action.prototype._getProperty = function (propertyPath) {
  52485. return this._actionManager._getProperty(propertyPath);
  52486. };
  52487. /**
  52488. * Internal only
  52489. * @hidden
  52490. */
  52491. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52492. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52493. };
  52494. /**
  52495. * Serialize placeholder for child classes
  52496. * @param parent of child
  52497. * @returns the serialized object
  52498. */
  52499. Action.prototype.serialize = function (parent) {
  52500. };
  52501. /**
  52502. * Internal only called by serialize
  52503. * @hidden
  52504. */
  52505. Action.prototype._serialize = function (serializedAction, parent) {
  52506. var serializationObject = {
  52507. type: 1,
  52508. children: [],
  52509. name: serializedAction.name,
  52510. properties: serializedAction.properties || []
  52511. };
  52512. // Serialize child
  52513. if (this._child) {
  52514. this._child.serialize(serializationObject);
  52515. }
  52516. // Check if "this" has a condition
  52517. if (this._condition) {
  52518. var serializedCondition = this._condition.serialize();
  52519. serializedCondition.children.push(serializationObject);
  52520. if (parent) {
  52521. parent.children.push(serializedCondition);
  52522. }
  52523. return serializedCondition;
  52524. }
  52525. if (parent) {
  52526. parent.children.push(serializationObject);
  52527. }
  52528. return serializationObject;
  52529. };
  52530. /**
  52531. * Internal only
  52532. * @hidden
  52533. */
  52534. Action._SerializeValueAsString = function (value) {
  52535. if (typeof value === "number") {
  52536. return value.toString();
  52537. }
  52538. if (typeof value === "boolean") {
  52539. return value ? "true" : "false";
  52540. }
  52541. if (value instanceof BABYLON.Vector2) {
  52542. return value.x + ", " + value.y;
  52543. }
  52544. if (value instanceof BABYLON.Vector3) {
  52545. return value.x + ", " + value.y + ", " + value.z;
  52546. }
  52547. if (value instanceof BABYLON.Color3) {
  52548. return value.r + ", " + value.g + ", " + value.b;
  52549. }
  52550. if (value instanceof BABYLON.Color4) {
  52551. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52552. }
  52553. return value; // string
  52554. };
  52555. /**
  52556. * Internal only
  52557. * @hidden
  52558. */
  52559. Action._GetTargetProperty = function (target) {
  52560. return {
  52561. name: "target",
  52562. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52563. : target instanceof BABYLON.Light ? "LightProperties"
  52564. : target instanceof BABYLON.Camera ? "CameraProperties"
  52565. : "SceneProperties",
  52566. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52567. };
  52568. };
  52569. return Action;
  52570. }());
  52571. BABYLON.Action = Action;
  52572. })(BABYLON || (BABYLON = {}));
  52573. //# sourceMappingURL=babylon.action.js.map
  52574. var BABYLON;
  52575. (function (BABYLON) {
  52576. /**
  52577. * ActionEvent is the event being sent when an action is triggered.
  52578. */
  52579. var ActionEvent = /** @class */ (function () {
  52580. /**
  52581. * Creates a new ActionEvent
  52582. * @param source The mesh or sprite that triggered the action
  52583. * @param pointerX The X mouse cursor position at the time of the event
  52584. * @param pointerY The Y mouse cursor position at the time of the event
  52585. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52586. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52587. * @param additionalData additional data for the event
  52588. */
  52589. function ActionEvent(
  52590. /** The mesh or sprite that triggered the action */
  52591. source,
  52592. /** The X mouse cursor position at the time of the event */
  52593. pointerX,
  52594. /** The Y mouse cursor position at the time of the event */
  52595. pointerY,
  52596. /** The mesh that is currently pointed at (can be null) */
  52597. meshUnderPointer,
  52598. /** the original (browser) event that triggered the ActionEvent */
  52599. sourceEvent,
  52600. /** additional data for the event */
  52601. additionalData) {
  52602. this.source = source;
  52603. this.pointerX = pointerX;
  52604. this.pointerY = pointerY;
  52605. this.meshUnderPointer = meshUnderPointer;
  52606. this.sourceEvent = sourceEvent;
  52607. this.additionalData = additionalData;
  52608. }
  52609. /**
  52610. * Helper function to auto-create an ActionEvent from a source mesh.
  52611. * @param source The source mesh that triggered the event
  52612. * @param evt The original (browser) event
  52613. * @param additionalData additional data for the event
  52614. * @returns the new ActionEvent
  52615. */
  52616. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52617. var scene = source.getScene();
  52618. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52619. };
  52620. /**
  52621. * Helper function to auto-create an ActionEvent from a source sprite
  52622. * @param source The source sprite that triggered the event
  52623. * @param scene Scene associated with the sprite
  52624. * @param evt The original (browser) event
  52625. * @param additionalData additional data for the event
  52626. * @returns the new ActionEvent
  52627. */
  52628. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52629. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52630. };
  52631. /**
  52632. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52633. * @param scene the scene where the event occurred
  52634. * @param evt The original (browser) event
  52635. * @returns the new ActionEvent
  52636. */
  52637. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52638. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52639. };
  52640. /**
  52641. * Helper function to auto-create an ActionEvent from a primitive
  52642. * @param prim defines the target primitive
  52643. * @param pointerPos defines the pointer position
  52644. * @param evt The original (browser) event
  52645. * @param additionalData additional data for the event
  52646. * @returns the new ActionEvent
  52647. */
  52648. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52649. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52650. };
  52651. return ActionEvent;
  52652. }());
  52653. BABYLON.ActionEvent = ActionEvent;
  52654. /**
  52655. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52656. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52657. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52658. */
  52659. var ActionManager = /** @class */ (function () {
  52660. /**
  52661. * Creates a new action manager
  52662. * @param scene defines the hosting scene
  52663. */
  52664. function ActionManager(scene) {
  52665. // Members
  52666. /** Gets the list of actions */
  52667. this.actions = new Array();
  52668. /** Gets the cursor to use when hovering items */
  52669. this.hoverCursor = '';
  52670. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52671. scene.actionManagers.push(this);
  52672. }
  52673. Object.defineProperty(ActionManager, "NothingTrigger", {
  52674. /**
  52675. * Nothing
  52676. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52677. */
  52678. get: function () {
  52679. return ActionManager._NothingTrigger;
  52680. },
  52681. enumerable: true,
  52682. configurable: true
  52683. });
  52684. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52685. /**
  52686. * On pick
  52687. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52688. */
  52689. get: function () {
  52690. return ActionManager._OnPickTrigger;
  52691. },
  52692. enumerable: true,
  52693. configurable: true
  52694. });
  52695. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52696. /**
  52697. * On left pick
  52698. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52699. */
  52700. get: function () {
  52701. return ActionManager._OnLeftPickTrigger;
  52702. },
  52703. enumerable: true,
  52704. configurable: true
  52705. });
  52706. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52707. /**
  52708. * On right pick
  52709. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52710. */
  52711. get: function () {
  52712. return ActionManager._OnRightPickTrigger;
  52713. },
  52714. enumerable: true,
  52715. configurable: true
  52716. });
  52717. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52718. /**
  52719. * On center pick
  52720. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52721. */
  52722. get: function () {
  52723. return ActionManager._OnCenterPickTrigger;
  52724. },
  52725. enumerable: true,
  52726. configurable: true
  52727. });
  52728. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52729. /**
  52730. * On pick down
  52731. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52732. */
  52733. get: function () {
  52734. return ActionManager._OnPickDownTrigger;
  52735. },
  52736. enumerable: true,
  52737. configurable: true
  52738. });
  52739. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52740. /**
  52741. * On double pick
  52742. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52743. */
  52744. get: function () {
  52745. return ActionManager._OnDoublePickTrigger;
  52746. },
  52747. enumerable: true,
  52748. configurable: true
  52749. });
  52750. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52751. /**
  52752. * On pick up
  52753. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52754. */
  52755. get: function () {
  52756. return ActionManager._OnPickUpTrigger;
  52757. },
  52758. enumerable: true,
  52759. configurable: true
  52760. });
  52761. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52762. /**
  52763. * On pick out.
  52764. * This trigger will only be raised if you also declared a OnPickDown
  52765. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52766. */
  52767. get: function () {
  52768. return ActionManager._OnPickOutTrigger;
  52769. },
  52770. enumerable: true,
  52771. configurable: true
  52772. });
  52773. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52774. /**
  52775. * On long press
  52776. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52777. */
  52778. get: function () {
  52779. return ActionManager._OnLongPressTrigger;
  52780. },
  52781. enumerable: true,
  52782. configurable: true
  52783. });
  52784. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52785. /**
  52786. * On pointer over
  52787. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52788. */
  52789. get: function () {
  52790. return ActionManager._OnPointerOverTrigger;
  52791. },
  52792. enumerable: true,
  52793. configurable: true
  52794. });
  52795. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52796. /**
  52797. * On pointer out
  52798. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52799. */
  52800. get: function () {
  52801. return ActionManager._OnPointerOutTrigger;
  52802. },
  52803. enumerable: true,
  52804. configurable: true
  52805. });
  52806. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52807. /**
  52808. * On every frame
  52809. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52810. */
  52811. get: function () {
  52812. return ActionManager._OnEveryFrameTrigger;
  52813. },
  52814. enumerable: true,
  52815. configurable: true
  52816. });
  52817. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52818. /**
  52819. * On intersection enter
  52820. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52821. */
  52822. get: function () {
  52823. return ActionManager._OnIntersectionEnterTrigger;
  52824. },
  52825. enumerable: true,
  52826. configurable: true
  52827. });
  52828. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52829. /**
  52830. * On intersection exit
  52831. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52832. */
  52833. get: function () {
  52834. return ActionManager._OnIntersectionExitTrigger;
  52835. },
  52836. enumerable: true,
  52837. configurable: true
  52838. });
  52839. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52840. /**
  52841. * On key down
  52842. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52843. */
  52844. get: function () {
  52845. return ActionManager._OnKeyDownTrigger;
  52846. },
  52847. enumerable: true,
  52848. configurable: true
  52849. });
  52850. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52851. /**
  52852. * On key up
  52853. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52854. */
  52855. get: function () {
  52856. return ActionManager._OnKeyUpTrigger;
  52857. },
  52858. enumerable: true,
  52859. configurable: true
  52860. });
  52861. // Methods
  52862. /**
  52863. * Releases all associated resources
  52864. */
  52865. ActionManager.prototype.dispose = function () {
  52866. var index = this._scene.actionManagers.indexOf(this);
  52867. for (var i = 0; i < this.actions.length; i++) {
  52868. var action = this.actions[i];
  52869. ActionManager.Triggers[action.trigger]--;
  52870. if (ActionManager.Triggers[action.trigger] === 0) {
  52871. delete ActionManager.Triggers[action.trigger];
  52872. }
  52873. }
  52874. if (index > -1) {
  52875. this._scene.actionManagers.splice(index, 1);
  52876. }
  52877. };
  52878. /**
  52879. * Gets hosting scene
  52880. * @returns the hosting scene
  52881. */
  52882. ActionManager.prototype.getScene = function () {
  52883. return this._scene;
  52884. };
  52885. /**
  52886. * Does this action manager handles actions of any of the given triggers
  52887. * @param triggers defines the triggers to be tested
  52888. * @return a boolean indicating whether one (or more) of the triggers is handled
  52889. */
  52890. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52891. for (var index = 0; index < this.actions.length; index++) {
  52892. var action = this.actions[index];
  52893. if (triggers.indexOf(action.trigger) > -1) {
  52894. return true;
  52895. }
  52896. }
  52897. return false;
  52898. };
  52899. /**
  52900. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  52901. * speed.
  52902. * @param triggerA defines the trigger to be tested
  52903. * @param triggerB defines the trigger to be tested
  52904. * @return a boolean indicating whether one (or more) of the triggers is handled
  52905. */
  52906. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  52907. for (var index = 0; index < this.actions.length; index++) {
  52908. var action = this.actions[index];
  52909. if (triggerA == action.trigger || triggerB == action.trigger) {
  52910. return true;
  52911. }
  52912. }
  52913. return false;
  52914. };
  52915. /**
  52916. * Does this action manager handles actions of a given trigger
  52917. * @param trigger defines the trigger to be tested
  52918. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52919. * @return whether the trigger is handled
  52920. */
  52921. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52922. for (var index = 0; index < this.actions.length; index++) {
  52923. var action = this.actions[index];
  52924. if (action.trigger === trigger) {
  52925. if (parameterPredicate) {
  52926. if (parameterPredicate(action.getTriggerParameter())) {
  52927. return true;
  52928. }
  52929. }
  52930. else {
  52931. return true;
  52932. }
  52933. }
  52934. }
  52935. return false;
  52936. };
  52937. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52938. /**
  52939. * Does this action manager has pointer triggers
  52940. */
  52941. get: function () {
  52942. for (var index = 0; index < this.actions.length; index++) {
  52943. var action = this.actions[index];
  52944. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52945. return true;
  52946. }
  52947. }
  52948. return false;
  52949. },
  52950. enumerable: true,
  52951. configurable: true
  52952. });
  52953. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52954. /**
  52955. * Does this action manager has pick triggers
  52956. */
  52957. get: function () {
  52958. for (var index = 0; index < this.actions.length; index++) {
  52959. var action = this.actions[index];
  52960. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52961. return true;
  52962. }
  52963. }
  52964. return false;
  52965. },
  52966. enumerable: true,
  52967. configurable: true
  52968. });
  52969. Object.defineProperty(ActionManager, "HasTriggers", {
  52970. /**
  52971. * Does exist one action manager with at least one trigger
  52972. **/
  52973. get: function () {
  52974. for (var t in ActionManager.Triggers) {
  52975. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52976. return true;
  52977. }
  52978. }
  52979. return false;
  52980. },
  52981. enumerable: true,
  52982. configurable: true
  52983. });
  52984. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52985. /**
  52986. * Does exist one action manager with at least one pick trigger
  52987. **/
  52988. get: function () {
  52989. for (var t in ActionManager.Triggers) {
  52990. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52991. var t_int = parseInt(t);
  52992. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52993. return true;
  52994. }
  52995. }
  52996. }
  52997. return false;
  52998. },
  52999. enumerable: true,
  53000. configurable: true
  53001. });
  53002. /**
  53003. * Does exist one action manager that handles actions of a given trigger
  53004. * @param trigger defines the trigger to be tested
  53005. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53006. **/
  53007. ActionManager.HasSpecificTrigger = function (trigger) {
  53008. for (var t in ActionManager.Triggers) {
  53009. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53010. var t_int = parseInt(t);
  53011. if (t_int === trigger) {
  53012. return true;
  53013. }
  53014. }
  53015. }
  53016. return false;
  53017. };
  53018. /**
  53019. * Registers an action to this action manager
  53020. * @param action defines the action to be registered
  53021. * @return the action amended (prepared) after registration
  53022. */
  53023. ActionManager.prototype.registerAction = function (action) {
  53024. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53025. if (this.getScene().actionManager !== this) {
  53026. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53027. return null;
  53028. }
  53029. }
  53030. this.actions.push(action);
  53031. if (ActionManager.Triggers[action.trigger]) {
  53032. ActionManager.Triggers[action.trigger]++;
  53033. }
  53034. else {
  53035. ActionManager.Triggers[action.trigger] = 1;
  53036. }
  53037. action._actionManager = this;
  53038. action._prepare();
  53039. return action;
  53040. };
  53041. /**
  53042. * Unregisters an action to this action manager
  53043. * @param action defines the action to be unregistered
  53044. * @return a boolean indicating whether the action has been unregistered
  53045. */
  53046. ActionManager.prototype.unregisterAction = function (action) {
  53047. var index = this.actions.indexOf(action);
  53048. if (index !== -1) {
  53049. this.actions.splice(index, 1);
  53050. ActionManager.Triggers[action.trigger] -= 1;
  53051. if (ActionManager.Triggers[action.trigger] === 0) {
  53052. delete ActionManager.Triggers[action.trigger];
  53053. }
  53054. delete action._actionManager;
  53055. return true;
  53056. }
  53057. return false;
  53058. };
  53059. /**
  53060. * Process a specific trigger
  53061. * @param trigger defines the trigger to process
  53062. * @param evt defines the event details to be processed
  53063. */
  53064. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53065. for (var index = 0; index < this.actions.length; index++) {
  53066. var action = this.actions[index];
  53067. if (action.trigger === trigger) {
  53068. if (evt) {
  53069. if (trigger === ActionManager.OnKeyUpTrigger
  53070. || trigger === ActionManager.OnKeyDownTrigger) {
  53071. var parameter = action.getTriggerParameter();
  53072. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53073. if (!parameter.toLowerCase) {
  53074. continue;
  53075. }
  53076. var lowerCase = parameter.toLowerCase();
  53077. if (lowerCase !== evt.sourceEvent.key) {
  53078. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53079. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53080. if (actualkey !== lowerCase) {
  53081. continue;
  53082. }
  53083. }
  53084. }
  53085. }
  53086. }
  53087. action._executeCurrent(evt);
  53088. }
  53089. }
  53090. };
  53091. /** @hidden */
  53092. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53093. var properties = propertyPath.split(".");
  53094. for (var index = 0; index < properties.length - 1; index++) {
  53095. target = target[properties[index]];
  53096. }
  53097. return target;
  53098. };
  53099. /** @hidden */
  53100. ActionManager.prototype._getProperty = function (propertyPath) {
  53101. var properties = propertyPath.split(".");
  53102. return properties[properties.length - 1];
  53103. };
  53104. /**
  53105. * Serialize this manager to a JSON object
  53106. * @param name defines the property name to store this manager
  53107. * @returns a JSON representation of this manager
  53108. */
  53109. ActionManager.prototype.serialize = function (name) {
  53110. var root = {
  53111. children: new Array(),
  53112. name: name,
  53113. type: 3,
  53114. properties: new Array() // Empty for root but required
  53115. };
  53116. for (var i = 0; i < this.actions.length; i++) {
  53117. var triggerObject = {
  53118. type: 0,
  53119. children: new Array(),
  53120. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53121. properties: new Array()
  53122. };
  53123. var triggerOptions = this.actions[i].triggerOptions;
  53124. if (triggerOptions && typeof triggerOptions !== "number") {
  53125. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53126. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53127. }
  53128. else {
  53129. var parameter = {};
  53130. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53131. if (triggerOptions.parameter.mesh) {
  53132. parameter._meshId = triggerOptions.parameter.mesh.id;
  53133. }
  53134. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53135. }
  53136. }
  53137. // Serialize child action, recursively
  53138. this.actions[i].serialize(triggerObject);
  53139. // Add serialized trigger
  53140. root.children.push(triggerObject);
  53141. }
  53142. return root;
  53143. };
  53144. /**
  53145. * Creates a new ActionManager from a JSON data
  53146. * @param parsedActions defines the JSON data to read from
  53147. * @param object defines the hosting mesh
  53148. * @param scene defines the hosting scene
  53149. */
  53150. ActionManager.Parse = function (parsedActions, object, scene) {
  53151. var actionManager = new ActionManager(scene);
  53152. if (object === null)
  53153. scene.actionManager = actionManager;
  53154. else
  53155. object.actionManager = actionManager;
  53156. // instanciate a new object
  53157. var instanciate = function (name, params) {
  53158. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53159. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53160. newInstance.constructor.apply(newInstance, params);
  53161. return newInstance;
  53162. };
  53163. var parseParameter = function (name, value, target, propertyPath) {
  53164. if (propertyPath === null) {
  53165. // String, boolean or float
  53166. var floatValue = parseFloat(value);
  53167. if (value === "true" || value === "false")
  53168. return value === "true";
  53169. else
  53170. return isNaN(floatValue) ? value : floatValue;
  53171. }
  53172. var effectiveTarget = propertyPath.split(".");
  53173. var values = value.split(",");
  53174. // Get effective Target
  53175. for (var i = 0; i < effectiveTarget.length; i++) {
  53176. target = target[effectiveTarget[i]];
  53177. }
  53178. // Return appropriate value with its type
  53179. if (typeof (target) === "boolean")
  53180. return values[0] === "true";
  53181. if (typeof (target) === "string")
  53182. return values[0];
  53183. // Parameters with multiple values such as Vector3 etc.
  53184. var split = new Array();
  53185. for (var i = 0; i < values.length; i++)
  53186. split.push(parseFloat(values[i]));
  53187. if (target instanceof BABYLON.Vector3)
  53188. return BABYLON.Vector3.FromArray(split);
  53189. if (target instanceof BABYLON.Vector4)
  53190. return BABYLON.Vector4.FromArray(split);
  53191. if (target instanceof BABYLON.Color3)
  53192. return BABYLON.Color3.FromArray(split);
  53193. if (target instanceof BABYLON.Color4)
  53194. return BABYLON.Color4.FromArray(split);
  53195. return parseFloat(values[0]);
  53196. };
  53197. // traverse graph per trigger
  53198. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53199. if (combineArray === void 0) { combineArray = null; }
  53200. if (parsedAction.detached)
  53201. return;
  53202. var parameters = new Array();
  53203. var target = null;
  53204. var propertyPath = null;
  53205. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53206. // Parameters
  53207. if (parsedAction.type === 2)
  53208. parameters.push(actionManager);
  53209. else
  53210. parameters.push(trigger);
  53211. if (combine) {
  53212. var actions = new Array();
  53213. for (var j = 0; j < parsedAction.combine.length; j++) {
  53214. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53215. }
  53216. parameters.push(actions);
  53217. }
  53218. else {
  53219. for (var i = 0; i < parsedAction.properties.length; i++) {
  53220. var value = parsedAction.properties[i].value;
  53221. var name = parsedAction.properties[i].name;
  53222. var targetType = parsedAction.properties[i].targetType;
  53223. if (name === "target")
  53224. if (targetType !== null && targetType === "SceneProperties")
  53225. value = target = scene;
  53226. else
  53227. value = target = scene.getNodeByName(value);
  53228. else if (name === "parent")
  53229. value = scene.getNodeByName(value);
  53230. else if (name === "sound")
  53231. value = scene.getSoundByName(value);
  53232. else if (name !== "propertyPath") {
  53233. if (parsedAction.type === 2 && name === "operator")
  53234. value = BABYLON.ValueCondition[value];
  53235. else
  53236. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53237. }
  53238. else {
  53239. propertyPath = value;
  53240. }
  53241. parameters.push(value);
  53242. }
  53243. }
  53244. if (combineArray === null) {
  53245. parameters.push(condition);
  53246. }
  53247. else {
  53248. parameters.push(null);
  53249. }
  53250. // If interpolate value action
  53251. if (parsedAction.name === "InterpolateValueAction") {
  53252. var param = parameters[parameters.length - 2];
  53253. parameters[parameters.length - 1] = param;
  53254. parameters[parameters.length - 2] = condition;
  53255. }
  53256. // Action or condition(s) and not CombineAction
  53257. var newAction = instanciate(parsedAction.name, parameters);
  53258. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53259. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53260. if (action)
  53261. action.then(nothing);
  53262. else
  53263. actionManager.registerAction(nothing);
  53264. action = nothing;
  53265. }
  53266. if (combineArray === null) {
  53267. if (newAction instanceof BABYLON.Condition) {
  53268. condition = newAction;
  53269. newAction = action;
  53270. }
  53271. else {
  53272. condition = null;
  53273. if (action)
  53274. action.then(newAction);
  53275. else
  53276. actionManager.registerAction(newAction);
  53277. }
  53278. }
  53279. else {
  53280. combineArray.push(newAction);
  53281. }
  53282. for (var i = 0; i < parsedAction.children.length; i++)
  53283. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53284. };
  53285. // triggers
  53286. for (var i = 0; i < parsedActions.children.length; i++) {
  53287. var triggerParams;
  53288. var trigger = parsedActions.children[i];
  53289. if (trigger.properties.length > 0) {
  53290. var param = trigger.properties[0].value;
  53291. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53292. if (value._meshId) {
  53293. value.mesh = scene.getMeshByID(value._meshId);
  53294. }
  53295. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53296. }
  53297. else
  53298. triggerParams = ActionManager[trigger.name];
  53299. for (var j = 0; j < trigger.children.length; j++) {
  53300. if (!trigger.detached)
  53301. traverse(trigger.children[j], triggerParams, null, null);
  53302. }
  53303. }
  53304. };
  53305. /**
  53306. * Get a trigger name by index
  53307. * @param trigger defines the trigger index
  53308. * @returns a trigger name
  53309. */
  53310. ActionManager.GetTriggerName = function (trigger) {
  53311. switch (trigger) {
  53312. case 0: return "NothingTrigger";
  53313. case 1: return "OnPickTrigger";
  53314. case 2: return "OnLeftPickTrigger";
  53315. case 3: return "OnRightPickTrigger";
  53316. case 4: return "OnCenterPickTrigger";
  53317. case 5: return "OnPickDownTrigger";
  53318. case 6: return "OnPickUpTrigger";
  53319. case 7: return "OnLongPressTrigger";
  53320. case 8: return "OnPointerOverTrigger";
  53321. case 9: return "OnPointerOutTrigger";
  53322. case 10: return "OnEveryFrameTrigger";
  53323. case 11: return "OnIntersectionEnterTrigger";
  53324. case 12: return "OnIntersectionExitTrigger";
  53325. case 13: return "OnKeyDownTrigger";
  53326. case 14: return "OnKeyUpTrigger";
  53327. case 15: return "OnPickOutTrigger";
  53328. default: return "";
  53329. }
  53330. };
  53331. // Statics
  53332. ActionManager._NothingTrigger = 0;
  53333. ActionManager._OnPickTrigger = 1;
  53334. ActionManager._OnLeftPickTrigger = 2;
  53335. ActionManager._OnRightPickTrigger = 3;
  53336. ActionManager._OnCenterPickTrigger = 4;
  53337. ActionManager._OnPickDownTrigger = 5;
  53338. ActionManager._OnDoublePickTrigger = 6;
  53339. ActionManager._OnPickUpTrigger = 7;
  53340. ActionManager._OnLongPressTrigger = 8;
  53341. ActionManager._OnPointerOverTrigger = 9;
  53342. ActionManager._OnPointerOutTrigger = 10;
  53343. ActionManager._OnEveryFrameTrigger = 11;
  53344. ActionManager._OnIntersectionEnterTrigger = 12;
  53345. ActionManager._OnIntersectionExitTrigger = 13;
  53346. ActionManager._OnKeyDownTrigger = 14;
  53347. ActionManager._OnKeyUpTrigger = 15;
  53348. ActionManager._OnPickOutTrigger = 16;
  53349. /** Gets the list of active triggers */
  53350. ActionManager.Triggers = {};
  53351. return ActionManager;
  53352. }());
  53353. BABYLON.ActionManager = ActionManager;
  53354. })(BABYLON || (BABYLON = {}));
  53355. //# sourceMappingURL=babylon.actionManager.js.map
  53356. var BABYLON;
  53357. (function (BABYLON) {
  53358. var InterpolateValueAction = /** @class */ (function (_super) {
  53359. __extends(InterpolateValueAction, _super);
  53360. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53361. if (duration === void 0) { duration = 1000; }
  53362. var _this = _super.call(this, triggerOptions, condition) || this;
  53363. _this.propertyPath = propertyPath;
  53364. _this.value = value;
  53365. _this.duration = duration;
  53366. _this.stopOtherAnimations = stopOtherAnimations;
  53367. _this.onInterpolationDone = onInterpolationDone;
  53368. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53369. _this._target = _this._effectiveTarget = target;
  53370. return _this;
  53371. }
  53372. /** @hidden */
  53373. InterpolateValueAction.prototype._prepare = function () {
  53374. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53375. this._property = this._getProperty(this.propertyPath);
  53376. };
  53377. InterpolateValueAction.prototype.execute = function () {
  53378. var _this = this;
  53379. var scene = this._actionManager.getScene();
  53380. var keys = [
  53381. {
  53382. frame: 0,
  53383. value: this._effectiveTarget[this._property]
  53384. }, {
  53385. frame: 100,
  53386. value: this.value
  53387. }
  53388. ];
  53389. var dataType;
  53390. if (typeof this.value === "number") {
  53391. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53392. }
  53393. else if (this.value instanceof BABYLON.Color3) {
  53394. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53395. }
  53396. else if (this.value instanceof BABYLON.Vector3) {
  53397. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53398. }
  53399. else if (this.value instanceof BABYLON.Matrix) {
  53400. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53401. }
  53402. else if (this.value instanceof BABYLON.Quaternion) {
  53403. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53404. }
  53405. else {
  53406. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53407. return;
  53408. }
  53409. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53410. animation.setKeys(keys);
  53411. if (this.stopOtherAnimations) {
  53412. scene.stopAnimation(this._effectiveTarget);
  53413. }
  53414. var wrapper = function () {
  53415. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53416. if (_this.onInterpolationDone) {
  53417. _this.onInterpolationDone();
  53418. }
  53419. };
  53420. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53421. };
  53422. InterpolateValueAction.prototype.serialize = function (parent) {
  53423. return _super.prototype._serialize.call(this, {
  53424. name: "InterpolateValueAction",
  53425. properties: [
  53426. BABYLON.Action._GetTargetProperty(this._target),
  53427. { name: "propertyPath", value: this.propertyPath },
  53428. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53429. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53430. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53431. ]
  53432. }, parent);
  53433. };
  53434. return InterpolateValueAction;
  53435. }(BABYLON.Action));
  53436. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53437. })(BABYLON || (BABYLON = {}));
  53438. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53439. var BABYLON;
  53440. (function (BABYLON) {
  53441. var SwitchBooleanAction = /** @class */ (function (_super) {
  53442. __extends(SwitchBooleanAction, _super);
  53443. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53444. var _this = _super.call(this, triggerOptions, condition) || this;
  53445. _this.propertyPath = propertyPath;
  53446. _this._target = _this._effectiveTarget = target;
  53447. return _this;
  53448. }
  53449. /** @hidden */
  53450. SwitchBooleanAction.prototype._prepare = function () {
  53451. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53452. this._property = this._getProperty(this.propertyPath);
  53453. };
  53454. SwitchBooleanAction.prototype.execute = function () {
  53455. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53456. };
  53457. SwitchBooleanAction.prototype.serialize = function (parent) {
  53458. return _super.prototype._serialize.call(this, {
  53459. name: "SwitchBooleanAction",
  53460. properties: [
  53461. BABYLON.Action._GetTargetProperty(this._target),
  53462. { name: "propertyPath", value: this.propertyPath }
  53463. ]
  53464. }, parent);
  53465. };
  53466. return SwitchBooleanAction;
  53467. }(BABYLON.Action));
  53468. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53469. var SetStateAction = /** @class */ (function (_super) {
  53470. __extends(SetStateAction, _super);
  53471. function SetStateAction(triggerOptions, target, value, condition) {
  53472. var _this = _super.call(this, triggerOptions, condition) || this;
  53473. _this.value = value;
  53474. _this._target = target;
  53475. return _this;
  53476. }
  53477. SetStateAction.prototype.execute = function () {
  53478. this._target.state = this.value;
  53479. };
  53480. SetStateAction.prototype.serialize = function (parent) {
  53481. return _super.prototype._serialize.call(this, {
  53482. name: "SetStateAction",
  53483. properties: [
  53484. BABYLON.Action._GetTargetProperty(this._target),
  53485. { name: "value", value: this.value }
  53486. ]
  53487. }, parent);
  53488. };
  53489. return SetStateAction;
  53490. }(BABYLON.Action));
  53491. BABYLON.SetStateAction = SetStateAction;
  53492. var SetValueAction = /** @class */ (function (_super) {
  53493. __extends(SetValueAction, _super);
  53494. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53495. var _this = _super.call(this, triggerOptions, condition) || this;
  53496. _this.propertyPath = propertyPath;
  53497. _this.value = value;
  53498. _this._target = _this._effectiveTarget = target;
  53499. return _this;
  53500. }
  53501. /** @hidden */
  53502. SetValueAction.prototype._prepare = function () {
  53503. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53504. this._property = this._getProperty(this.propertyPath);
  53505. };
  53506. SetValueAction.prototype.execute = function () {
  53507. this._effectiveTarget[this._property] = this.value;
  53508. if (this._target.markAsDirty) {
  53509. this._target.markAsDirty(this._property);
  53510. }
  53511. };
  53512. SetValueAction.prototype.serialize = function (parent) {
  53513. return _super.prototype._serialize.call(this, {
  53514. name: "SetValueAction",
  53515. properties: [
  53516. BABYLON.Action._GetTargetProperty(this._target),
  53517. { name: "propertyPath", value: this.propertyPath },
  53518. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53519. ]
  53520. }, parent);
  53521. };
  53522. return SetValueAction;
  53523. }(BABYLON.Action));
  53524. BABYLON.SetValueAction = SetValueAction;
  53525. var IncrementValueAction = /** @class */ (function (_super) {
  53526. __extends(IncrementValueAction, _super);
  53527. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53528. var _this = _super.call(this, triggerOptions, condition) || this;
  53529. _this.propertyPath = propertyPath;
  53530. _this.value = value;
  53531. _this._target = _this._effectiveTarget = target;
  53532. return _this;
  53533. }
  53534. /** @hidden */
  53535. IncrementValueAction.prototype._prepare = function () {
  53536. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53537. this._property = this._getProperty(this.propertyPath);
  53538. if (typeof this._effectiveTarget[this._property] !== "number") {
  53539. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53540. }
  53541. };
  53542. IncrementValueAction.prototype.execute = function () {
  53543. this._effectiveTarget[this._property] += this.value;
  53544. if (this._target.markAsDirty) {
  53545. this._target.markAsDirty(this._property);
  53546. }
  53547. };
  53548. IncrementValueAction.prototype.serialize = function (parent) {
  53549. return _super.prototype._serialize.call(this, {
  53550. name: "IncrementValueAction",
  53551. properties: [
  53552. BABYLON.Action._GetTargetProperty(this._target),
  53553. { name: "propertyPath", value: this.propertyPath },
  53554. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53555. ]
  53556. }, parent);
  53557. };
  53558. return IncrementValueAction;
  53559. }(BABYLON.Action));
  53560. BABYLON.IncrementValueAction = IncrementValueAction;
  53561. var PlayAnimationAction = /** @class */ (function (_super) {
  53562. __extends(PlayAnimationAction, _super);
  53563. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53564. var _this = _super.call(this, triggerOptions, condition) || this;
  53565. _this.from = from;
  53566. _this.to = to;
  53567. _this.loop = loop;
  53568. _this._target = target;
  53569. return _this;
  53570. }
  53571. /** @hidden */
  53572. PlayAnimationAction.prototype._prepare = function () {
  53573. };
  53574. PlayAnimationAction.prototype.execute = function () {
  53575. var scene = this._actionManager.getScene();
  53576. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53577. };
  53578. PlayAnimationAction.prototype.serialize = function (parent) {
  53579. return _super.prototype._serialize.call(this, {
  53580. name: "PlayAnimationAction",
  53581. properties: [
  53582. BABYLON.Action._GetTargetProperty(this._target),
  53583. { name: "from", value: String(this.from) },
  53584. { name: "to", value: String(this.to) },
  53585. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53586. ]
  53587. }, parent);
  53588. };
  53589. return PlayAnimationAction;
  53590. }(BABYLON.Action));
  53591. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53592. var StopAnimationAction = /** @class */ (function (_super) {
  53593. __extends(StopAnimationAction, _super);
  53594. function StopAnimationAction(triggerOptions, target, condition) {
  53595. var _this = _super.call(this, triggerOptions, condition) || this;
  53596. _this._target = target;
  53597. return _this;
  53598. }
  53599. /** @hidden */
  53600. StopAnimationAction.prototype._prepare = function () {
  53601. };
  53602. StopAnimationAction.prototype.execute = function () {
  53603. var scene = this._actionManager.getScene();
  53604. scene.stopAnimation(this._target);
  53605. };
  53606. StopAnimationAction.prototype.serialize = function (parent) {
  53607. return _super.prototype._serialize.call(this, {
  53608. name: "StopAnimationAction",
  53609. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53610. }, parent);
  53611. };
  53612. return StopAnimationAction;
  53613. }(BABYLON.Action));
  53614. BABYLON.StopAnimationAction = StopAnimationAction;
  53615. var DoNothingAction = /** @class */ (function (_super) {
  53616. __extends(DoNothingAction, _super);
  53617. function DoNothingAction(triggerOptions, condition) {
  53618. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53619. return _super.call(this, triggerOptions, condition) || this;
  53620. }
  53621. DoNothingAction.prototype.execute = function () {
  53622. };
  53623. DoNothingAction.prototype.serialize = function (parent) {
  53624. return _super.prototype._serialize.call(this, {
  53625. name: "DoNothingAction",
  53626. properties: []
  53627. }, parent);
  53628. };
  53629. return DoNothingAction;
  53630. }(BABYLON.Action));
  53631. BABYLON.DoNothingAction = DoNothingAction;
  53632. var CombineAction = /** @class */ (function (_super) {
  53633. __extends(CombineAction, _super);
  53634. function CombineAction(triggerOptions, children, condition) {
  53635. var _this = _super.call(this, triggerOptions, condition) || this;
  53636. _this.children = children;
  53637. return _this;
  53638. }
  53639. /** @hidden */
  53640. CombineAction.prototype._prepare = function () {
  53641. for (var index = 0; index < this.children.length; index++) {
  53642. this.children[index]._actionManager = this._actionManager;
  53643. this.children[index]._prepare();
  53644. }
  53645. };
  53646. CombineAction.prototype.execute = function (evt) {
  53647. for (var index = 0; index < this.children.length; index++) {
  53648. this.children[index].execute(evt);
  53649. }
  53650. };
  53651. CombineAction.prototype.serialize = function (parent) {
  53652. var serializationObject = _super.prototype._serialize.call(this, {
  53653. name: "CombineAction",
  53654. properties: [],
  53655. combine: []
  53656. }, parent);
  53657. for (var i = 0; i < this.children.length; i++) {
  53658. serializationObject.combine.push(this.children[i].serialize(null));
  53659. }
  53660. return serializationObject;
  53661. };
  53662. return CombineAction;
  53663. }(BABYLON.Action));
  53664. BABYLON.CombineAction = CombineAction;
  53665. var ExecuteCodeAction = /** @class */ (function (_super) {
  53666. __extends(ExecuteCodeAction, _super);
  53667. function ExecuteCodeAction(triggerOptions, func, condition) {
  53668. var _this = _super.call(this, triggerOptions, condition) || this;
  53669. _this.func = func;
  53670. return _this;
  53671. }
  53672. ExecuteCodeAction.prototype.execute = function (evt) {
  53673. this.func(evt);
  53674. };
  53675. return ExecuteCodeAction;
  53676. }(BABYLON.Action));
  53677. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53678. var SetParentAction = /** @class */ (function (_super) {
  53679. __extends(SetParentAction, _super);
  53680. function SetParentAction(triggerOptions, target, parent, condition) {
  53681. var _this = _super.call(this, triggerOptions, condition) || this;
  53682. _this._target = target;
  53683. _this._parent = parent;
  53684. return _this;
  53685. }
  53686. /** @hidden */
  53687. SetParentAction.prototype._prepare = function () {
  53688. };
  53689. SetParentAction.prototype.execute = function () {
  53690. if (this._target.parent === this._parent) {
  53691. return;
  53692. }
  53693. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53694. invertParentWorldMatrix.invert();
  53695. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53696. this._target.parent = this._parent;
  53697. };
  53698. SetParentAction.prototype.serialize = function (parent) {
  53699. return _super.prototype._serialize.call(this, {
  53700. name: "SetParentAction",
  53701. properties: [
  53702. BABYLON.Action._GetTargetProperty(this._target),
  53703. BABYLON.Action._GetTargetProperty(this._parent),
  53704. ]
  53705. }, parent);
  53706. };
  53707. return SetParentAction;
  53708. }(BABYLON.Action));
  53709. BABYLON.SetParentAction = SetParentAction;
  53710. var PlaySoundAction = /** @class */ (function (_super) {
  53711. __extends(PlaySoundAction, _super);
  53712. function PlaySoundAction(triggerOptions, sound, condition) {
  53713. var _this = _super.call(this, triggerOptions, condition) || this;
  53714. _this._sound = sound;
  53715. return _this;
  53716. }
  53717. /** @hidden */
  53718. PlaySoundAction.prototype._prepare = function () {
  53719. };
  53720. PlaySoundAction.prototype.execute = function () {
  53721. if (this._sound !== undefined)
  53722. this._sound.play();
  53723. };
  53724. PlaySoundAction.prototype.serialize = function (parent) {
  53725. return _super.prototype._serialize.call(this, {
  53726. name: "PlaySoundAction",
  53727. properties: [{ name: "sound", value: this._sound.name }]
  53728. }, parent);
  53729. };
  53730. return PlaySoundAction;
  53731. }(BABYLON.Action));
  53732. BABYLON.PlaySoundAction = PlaySoundAction;
  53733. var StopSoundAction = /** @class */ (function (_super) {
  53734. __extends(StopSoundAction, _super);
  53735. function StopSoundAction(triggerOptions, sound, condition) {
  53736. var _this = _super.call(this, triggerOptions, condition) || this;
  53737. _this._sound = sound;
  53738. return _this;
  53739. }
  53740. /** @hidden */
  53741. StopSoundAction.prototype._prepare = function () {
  53742. };
  53743. StopSoundAction.prototype.execute = function () {
  53744. if (this._sound !== undefined)
  53745. this._sound.stop();
  53746. };
  53747. StopSoundAction.prototype.serialize = function (parent) {
  53748. return _super.prototype._serialize.call(this, {
  53749. name: "StopSoundAction",
  53750. properties: [{ name: "sound", value: this._sound.name }]
  53751. }, parent);
  53752. };
  53753. return StopSoundAction;
  53754. }(BABYLON.Action));
  53755. BABYLON.StopSoundAction = StopSoundAction;
  53756. })(BABYLON || (BABYLON = {}));
  53757. //# sourceMappingURL=babylon.directActions.js.map
  53758. var BABYLON;
  53759. (function (BABYLON) {
  53760. var SpriteManager = /** @class */ (function () {
  53761. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53762. if (epsilon === void 0) { epsilon = 0.01; }
  53763. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53764. this.name = name;
  53765. this.sprites = new Array();
  53766. this.renderingGroupId = 0;
  53767. this.layerMask = 0x0FFFFFFF;
  53768. this.fogEnabled = true;
  53769. this.isPickable = false;
  53770. /**
  53771. * An event triggered when the manager is disposed.
  53772. */
  53773. this.onDisposeObservable = new BABYLON.Observable();
  53774. this._vertexBuffers = {};
  53775. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  53776. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  53777. }
  53778. this._capacity = capacity;
  53779. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53780. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53781. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53782. if (cellSize.width && cellSize.height) {
  53783. this.cellWidth = cellSize.width;
  53784. this.cellHeight = cellSize.height;
  53785. }
  53786. else if (cellSize !== undefined) {
  53787. this.cellWidth = cellSize;
  53788. this.cellHeight = cellSize;
  53789. }
  53790. else {
  53791. return;
  53792. }
  53793. this._epsilon = epsilon;
  53794. this._scene = scene;
  53795. this._scene.spriteManagers.push(this);
  53796. var indices = [];
  53797. var index = 0;
  53798. for (var count = 0; count < capacity; count++) {
  53799. indices.push(index);
  53800. indices.push(index + 1);
  53801. indices.push(index + 2);
  53802. indices.push(index);
  53803. indices.push(index + 2);
  53804. indices.push(index + 3);
  53805. index += 4;
  53806. }
  53807. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53808. // VBO
  53809. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53810. this._vertexData = new Float32Array(capacity * 16 * 4);
  53811. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53812. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53813. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53814. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53815. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53816. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53817. this._vertexBuffers["options"] = options;
  53818. this._vertexBuffers["cellInfo"] = cellInfo;
  53819. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53820. // Effects
  53821. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53822. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53823. }
  53824. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53825. set: function (callback) {
  53826. if (this._onDisposeObserver) {
  53827. this.onDisposeObservable.remove(this._onDisposeObserver);
  53828. }
  53829. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53830. },
  53831. enumerable: true,
  53832. configurable: true
  53833. });
  53834. Object.defineProperty(SpriteManager.prototype, "texture", {
  53835. get: function () {
  53836. return this._spriteTexture;
  53837. },
  53838. set: function (value) {
  53839. this._spriteTexture = value;
  53840. },
  53841. enumerable: true,
  53842. configurable: true
  53843. });
  53844. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53845. var arrayOffset = index * 16;
  53846. if (offsetX === 0)
  53847. offsetX = this._epsilon;
  53848. else if (offsetX === 1)
  53849. offsetX = 1 - this._epsilon;
  53850. if (offsetY === 0)
  53851. offsetY = this._epsilon;
  53852. else if (offsetY === 1)
  53853. offsetY = 1 - this._epsilon;
  53854. this._vertexData[arrayOffset] = sprite.position.x;
  53855. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53856. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53857. this._vertexData[arrayOffset + 3] = sprite.angle;
  53858. this._vertexData[arrayOffset + 4] = sprite.width;
  53859. this._vertexData[arrayOffset + 5] = sprite.height;
  53860. this._vertexData[arrayOffset + 6] = offsetX;
  53861. this._vertexData[arrayOffset + 7] = offsetY;
  53862. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53863. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53864. var offset = (sprite.cellIndex / rowSize) >> 0;
  53865. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53866. this._vertexData[arrayOffset + 11] = offset;
  53867. // Color
  53868. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53869. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53870. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53871. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53872. };
  53873. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53874. var count = Math.min(this._capacity, this.sprites.length);
  53875. var min = BABYLON.Vector3.Zero();
  53876. var max = BABYLON.Vector3.Zero();
  53877. var distance = Number.MAX_VALUE;
  53878. var currentSprite = null;
  53879. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53880. var cameraView = camera.getViewMatrix();
  53881. for (var index = 0; index < count; index++) {
  53882. var sprite = this.sprites[index];
  53883. if (!sprite) {
  53884. continue;
  53885. }
  53886. if (predicate) {
  53887. if (!predicate(sprite)) {
  53888. continue;
  53889. }
  53890. }
  53891. else if (!sprite.isPickable) {
  53892. continue;
  53893. }
  53894. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53895. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53896. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53897. if (ray.intersectsBoxMinMax(min, max)) {
  53898. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53899. if (distance > currentDistance) {
  53900. distance = currentDistance;
  53901. currentSprite = sprite;
  53902. if (fastCheck) {
  53903. break;
  53904. }
  53905. }
  53906. }
  53907. }
  53908. if (currentSprite) {
  53909. var result = new BABYLON.PickingInfo();
  53910. result.hit = true;
  53911. result.pickedSprite = currentSprite;
  53912. result.distance = distance;
  53913. return result;
  53914. }
  53915. return null;
  53916. };
  53917. SpriteManager.prototype.render = function () {
  53918. // Check
  53919. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53920. return;
  53921. var engine = this._scene.getEngine();
  53922. var baseSize = this._spriteTexture.getBaseSize();
  53923. // Sprites
  53924. var deltaTime = engine.getDeltaTime();
  53925. var max = Math.min(this._capacity, this.sprites.length);
  53926. var rowSize = baseSize.width / this.cellWidth;
  53927. var offset = 0;
  53928. for (var index = 0; index < max; index++) {
  53929. var sprite = this.sprites[index];
  53930. if (!sprite || !sprite.isVisible) {
  53931. continue;
  53932. }
  53933. sprite._animate(deltaTime);
  53934. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53935. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53936. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53937. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53938. }
  53939. this._buffer.update(this._vertexData);
  53940. // Render
  53941. var effect = this._effectBase;
  53942. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53943. effect = this._effectFog;
  53944. }
  53945. engine.enableEffect(effect);
  53946. var viewMatrix = this._scene.getViewMatrix();
  53947. effect.setTexture("diffuseSampler", this._spriteTexture);
  53948. effect.setMatrix("view", viewMatrix);
  53949. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53950. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53951. // Fog
  53952. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53953. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53954. effect.setColor3("vFogColor", this._scene.fogColor);
  53955. }
  53956. // VBOs
  53957. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53958. // Draw order
  53959. engine.setDepthFunctionToLessOrEqual();
  53960. effect.setBool("alphaTest", true);
  53961. engine.setColorWrite(false);
  53962. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53963. engine.setColorWrite(true);
  53964. effect.setBool("alphaTest", false);
  53965. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53966. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53967. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53968. };
  53969. SpriteManager.prototype.dispose = function () {
  53970. if (this._buffer) {
  53971. this._buffer.dispose();
  53972. this._buffer = null;
  53973. }
  53974. if (this._indexBuffer) {
  53975. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53976. this._indexBuffer = null;
  53977. }
  53978. if (this._spriteTexture) {
  53979. this._spriteTexture.dispose();
  53980. this._spriteTexture = null;
  53981. }
  53982. // Remove from scene
  53983. var index = this._scene.spriteManagers.indexOf(this);
  53984. this._scene.spriteManagers.splice(index, 1);
  53985. // Callback
  53986. this.onDisposeObservable.notifyObservers(this);
  53987. this.onDisposeObservable.clear();
  53988. };
  53989. return SpriteManager;
  53990. }());
  53991. BABYLON.SpriteManager = SpriteManager;
  53992. })(BABYLON || (BABYLON = {}));
  53993. //# sourceMappingURL=babylon.spriteManager.js.map
  53994. var BABYLON;
  53995. (function (BABYLON) {
  53996. var Sprite = /** @class */ (function () {
  53997. function Sprite(name, manager) {
  53998. this.name = name;
  53999. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54000. this.width = 1.0;
  54001. this.height = 1.0;
  54002. this.angle = 0;
  54003. this.cellIndex = 0;
  54004. this.invertU = 0;
  54005. this.invertV = 0;
  54006. this.animations = new Array();
  54007. this.isPickable = false;
  54008. this._animationStarted = false;
  54009. this._loopAnimation = false;
  54010. this._fromIndex = 0;
  54011. this._toIndex = 0;
  54012. this._delay = 0;
  54013. this._direction = 1;
  54014. this._time = 0;
  54015. /**
  54016. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54017. */
  54018. this.isVisible = true;
  54019. this._manager = manager;
  54020. this._manager.sprites.push(this);
  54021. this.position = BABYLON.Vector3.Zero();
  54022. }
  54023. Object.defineProperty(Sprite.prototype, "size", {
  54024. get: function () {
  54025. return this.width;
  54026. },
  54027. set: function (value) {
  54028. this.width = value;
  54029. this.height = value;
  54030. },
  54031. enumerable: true,
  54032. configurable: true
  54033. });
  54034. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54035. this._fromIndex = from;
  54036. this._toIndex = to;
  54037. this._loopAnimation = loop;
  54038. this._delay = delay;
  54039. this._animationStarted = true;
  54040. this._direction = from < to ? 1 : -1;
  54041. this.cellIndex = from;
  54042. this._time = 0;
  54043. this._onAnimationEnd = onAnimationEnd;
  54044. };
  54045. Sprite.prototype.stopAnimation = function () {
  54046. this._animationStarted = false;
  54047. };
  54048. /** @hidden */
  54049. Sprite.prototype._animate = function (deltaTime) {
  54050. if (!this._animationStarted)
  54051. return;
  54052. this._time += deltaTime;
  54053. if (this._time > this._delay) {
  54054. this._time = this._time % this._delay;
  54055. this.cellIndex += this._direction;
  54056. if (this.cellIndex > this._toIndex) {
  54057. if (this._loopAnimation) {
  54058. this.cellIndex = this._fromIndex;
  54059. }
  54060. else {
  54061. this.cellIndex = this._toIndex;
  54062. this._animationStarted = false;
  54063. if (this._onAnimationEnd) {
  54064. this._onAnimationEnd();
  54065. }
  54066. if (this.disposeWhenFinishedAnimating) {
  54067. this.dispose();
  54068. }
  54069. }
  54070. }
  54071. }
  54072. };
  54073. Sprite.prototype.dispose = function () {
  54074. for (var i = 0; i < this._manager.sprites.length; i++) {
  54075. if (this._manager.sprites[i] == this) {
  54076. this._manager.sprites.splice(i, 1);
  54077. }
  54078. }
  54079. };
  54080. return Sprite;
  54081. }());
  54082. BABYLON.Sprite = Sprite;
  54083. })(BABYLON || (BABYLON = {}));
  54084. //# sourceMappingURL=babylon.sprite.js.map
  54085. var BABYLON;
  54086. (function (BABYLON) {
  54087. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  54088. if (!BABYLON.PickingInfo) {
  54089. return null;
  54090. }
  54091. var pickingInfo = null;
  54092. if (!camera) {
  54093. if (!this.activeCamera) {
  54094. return null;
  54095. }
  54096. camera = this.activeCamera;
  54097. }
  54098. if (this.spriteManagers.length > 0) {
  54099. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  54100. var spriteManager = this.spriteManagers[spriteIndex];
  54101. if (!spriteManager.isPickable) {
  54102. continue;
  54103. }
  54104. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  54105. if (!result || !result.hit)
  54106. continue;
  54107. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  54108. continue;
  54109. pickingInfo = result;
  54110. if (fastCheck) {
  54111. break;
  54112. }
  54113. }
  54114. }
  54115. return pickingInfo || new BABYLON.PickingInfo();
  54116. };
  54117. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  54118. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  54119. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54120. };
  54121. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  54122. if (!this._tempSpritePickingRay) {
  54123. return null;
  54124. }
  54125. if (!camera) {
  54126. if (!this.activeCamera) {
  54127. return null;
  54128. }
  54129. camera = this.activeCamera;
  54130. }
  54131. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  54132. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54133. };
  54134. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  54135. if (this._pointerOverSprite === sprite) {
  54136. return;
  54137. }
  54138. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  54139. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  54140. }
  54141. this._pointerOverSprite = sprite;
  54142. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  54143. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  54144. }
  54145. };
  54146. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  54147. return this._pointerOverSprite;
  54148. };
  54149. /**
  54150. * Defines the sprite scene component responsible to manage sprites
  54151. * in a given scene.
  54152. */
  54153. var SpriteSceneComponent = /** @class */ (function () {
  54154. /**
  54155. * Creates a new instance of the component for the given scene
  54156. * @param scene Defines the scene to register the component in
  54157. */
  54158. function SpriteSceneComponent(scene) {
  54159. /**
  54160. * The component name helpfull to identify the component in the list of scene components.
  54161. */
  54162. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  54163. this.scene = scene;
  54164. this.scene.spriteManagers = new Array();
  54165. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  54166. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  54167. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  54168. this._spritePredicate = function (sprite) {
  54169. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  54170. };
  54171. }
  54172. /**
  54173. * Registers the component in a given scene
  54174. */
  54175. SpriteSceneComponent.prototype.register = function () {
  54176. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  54177. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  54178. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  54179. };
  54180. /**
  54181. * Rebuilds the elements related to this component in case of
  54182. * context lost for instance.
  54183. */
  54184. SpriteSceneComponent.prototype.rebuild = function () {
  54185. /** Nothing to do for sprites */
  54186. };
  54187. /**
  54188. * Disposes the component and the associated ressources.
  54189. */
  54190. SpriteSceneComponent.prototype.dispose = function () {
  54191. this.scene.onBeforeSpritesRenderingObservable.clear();
  54192. this.scene.onAfterSpritesRenderingObservable.clear();
  54193. var spriteManagers = this.scene.spriteManagers;
  54194. while (spriteManagers.length) {
  54195. spriteManagers[0].dispose();
  54196. }
  54197. };
  54198. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  54199. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  54200. if (result) {
  54201. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  54202. }
  54203. return result;
  54204. };
  54205. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  54206. var scene = this.scene;
  54207. if (isMeshPicked) {
  54208. scene.setPointerOverSprite(null);
  54209. }
  54210. else {
  54211. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  54212. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  54213. scene.setPointerOverSprite(pickResult.pickedSprite);
  54214. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  54215. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  54216. }
  54217. else {
  54218. canvas.style.cursor = scene.hoverCursor;
  54219. }
  54220. }
  54221. else {
  54222. scene.setPointerOverSprite(null);
  54223. }
  54224. }
  54225. return pickResult;
  54226. };
  54227. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54228. var scene = this.scene;
  54229. scene._pickedDownSprite = null;
  54230. if (scene.spriteManagers.length > 0) {
  54231. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54232. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  54233. if (pickResult.pickedSprite.actionManager) {
  54234. scene._pickedDownSprite = pickResult.pickedSprite;
  54235. switch (evt.button) {
  54236. case 0:
  54237. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54238. break;
  54239. case 1:
  54240. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54241. break;
  54242. case 2:
  54243. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54244. break;
  54245. }
  54246. if (pickResult.pickedSprite.actionManager) {
  54247. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54248. }
  54249. }
  54250. }
  54251. }
  54252. return pickResult;
  54253. };
  54254. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54255. var scene = this.scene;
  54256. if (scene.spriteManagers.length > 0) {
  54257. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54258. if (spritePickResult) {
  54259. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  54260. if (spritePickResult.pickedSprite.actionManager) {
  54261. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54262. if (spritePickResult.pickedSprite.actionManager) {
  54263. if (!this.scene._isPointerSwiping()) {
  54264. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54265. }
  54266. }
  54267. }
  54268. }
  54269. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  54270. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  54271. }
  54272. }
  54273. }
  54274. return pickResult;
  54275. };
  54276. return SpriteSceneComponent;
  54277. }());
  54278. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  54279. })(BABYLON || (BABYLON = {}));
  54280. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  54281. var BABYLON;
  54282. (function (BABYLON) {
  54283. var IntersectionInfo = /** @class */ (function () {
  54284. function IntersectionInfo(bu, bv, distance) {
  54285. this.bu = bu;
  54286. this.bv = bv;
  54287. this.distance = distance;
  54288. this.faceId = 0;
  54289. this.subMeshId = 0;
  54290. }
  54291. return IntersectionInfo;
  54292. }());
  54293. BABYLON.IntersectionInfo = IntersectionInfo;
  54294. /**
  54295. * Information about the result of picking within a scene
  54296. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54297. */
  54298. var PickingInfo = /** @class */ (function () {
  54299. function PickingInfo() {
  54300. /**
  54301. * If the pick collided with an object
  54302. */
  54303. this.hit = false;
  54304. /**
  54305. * Distance away where the pick collided
  54306. */
  54307. this.distance = 0;
  54308. /**
  54309. * The location of pick collision
  54310. */
  54311. this.pickedPoint = null;
  54312. /**
  54313. * The mesh corresponding the the pick collision
  54314. */
  54315. this.pickedMesh = null;
  54316. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54317. this.bu = 0;
  54318. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54319. this.bv = 0;
  54320. /** The id of the face on the mesh that was picked */
  54321. this.faceId = -1;
  54322. /** Id of the the submesh that was picked */
  54323. this.subMeshId = 0;
  54324. /** If a sprite was picked, this will be the sprite the pick collided with */
  54325. this.pickedSprite = null;
  54326. /**
  54327. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54328. */
  54329. this.originMesh = null;
  54330. /**
  54331. * The ray that was used to perform the picking.
  54332. */
  54333. this.ray = null;
  54334. }
  54335. /**
  54336. * Gets the normal correspodning to the face the pick collided with
  54337. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54338. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54339. * @returns The normal correspodning to the face the pick collided with
  54340. */
  54341. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54342. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54343. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54344. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54345. return null;
  54346. }
  54347. var indices = this.pickedMesh.getIndices();
  54348. if (!indices) {
  54349. return null;
  54350. }
  54351. var result;
  54352. if (useVerticesNormals) {
  54353. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54354. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54355. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54356. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54357. normal0 = normal0.scale(this.bu);
  54358. normal1 = normal1.scale(this.bv);
  54359. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54360. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54361. }
  54362. else {
  54363. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54364. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54365. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54366. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54367. var p1p2 = vertex1.subtract(vertex2);
  54368. var p3p2 = vertex3.subtract(vertex2);
  54369. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54370. }
  54371. if (useWorldCoordinates) {
  54372. var wm = this.pickedMesh.getWorldMatrix();
  54373. if (this.pickedMesh.nonUniformScaling) {
  54374. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54375. wm = BABYLON.Tmp.Matrix[0];
  54376. wm.setTranslationFromFloats(0, 0, 0);
  54377. wm.invert();
  54378. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54379. wm = BABYLON.Tmp.Matrix[1];
  54380. }
  54381. result = BABYLON.Vector3.TransformNormal(result, wm);
  54382. }
  54383. result.normalize();
  54384. return result;
  54385. };
  54386. /**
  54387. * Gets the texture coordinates of where the pick occured
  54388. * @returns the vector containing the coordnates of the texture
  54389. */
  54390. PickingInfo.prototype.getTextureCoordinates = function () {
  54391. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54392. return null;
  54393. }
  54394. var indices = this.pickedMesh.getIndices();
  54395. if (!indices) {
  54396. return null;
  54397. }
  54398. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54399. if (!uvs) {
  54400. return null;
  54401. }
  54402. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54403. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54404. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54405. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54406. uv1 = uv1.scale(this.bu);
  54407. uv2 = uv2.scale(this.bv);
  54408. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54409. };
  54410. return PickingInfo;
  54411. }());
  54412. BABYLON.PickingInfo = PickingInfo;
  54413. })(BABYLON || (BABYLON = {}));
  54414. //# sourceMappingURL=babylon.pickingInfo.js.map
  54415. var BABYLON;
  54416. (function (BABYLON) {
  54417. var Ray = /** @class */ (function () {
  54418. function Ray(origin, direction, length) {
  54419. if (length === void 0) { length = Number.MAX_VALUE; }
  54420. this.origin = origin;
  54421. this.direction = direction;
  54422. this.length = length;
  54423. }
  54424. // Methods
  54425. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54426. var d = 0.0;
  54427. var maxValue = Number.MAX_VALUE;
  54428. var inv;
  54429. var min;
  54430. var max;
  54431. var temp;
  54432. if (Math.abs(this.direction.x) < 0.0000001) {
  54433. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54434. return false;
  54435. }
  54436. }
  54437. else {
  54438. inv = 1.0 / this.direction.x;
  54439. min = (minimum.x - this.origin.x) * inv;
  54440. max = (maximum.x - this.origin.x) * inv;
  54441. if (max === -Infinity) {
  54442. max = Infinity;
  54443. }
  54444. if (min > max) {
  54445. temp = min;
  54446. min = max;
  54447. max = temp;
  54448. }
  54449. d = Math.max(min, d);
  54450. maxValue = Math.min(max, maxValue);
  54451. if (d > maxValue) {
  54452. return false;
  54453. }
  54454. }
  54455. if (Math.abs(this.direction.y) < 0.0000001) {
  54456. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54457. return false;
  54458. }
  54459. }
  54460. else {
  54461. inv = 1.0 / this.direction.y;
  54462. min = (minimum.y - this.origin.y) * inv;
  54463. max = (maximum.y - this.origin.y) * inv;
  54464. if (max === -Infinity) {
  54465. max = Infinity;
  54466. }
  54467. if (min > max) {
  54468. temp = min;
  54469. min = max;
  54470. max = temp;
  54471. }
  54472. d = Math.max(min, d);
  54473. maxValue = Math.min(max, maxValue);
  54474. if (d > maxValue) {
  54475. return false;
  54476. }
  54477. }
  54478. if (Math.abs(this.direction.z) < 0.0000001) {
  54479. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54480. return false;
  54481. }
  54482. }
  54483. else {
  54484. inv = 1.0 / this.direction.z;
  54485. min = (minimum.z - this.origin.z) * inv;
  54486. max = (maximum.z - this.origin.z) * inv;
  54487. if (max === -Infinity) {
  54488. max = Infinity;
  54489. }
  54490. if (min > max) {
  54491. temp = min;
  54492. min = max;
  54493. max = temp;
  54494. }
  54495. d = Math.max(min, d);
  54496. maxValue = Math.min(max, maxValue);
  54497. if (d > maxValue) {
  54498. return false;
  54499. }
  54500. }
  54501. return true;
  54502. };
  54503. Ray.prototype.intersectsBox = function (box) {
  54504. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54505. };
  54506. Ray.prototype.intersectsSphere = function (sphere) {
  54507. var x = sphere.center.x - this.origin.x;
  54508. var y = sphere.center.y - this.origin.y;
  54509. var z = sphere.center.z - this.origin.z;
  54510. var pyth = (x * x) + (y * y) + (z * z);
  54511. var rr = sphere.radius * sphere.radius;
  54512. if (pyth <= rr) {
  54513. return true;
  54514. }
  54515. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54516. if (dot < 0.0) {
  54517. return false;
  54518. }
  54519. var temp = pyth - (dot * dot);
  54520. return temp <= rr;
  54521. };
  54522. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54523. if (!this._edge1) {
  54524. this._edge1 = BABYLON.Vector3.Zero();
  54525. this._edge2 = BABYLON.Vector3.Zero();
  54526. this._pvec = BABYLON.Vector3.Zero();
  54527. this._tvec = BABYLON.Vector3.Zero();
  54528. this._qvec = BABYLON.Vector3.Zero();
  54529. }
  54530. vertex1.subtractToRef(vertex0, this._edge1);
  54531. vertex2.subtractToRef(vertex0, this._edge2);
  54532. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54533. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54534. if (det === 0) {
  54535. return null;
  54536. }
  54537. var invdet = 1 / det;
  54538. this.origin.subtractToRef(vertex0, this._tvec);
  54539. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54540. if (bu < 0 || bu > 1.0) {
  54541. return null;
  54542. }
  54543. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54544. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54545. if (bv < 0 || bu + bv > 1.0) {
  54546. return null;
  54547. }
  54548. //check if the distance is longer than the predefined length.
  54549. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54550. if (distance > this.length) {
  54551. return null;
  54552. }
  54553. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54554. };
  54555. Ray.prototype.intersectsPlane = function (plane) {
  54556. var distance;
  54557. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54558. if (Math.abs(result1) < 9.99999997475243E-07) {
  54559. return null;
  54560. }
  54561. else {
  54562. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54563. distance = (-plane.d - result2) / result1;
  54564. if (distance < 0.0) {
  54565. if (distance < -9.99999997475243E-07) {
  54566. return null;
  54567. }
  54568. else {
  54569. return 0;
  54570. }
  54571. }
  54572. return distance;
  54573. }
  54574. };
  54575. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54576. var tm = BABYLON.Tmp.Matrix[0];
  54577. mesh.getWorldMatrix().invertToRef(tm);
  54578. if (this._tmpRay) {
  54579. Ray.TransformToRef(this, tm, this._tmpRay);
  54580. }
  54581. else {
  54582. this._tmpRay = Ray.Transform(this, tm);
  54583. }
  54584. return mesh.intersects(this._tmpRay, fastCheck);
  54585. };
  54586. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54587. if (results) {
  54588. results.length = 0;
  54589. }
  54590. else {
  54591. results = [];
  54592. }
  54593. for (var i = 0; i < meshes.length; i++) {
  54594. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54595. if (pickInfo.hit) {
  54596. results.push(pickInfo);
  54597. }
  54598. }
  54599. results.sort(this._comparePickingInfo);
  54600. return results;
  54601. };
  54602. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54603. if (pickingInfoA.distance < pickingInfoB.distance) {
  54604. return -1;
  54605. }
  54606. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54607. return 1;
  54608. }
  54609. else {
  54610. return 0;
  54611. }
  54612. };
  54613. /**
  54614. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54615. * @param sega the first point of the segment to test the intersection against
  54616. * @param segb the second point of the segment to test the intersection against
  54617. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54618. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54619. */
  54620. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54621. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54622. var u = segb.subtract(sega);
  54623. var v = rsegb.subtract(this.origin);
  54624. var w = sega.subtract(this.origin);
  54625. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54626. var b = BABYLON.Vector3.Dot(u, v);
  54627. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54628. var d = BABYLON.Vector3.Dot(u, w);
  54629. var e = BABYLON.Vector3.Dot(v, w);
  54630. var D = a * c - b * b; // always >= 0
  54631. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54632. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54633. // compute the line parameters of the two closest points
  54634. if (D < Ray.smallnum) { // the lines are almost parallel
  54635. sN = 0.0; // force using point P0 on segment S1
  54636. sD = 1.0; // to prevent possible division by 0.0 later
  54637. tN = e;
  54638. tD = c;
  54639. }
  54640. else { // get the closest points on the infinite lines
  54641. sN = (b * e - c * d);
  54642. tN = (a * e - b * d);
  54643. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54644. sN = 0.0;
  54645. tN = e;
  54646. tD = c;
  54647. }
  54648. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54649. sN = sD;
  54650. tN = e + b;
  54651. tD = c;
  54652. }
  54653. }
  54654. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54655. tN = 0.0;
  54656. // recompute sc for this edge
  54657. if (-d < 0.0) {
  54658. sN = 0.0;
  54659. }
  54660. else if (-d > a)
  54661. sN = sD;
  54662. else {
  54663. sN = -d;
  54664. sD = a;
  54665. }
  54666. }
  54667. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54668. tN = tD;
  54669. // recompute sc for this edge
  54670. if ((-d + b) < 0.0) {
  54671. sN = 0;
  54672. }
  54673. else if ((-d + b) > a) {
  54674. sN = sD;
  54675. }
  54676. else {
  54677. sN = (-d + b);
  54678. sD = a;
  54679. }
  54680. }
  54681. // finally do the division to get sc and tc
  54682. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54683. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54684. // get the difference of the two closest points
  54685. var qtc = v.multiplyByFloats(tc, tc, tc);
  54686. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54687. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54688. if (isIntersected) {
  54689. return qtc.length();
  54690. }
  54691. return -1;
  54692. };
  54693. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54694. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54695. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54696. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54697. this.direction.normalize();
  54698. return this;
  54699. };
  54700. // Statics
  54701. Ray.Zero = function () {
  54702. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54703. };
  54704. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54705. var result = Ray.Zero();
  54706. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54707. };
  54708. /**
  54709. * 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
  54710. * transformed to the given world matrix.
  54711. * @param origin The origin point
  54712. * @param end The end point
  54713. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54714. */
  54715. Ray.CreateNewFromTo = function (origin, end, world) {
  54716. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54717. var direction = end.subtract(origin);
  54718. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54719. direction.normalize();
  54720. return Ray.Transform(new Ray(origin, direction, length), world);
  54721. };
  54722. Ray.Transform = function (ray, matrix) {
  54723. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54724. Ray.TransformToRef(ray, matrix, result);
  54725. return result;
  54726. };
  54727. Ray.TransformToRef = function (ray, matrix, result) {
  54728. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54729. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54730. result.length = ray.length;
  54731. var dir = result.direction;
  54732. var len = dir.length();
  54733. if (!(len === 0 || len === 1)) {
  54734. var num = 1.0 / len;
  54735. dir.x *= num;
  54736. dir.y *= num;
  54737. dir.z *= num;
  54738. result.length *= len;
  54739. }
  54740. };
  54741. Ray.smallnum = 0.00000001;
  54742. Ray.rayl = 10e8;
  54743. return Ray;
  54744. }());
  54745. BABYLON.Ray = Ray;
  54746. })(BABYLON || (BABYLON = {}));
  54747. //# sourceMappingURL=babylon.ray.js.map
  54748. var BABYLON;
  54749. (function (BABYLON) {
  54750. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54751. if (boxMin.x > sphereCenter.x + sphereRadius)
  54752. return false;
  54753. if (sphereCenter.x - sphereRadius > boxMax.x)
  54754. return false;
  54755. if (boxMin.y > sphereCenter.y + sphereRadius)
  54756. return false;
  54757. if (sphereCenter.y - sphereRadius > boxMax.y)
  54758. return false;
  54759. if (boxMin.z > sphereCenter.z + sphereRadius)
  54760. return false;
  54761. if (sphereCenter.z - sphereRadius > boxMax.z)
  54762. return false;
  54763. return true;
  54764. };
  54765. var getLowestRoot = (function () {
  54766. var result = { root: 0, found: false };
  54767. return function (a, b, c, maxR) {
  54768. result.root = 0;
  54769. result.found = false;
  54770. var determinant = b * b - 4.0 * a * c;
  54771. if (determinant < 0)
  54772. return result;
  54773. var sqrtD = Math.sqrt(determinant);
  54774. var r1 = (-b - sqrtD) / (2.0 * a);
  54775. var r2 = (-b + sqrtD) / (2.0 * a);
  54776. if (r1 > r2) {
  54777. var temp = r2;
  54778. r2 = r1;
  54779. r1 = temp;
  54780. }
  54781. if (r1 > 0 && r1 < maxR) {
  54782. result.root = r1;
  54783. result.found = true;
  54784. return result;
  54785. }
  54786. if (r2 > 0 && r2 < maxR) {
  54787. result.root = r2;
  54788. result.found = true;
  54789. return result;
  54790. }
  54791. return result;
  54792. };
  54793. })();
  54794. var Collider = /** @class */ (function () {
  54795. function Collider() {
  54796. this._collisionPoint = BABYLON.Vector3.Zero();
  54797. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54798. this._tempVector = BABYLON.Vector3.Zero();
  54799. this._tempVector2 = BABYLON.Vector3.Zero();
  54800. this._tempVector3 = BABYLON.Vector3.Zero();
  54801. this._tempVector4 = BABYLON.Vector3.Zero();
  54802. this._edge = BABYLON.Vector3.Zero();
  54803. this._baseToVertex = BABYLON.Vector3.Zero();
  54804. this._destinationPoint = BABYLON.Vector3.Zero();
  54805. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54806. this._displacementVector = BABYLON.Vector3.Zero();
  54807. /** @hidden */
  54808. this._radius = BABYLON.Vector3.One();
  54809. /** @hidden */
  54810. this._retry = 0;
  54811. /** @hidden */
  54812. this._basePointWorld = BABYLON.Vector3.Zero();
  54813. this._velocityWorld = BABYLON.Vector3.Zero();
  54814. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54815. this._collisionMask = -1;
  54816. }
  54817. Object.defineProperty(Collider.prototype, "collisionMask", {
  54818. get: function () {
  54819. return this._collisionMask;
  54820. },
  54821. set: function (mask) {
  54822. this._collisionMask = !isNaN(mask) ? mask : -1;
  54823. },
  54824. enumerable: true,
  54825. configurable: true
  54826. });
  54827. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54828. /**
  54829. * Gets the plane normal used to compute the sliding response (in local space)
  54830. */
  54831. get: function () {
  54832. return this._slidePlaneNormal;
  54833. },
  54834. enumerable: true,
  54835. configurable: true
  54836. });
  54837. // Methods
  54838. /** @hidden */
  54839. Collider.prototype._initialize = function (source, dir, e) {
  54840. this._velocity = dir;
  54841. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54842. this._basePoint = source;
  54843. source.multiplyToRef(this._radius, this._basePointWorld);
  54844. dir.multiplyToRef(this._radius, this._velocityWorld);
  54845. this._velocityWorldLength = this._velocityWorld.length();
  54846. this._epsilon = e;
  54847. this.collisionFound = false;
  54848. };
  54849. /** @hidden */
  54850. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54851. pa.subtractToRef(point, this._tempVector);
  54852. pb.subtractToRef(point, this._tempVector2);
  54853. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54854. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54855. if (d < 0)
  54856. return false;
  54857. pc.subtractToRef(point, this._tempVector3);
  54858. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54859. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54860. if (d < 0)
  54861. return false;
  54862. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54863. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54864. return d >= 0;
  54865. };
  54866. /** @hidden */
  54867. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54868. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54869. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54870. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54871. return false;
  54872. }
  54873. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54874. return false;
  54875. return true;
  54876. };
  54877. /** @hidden */
  54878. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54879. var t0;
  54880. var embeddedInPlane = false;
  54881. //defensive programming, actually not needed.
  54882. if (!trianglePlaneArray) {
  54883. trianglePlaneArray = [];
  54884. }
  54885. if (!trianglePlaneArray[faceIndex]) {
  54886. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54887. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54888. }
  54889. var trianglePlane = trianglePlaneArray[faceIndex];
  54890. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54891. return;
  54892. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54893. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54894. if (normalDotVelocity == 0) {
  54895. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54896. return;
  54897. embeddedInPlane = true;
  54898. t0 = 0;
  54899. }
  54900. else {
  54901. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54902. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54903. if (t0 > t1) {
  54904. var temp = t1;
  54905. t1 = t0;
  54906. t0 = temp;
  54907. }
  54908. if (t0 > 1.0 || t1 < 0.0)
  54909. return;
  54910. if (t0 < 0)
  54911. t0 = 0;
  54912. if (t0 > 1.0)
  54913. t0 = 1.0;
  54914. }
  54915. this._collisionPoint.copyFromFloats(0, 0, 0);
  54916. var found = false;
  54917. var t = 1.0;
  54918. if (!embeddedInPlane) {
  54919. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54920. this._velocity.scaleToRef(t0, this._tempVector);
  54921. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54922. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54923. found = true;
  54924. t = t0;
  54925. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54926. }
  54927. }
  54928. if (!found) {
  54929. var velocitySquaredLength = this._velocity.lengthSquared();
  54930. var a = velocitySquaredLength;
  54931. this._basePoint.subtractToRef(p1, this._tempVector);
  54932. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54933. var c = this._tempVector.lengthSquared() - 1.0;
  54934. var lowestRoot = getLowestRoot(a, b, c, t);
  54935. if (lowestRoot.found) {
  54936. t = lowestRoot.root;
  54937. found = true;
  54938. this._collisionPoint.copyFrom(p1);
  54939. }
  54940. this._basePoint.subtractToRef(p2, this._tempVector);
  54941. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54942. c = this._tempVector.lengthSquared() - 1.0;
  54943. lowestRoot = getLowestRoot(a, b, c, t);
  54944. if (lowestRoot.found) {
  54945. t = lowestRoot.root;
  54946. found = true;
  54947. this._collisionPoint.copyFrom(p2);
  54948. }
  54949. this._basePoint.subtractToRef(p3, this._tempVector);
  54950. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54951. c = this._tempVector.lengthSquared() - 1.0;
  54952. lowestRoot = getLowestRoot(a, b, c, t);
  54953. if (lowestRoot.found) {
  54954. t = lowestRoot.root;
  54955. found = true;
  54956. this._collisionPoint.copyFrom(p3);
  54957. }
  54958. p2.subtractToRef(p1, this._edge);
  54959. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54960. var edgeSquaredLength = this._edge.lengthSquared();
  54961. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54962. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54963. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54964. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54965. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54966. lowestRoot = getLowestRoot(a, b, c, t);
  54967. if (lowestRoot.found) {
  54968. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54969. if (f >= 0.0 && f <= 1.0) {
  54970. t = lowestRoot.root;
  54971. found = true;
  54972. this._edge.scaleInPlace(f);
  54973. p1.addToRef(this._edge, this._collisionPoint);
  54974. }
  54975. }
  54976. p3.subtractToRef(p2, this._edge);
  54977. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54978. edgeSquaredLength = this._edge.lengthSquared();
  54979. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54980. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54981. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54982. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54983. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54984. lowestRoot = getLowestRoot(a, b, c, t);
  54985. if (lowestRoot.found) {
  54986. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54987. if (f >= 0.0 && f <= 1.0) {
  54988. t = lowestRoot.root;
  54989. found = true;
  54990. this._edge.scaleInPlace(f);
  54991. p2.addToRef(this._edge, this._collisionPoint);
  54992. }
  54993. }
  54994. p1.subtractToRef(p3, this._edge);
  54995. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54996. edgeSquaredLength = this._edge.lengthSquared();
  54997. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54998. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54999. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55000. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55001. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55002. lowestRoot = getLowestRoot(a, b, c, t);
  55003. if (lowestRoot.found) {
  55004. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55005. if (f >= 0.0 && f <= 1.0) {
  55006. t = lowestRoot.root;
  55007. found = true;
  55008. this._edge.scaleInPlace(f);
  55009. p3.addToRef(this._edge, this._collisionPoint);
  55010. }
  55011. }
  55012. }
  55013. if (found) {
  55014. var distToCollision = t * this._velocity.length();
  55015. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55016. if (!this.intersectionPoint) {
  55017. this.intersectionPoint = this._collisionPoint.clone();
  55018. }
  55019. else {
  55020. this.intersectionPoint.copyFrom(this._collisionPoint);
  55021. }
  55022. this._nearestDistance = distToCollision;
  55023. this.collisionFound = true;
  55024. }
  55025. }
  55026. };
  55027. /** @hidden */
  55028. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55029. for (var i = indexStart; i < indexEnd; i += 3) {
  55030. var p1 = pts[indices[i] - decal];
  55031. var p2 = pts[indices[i + 1] - decal];
  55032. var p3 = pts[indices[i + 2] - decal];
  55033. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55034. }
  55035. };
  55036. /** @hidden */
  55037. Collider.prototype._getResponse = function (pos, vel) {
  55038. pos.addToRef(vel, this._destinationPoint);
  55039. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55040. this._basePoint.addToRef(vel, pos);
  55041. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55042. this._slidePlaneNormal.normalize();
  55043. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55044. pos.addInPlace(this._displacementVector);
  55045. this.intersectionPoint.addInPlace(this._displacementVector);
  55046. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55047. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55048. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55049. };
  55050. return Collider;
  55051. }());
  55052. BABYLON.Collider = Collider;
  55053. })(BABYLON || (BABYLON = {}));
  55054. //# sourceMappingURL=babylon.collider.js.map
  55055. var BABYLON;
  55056. (function (BABYLON) {
  55057. //WebWorker code will be inserted to this variable.
  55058. BABYLON.CollisionWorker = "";
  55059. /** Defines supported task for worker process */
  55060. var WorkerTaskType;
  55061. (function (WorkerTaskType) {
  55062. /** Initialization */
  55063. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55064. /** Update of geometry */
  55065. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55066. /** Evaluate collision */
  55067. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55068. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55069. /** Defines kind of replies returned by worker */
  55070. var WorkerReplyType;
  55071. (function (WorkerReplyType) {
  55072. /** Success */
  55073. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55074. /** Unkown error */
  55075. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55076. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55077. var CollisionCoordinatorWorker = /** @class */ (function () {
  55078. function CollisionCoordinatorWorker() {
  55079. var _this = this;
  55080. this._scaledPosition = BABYLON.Vector3.Zero();
  55081. this._scaledVelocity = BABYLON.Vector3.Zero();
  55082. this.onMeshUpdated = function (transformNode) {
  55083. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55084. };
  55085. this.onGeometryUpdated = function (geometry) {
  55086. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55087. };
  55088. this._afterRender = function () {
  55089. if (!_this._init)
  55090. return;
  55091. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55092. return;
  55093. }
  55094. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55095. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55096. if (_this._runningUpdated > 4) {
  55097. return;
  55098. }
  55099. ++_this._runningUpdated;
  55100. var payload = {
  55101. updatedMeshes: _this._addUpdateMeshesList,
  55102. updatedGeometries: _this._addUpdateGeometriesList,
  55103. removedGeometries: _this._toRemoveGeometryArray,
  55104. removedMeshes: _this._toRemoveMeshesArray
  55105. };
  55106. var message = {
  55107. payload: payload,
  55108. taskType: WorkerTaskType.UPDATE
  55109. };
  55110. var serializable = [];
  55111. for (var id in payload.updatedGeometries) {
  55112. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55113. //prepare transferables
  55114. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55115. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55116. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55117. }
  55118. }
  55119. _this._worker.postMessage(message, serializable);
  55120. _this._addUpdateMeshesList = {};
  55121. _this._addUpdateGeometriesList = {};
  55122. _this._toRemoveGeometryArray = [];
  55123. _this._toRemoveMeshesArray = [];
  55124. };
  55125. this._onMessageFromWorker = function (e) {
  55126. var returnData = e.data;
  55127. if (returnData.error != WorkerReplyType.SUCCESS) {
  55128. //TODO what errors can be returned from the worker?
  55129. BABYLON.Tools.Warn("error returned from worker!");
  55130. return;
  55131. }
  55132. switch (returnData.taskType) {
  55133. case WorkerTaskType.INIT:
  55134. _this._init = true;
  55135. //Update the worked with ALL of the scene's current state
  55136. _this._scene.meshes.forEach(function (mesh) {
  55137. _this.onMeshAdded(mesh);
  55138. });
  55139. _this._scene.getGeometries().forEach(function (geometry) {
  55140. _this.onGeometryAdded(geometry);
  55141. });
  55142. break;
  55143. case WorkerTaskType.UPDATE:
  55144. _this._runningUpdated--;
  55145. break;
  55146. case WorkerTaskType.COLLIDE:
  55147. var returnPayload = returnData.payload;
  55148. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55149. return;
  55150. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55151. if (callback) {
  55152. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55153. if (mesh) {
  55154. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55155. }
  55156. }
  55157. //cleanup
  55158. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55159. break;
  55160. }
  55161. };
  55162. this._collisionsCallbackArray = [];
  55163. this._init = false;
  55164. this._runningUpdated = 0;
  55165. this._addUpdateMeshesList = {};
  55166. this._addUpdateGeometriesList = {};
  55167. this._toRemoveGeometryArray = [];
  55168. this._toRemoveMeshesArray = [];
  55169. }
  55170. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55171. if (!this._init)
  55172. return;
  55173. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55174. return;
  55175. position.divideToRef(collider._radius, this._scaledPosition);
  55176. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55177. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55178. var payload = {
  55179. collider: {
  55180. position: this._scaledPosition.asArray(),
  55181. velocity: this._scaledVelocity.asArray(),
  55182. radius: collider._radius.asArray()
  55183. },
  55184. collisionId: collisionIndex,
  55185. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55186. maximumRetry: maximumRetry
  55187. };
  55188. var message = {
  55189. payload: payload,
  55190. taskType: WorkerTaskType.COLLIDE
  55191. };
  55192. this._worker.postMessage(message);
  55193. };
  55194. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55195. this._scene = scene;
  55196. this._scene.registerAfterRender(this._afterRender);
  55197. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55198. this._worker = new Worker(workerUrl);
  55199. this._worker.onmessage = this._onMessageFromWorker;
  55200. var message = {
  55201. payload: {},
  55202. taskType: WorkerTaskType.INIT
  55203. };
  55204. this._worker.postMessage(message);
  55205. };
  55206. CollisionCoordinatorWorker.prototype.destroy = function () {
  55207. this._scene.unregisterAfterRender(this._afterRender);
  55208. this._worker.terminate();
  55209. };
  55210. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55211. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55212. this.onMeshUpdated(mesh);
  55213. };
  55214. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55215. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55216. };
  55217. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55218. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55219. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55220. this.onGeometryUpdated(geometry);
  55221. };
  55222. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55223. this._toRemoveGeometryArray.push(geometry.id);
  55224. };
  55225. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55226. var submeshes = [];
  55227. if (mesh.subMeshes) {
  55228. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55229. var boundingInfo = sm.getBoundingInfo();
  55230. return {
  55231. position: idx,
  55232. verticesStart: sm.verticesStart,
  55233. verticesCount: sm.verticesCount,
  55234. indexStart: sm.indexStart,
  55235. indexCount: sm.indexCount,
  55236. hasMaterial: !!sm.getMaterial(),
  55237. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55238. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55239. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55240. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55241. };
  55242. });
  55243. }
  55244. var geometryId = null;
  55245. if (mesh instanceof BABYLON.Mesh) {
  55246. var geometry = mesh.geometry;
  55247. geometryId = geometry ? geometry.id : null;
  55248. }
  55249. else if (mesh instanceof BABYLON.InstancedMesh) {
  55250. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55251. geometryId = geometry ? geometry.id : null;
  55252. }
  55253. var boundingInfo = mesh.getBoundingInfo();
  55254. return {
  55255. uniqueId: mesh.uniqueId,
  55256. id: mesh.id,
  55257. name: mesh.name,
  55258. geometryId: geometryId,
  55259. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55260. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55261. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55262. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55263. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55264. subMeshes: submeshes,
  55265. checkCollisions: mesh.checkCollisions
  55266. };
  55267. };
  55268. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55269. return {
  55270. id: geometry.id,
  55271. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55272. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55273. indices: new Uint32Array(geometry.getIndices() || []),
  55274. };
  55275. };
  55276. return CollisionCoordinatorWorker;
  55277. }());
  55278. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55279. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55280. function CollisionCoordinatorLegacy() {
  55281. this._scaledPosition = BABYLON.Vector3.Zero();
  55282. this._scaledVelocity = BABYLON.Vector3.Zero();
  55283. this._finalPosition = BABYLON.Vector3.Zero();
  55284. }
  55285. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55286. position.divideToRef(collider._radius, this._scaledPosition);
  55287. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55288. collider.collidedMesh = null;
  55289. collider._retry = 0;
  55290. collider._initialVelocity = this._scaledVelocity;
  55291. collider._initialPosition = this._scaledPosition;
  55292. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55293. this._finalPosition.multiplyInPlace(collider._radius);
  55294. //run the callback
  55295. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55296. };
  55297. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55298. this._scene = scene;
  55299. };
  55300. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55301. //Legacy need no destruction method.
  55302. };
  55303. //No update in legacy mode
  55304. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55305. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55306. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55307. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55308. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55309. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55310. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55311. if (excludedMesh === void 0) { excludedMesh = null; }
  55312. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55313. if (collider._retry >= maximumRetry) {
  55314. finalPosition.copyFrom(position);
  55315. return;
  55316. }
  55317. // Check if this is a mesh else camera or -1
  55318. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55319. collider._initialize(position, velocity, closeDistance);
  55320. // Check all meshes
  55321. for (var index = 0; index < this._scene.meshes.length; index++) {
  55322. var mesh = this._scene.meshes[index];
  55323. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55324. mesh._checkCollision(collider);
  55325. }
  55326. }
  55327. if (!collider.collisionFound) {
  55328. position.addToRef(velocity, finalPosition);
  55329. return;
  55330. }
  55331. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55332. collider._getResponse(position, velocity);
  55333. }
  55334. if (velocity.length() <= closeDistance) {
  55335. finalPosition.copyFrom(position);
  55336. return;
  55337. }
  55338. collider._retry++;
  55339. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55340. };
  55341. return CollisionCoordinatorLegacy;
  55342. }());
  55343. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55344. })(BABYLON || (BABYLON = {}));
  55345. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55346. var BABYLON;
  55347. (function (BABYLON) {
  55348. /**
  55349. * A particle represents one of the element emitted by a particle system.
  55350. * This is mainly define by its coordinates, direction, velocity and age.
  55351. */
  55352. var Particle = /** @class */ (function () {
  55353. /**
  55354. * Creates a new instance Particle
  55355. * @param particleSystem the particle system the particle belongs to
  55356. */
  55357. function Particle(
  55358. /**
  55359. * The particle system the particle belongs to.
  55360. */
  55361. particleSystem) {
  55362. this.particleSystem = particleSystem;
  55363. /**
  55364. * The world position of the particle in the scene.
  55365. */
  55366. this.position = BABYLON.Vector3.Zero();
  55367. /**
  55368. * The world direction of the particle in the scene.
  55369. */
  55370. this.direction = BABYLON.Vector3.Zero();
  55371. /**
  55372. * The color of the particle.
  55373. */
  55374. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55375. /**
  55376. * The color change of the particle per step.
  55377. */
  55378. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55379. /**
  55380. * Defines how long will the life of the particle be.
  55381. */
  55382. this.lifeTime = 1.0;
  55383. /**
  55384. * The current age of the particle.
  55385. */
  55386. this.age = 0;
  55387. /**
  55388. * The current size of the particle.
  55389. */
  55390. this.size = 0;
  55391. /**
  55392. * The current scale of the particle.
  55393. */
  55394. this.scale = new BABYLON.Vector2(1, 1);
  55395. /**
  55396. * The current angle of the particle.
  55397. */
  55398. this.angle = 0;
  55399. /**
  55400. * Defines how fast is the angle changing.
  55401. */
  55402. this.angularSpeed = 0;
  55403. /**
  55404. * Defines the cell index used by the particle to be rendered from a sprite.
  55405. */
  55406. this.cellIndex = 0;
  55407. /** @hidden */
  55408. this._attachedSubEmitters = null;
  55409. /** @hidden */
  55410. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55411. /** @hidden */
  55412. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55413. /** @hidden */
  55414. this._currentSize1 = 0;
  55415. /** @hidden */
  55416. this._currentSize2 = 0;
  55417. /** @hidden */
  55418. this._currentAngularSpeed1 = 0;
  55419. /** @hidden */
  55420. this._currentAngularSpeed2 = 0;
  55421. /** @hidden */
  55422. this._currentVelocity1 = 0;
  55423. /** @hidden */
  55424. this._currentVelocity2 = 0;
  55425. /** @hidden */
  55426. this._currentLimitVelocity1 = 0;
  55427. /** @hidden */
  55428. this._currentLimitVelocity2 = 0;
  55429. /** @hidden */
  55430. this._currentDrag1 = 0;
  55431. /** @hidden */
  55432. this._currentDrag2 = 0;
  55433. this.id = Particle._Count++;
  55434. if (!this.particleSystem.isAnimationSheetEnabled) {
  55435. return;
  55436. }
  55437. this.updateCellInfoFromSystem();
  55438. }
  55439. Particle.prototype.updateCellInfoFromSystem = function () {
  55440. this.cellIndex = this.particleSystem.startSpriteCellID;
  55441. };
  55442. /**
  55443. * Defines how the sprite cell index is updated for the particle
  55444. */
  55445. Particle.prototype.updateCellIndex = function () {
  55446. var offsetAge = this.age;
  55447. if (this.particleSystem.spriteRandomStartCell) {
  55448. if (this._randomCellOffset === undefined) {
  55449. this._randomCellOffset = Math.random() * this.lifeTime;
  55450. }
  55451. offsetAge += this._randomCellOffset;
  55452. }
  55453. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55454. var ratio = BABYLON.Scalar.Clamp(((offsetAge * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55455. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55456. };
  55457. /** @hidden */
  55458. Particle.prototype._reset = function () {
  55459. this.age = 0;
  55460. this._currentColorGradient = null;
  55461. this._currentSizeGradient = null;
  55462. this._currentAngularSpeedGradient = null;
  55463. this._currentVelocityGradient = null;
  55464. this._currentLimitVelocityGradient = null;
  55465. this._currentDragGradient = null;
  55466. this.cellIndex = this.particleSystem.startSpriteCellID;
  55467. this._randomCellOffset = undefined;
  55468. };
  55469. /**
  55470. * Copy the properties of particle to another one.
  55471. * @param other the particle to copy the information to.
  55472. */
  55473. Particle.prototype.copyTo = function (other) {
  55474. other.position.copyFrom(this.position);
  55475. if (this._initialDirection) {
  55476. if (other._initialDirection) {
  55477. other._initialDirection.copyFrom(this._initialDirection);
  55478. }
  55479. else {
  55480. other._initialDirection = this._initialDirection.clone();
  55481. }
  55482. }
  55483. else {
  55484. other._initialDirection = null;
  55485. }
  55486. other.direction.copyFrom(this.direction);
  55487. other.color.copyFrom(this.color);
  55488. other.colorStep.copyFrom(this.colorStep);
  55489. other.lifeTime = this.lifeTime;
  55490. other.age = this.age;
  55491. other._randomCellOffset = undefined;
  55492. other.size = this.size;
  55493. other.scale.copyFrom(this.scale);
  55494. other.angle = this.angle;
  55495. other.angularSpeed = this.angularSpeed;
  55496. other.particleSystem = this.particleSystem;
  55497. other.cellIndex = this.cellIndex;
  55498. other.id = this.id;
  55499. other._attachedSubEmitters = this._attachedSubEmitters;
  55500. if (this._currentColorGradient) {
  55501. other._currentColorGradient = this._currentColorGradient;
  55502. other._currentColor1.copyFrom(this._currentColor1);
  55503. other._currentColor2.copyFrom(this._currentColor2);
  55504. }
  55505. if (this._currentSizeGradient) {
  55506. other._currentSizeGradient = this._currentSizeGradient;
  55507. other._currentSize1 = this._currentSize1;
  55508. other._currentSize2 = this._currentSize2;
  55509. }
  55510. if (this._currentAngularSpeedGradient) {
  55511. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55512. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55513. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55514. }
  55515. if (this._currentVelocityGradient) {
  55516. other._currentVelocityGradient = this._currentVelocityGradient;
  55517. other._currentVelocity1 = this._currentVelocity1;
  55518. other._currentVelocity2 = this._currentVelocity2;
  55519. }
  55520. if (this._currentLimitVelocityGradient) {
  55521. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55522. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55523. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55524. }
  55525. if (this._currentDragGradient) {
  55526. other._currentDragGradient = this._currentDragGradient;
  55527. other._currentDrag1 = this._currentDrag1;
  55528. other._currentDrag2 = this._currentDrag2;
  55529. }
  55530. if (this.particleSystem.isAnimationSheetEnabled) {
  55531. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55532. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55533. }
  55534. if (this.particleSystem.useRampGradients) {
  55535. other.remapData.copyFrom(this.remapData);
  55536. }
  55537. };
  55538. Particle._Count = 0;
  55539. return Particle;
  55540. }());
  55541. BABYLON.Particle = Particle;
  55542. })(BABYLON || (BABYLON = {}));
  55543. //# sourceMappingURL=babylon.particle.js.map
  55544. var BABYLON;
  55545. (function (BABYLON) {
  55546. /**
  55547. * This represents the base class for particle system in Babylon.
  55548. * 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.
  55549. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55550. * @example https://doc.babylonjs.com/babylon101/particles
  55551. */
  55552. var BaseParticleSystem = /** @class */ (function () {
  55553. /**
  55554. * Instantiates a particle system.
  55555. * 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.
  55556. * @param name The name of the particle system
  55557. */
  55558. function BaseParticleSystem(name) {
  55559. /**
  55560. * List of animations used by the particle system.
  55561. */
  55562. this.animations = [];
  55563. /**
  55564. * The rendering group used by the Particle system to chose when to render.
  55565. */
  55566. this.renderingGroupId = 0;
  55567. /**
  55568. * The emitter represents the Mesh or position we are attaching the particle system to.
  55569. */
  55570. this.emitter = null;
  55571. /**
  55572. * The maximum number of particles to emit per frame
  55573. */
  55574. this.emitRate = 10;
  55575. /**
  55576. * If you want to launch only a few particles at once, that can be done, as well.
  55577. */
  55578. this.manualEmitCount = -1;
  55579. /**
  55580. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55581. */
  55582. this.updateSpeed = 0.01;
  55583. /**
  55584. * The amount of time the particle system is running (depends of the overall update speed).
  55585. */
  55586. this.targetStopDuration = 0;
  55587. /**
  55588. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55589. */
  55590. this.disposeOnStop = false;
  55591. /**
  55592. * Minimum power of emitting particles.
  55593. */
  55594. this.minEmitPower = 1;
  55595. /**
  55596. * Maximum power of emitting particles.
  55597. */
  55598. this.maxEmitPower = 1;
  55599. /**
  55600. * Minimum life time of emitting particles.
  55601. */
  55602. this.minLifeTime = 1;
  55603. /**
  55604. * Maximum life time of emitting particles.
  55605. */
  55606. this.maxLifeTime = 1;
  55607. /**
  55608. * Minimum Size of emitting particles.
  55609. */
  55610. this.minSize = 1;
  55611. /**
  55612. * Maximum Size of emitting particles.
  55613. */
  55614. this.maxSize = 1;
  55615. /**
  55616. * Minimum scale of emitting particles on X axis.
  55617. */
  55618. this.minScaleX = 1;
  55619. /**
  55620. * Maximum scale of emitting particles on X axis.
  55621. */
  55622. this.maxScaleX = 1;
  55623. /**
  55624. * Minimum scale of emitting particles on Y axis.
  55625. */
  55626. this.minScaleY = 1;
  55627. /**
  55628. * Maximum scale of emitting particles on Y axis.
  55629. */
  55630. this.maxScaleY = 1;
  55631. /**
  55632. * Gets or sets the minimal initial rotation in radians.
  55633. */
  55634. this.minInitialRotation = 0;
  55635. /**
  55636. * Gets or sets the maximal initial rotation in radians.
  55637. */
  55638. this.maxInitialRotation = 0;
  55639. /**
  55640. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55641. */
  55642. this.minAngularSpeed = 0;
  55643. /**
  55644. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55645. */
  55646. this.maxAngularSpeed = 0;
  55647. /**
  55648. * The layer mask we are rendering the particles through.
  55649. */
  55650. this.layerMask = 0x0FFFFFFF;
  55651. /**
  55652. * This can help using your own shader to render the particle system.
  55653. * The according effect will be created
  55654. */
  55655. this.customShader = null;
  55656. /**
  55657. * By default particle system starts as soon as they are created. This prevents the
  55658. * automatic start to happen and let you decide when to start emitting particles.
  55659. */
  55660. this.preventAutoStart = false;
  55661. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55662. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55663. /**
  55664. * Callback triggered when the particle animation is ending.
  55665. */
  55666. this.onAnimationEnd = null;
  55667. /**
  55668. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55669. */
  55670. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55671. /**
  55672. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55673. * to override the particles.
  55674. */
  55675. this.forceDepthWrite = false;
  55676. /** 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 */
  55677. this.preWarmCycles = 0;
  55678. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55679. this.preWarmStepOffset = 1;
  55680. /**
  55681. * 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)
  55682. */
  55683. this.spriteCellChangeSpeed = 1;
  55684. /**
  55685. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55686. */
  55687. this.startSpriteCellID = 0;
  55688. /**
  55689. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55690. */
  55691. this.endSpriteCellID = 0;
  55692. /**
  55693. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55694. */
  55695. this.spriteCellWidth = 0;
  55696. /**
  55697. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55698. */
  55699. this.spriteCellHeight = 0;
  55700. /**
  55701. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  55702. */
  55703. this.spriteRandomStartCell = false;
  55704. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55705. this.translationPivot = new BABYLON.Vector2(0, 0);
  55706. /**
  55707. * You can use gravity if you want to give an orientation to your particles.
  55708. */
  55709. this.gravity = BABYLON.Vector3.Zero();
  55710. this._colorGradients = null;
  55711. this._sizeGradients = null;
  55712. this._lifeTimeGradients = null;
  55713. this._angularSpeedGradients = null;
  55714. this._velocityGradients = null;
  55715. this._limitVelocityGradients = null;
  55716. this._dragGradients = null;
  55717. this._emitRateGradients = null;
  55718. this._startSizeGradients = null;
  55719. this._rampGradients = null;
  55720. this._colorRemapGradients = null;
  55721. this._alphaRemapGradients = null;
  55722. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55723. this.limitVelocityDamping = 0.4;
  55724. /**
  55725. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55726. */
  55727. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55728. /**
  55729. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55730. */
  55731. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55732. /**
  55733. * Color the particle will have at the end of its lifetime
  55734. */
  55735. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55736. /**
  55737. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55738. */
  55739. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55740. /**
  55741. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55742. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55743. */
  55744. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55745. this._isBillboardBased = true;
  55746. /**
  55747. * Local cache of defines for image processing.
  55748. */
  55749. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55750. this.id = name;
  55751. this.name = name;
  55752. }
  55753. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55754. /**
  55755. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55756. */
  55757. get: function () {
  55758. return this._isAnimationSheetEnabled;
  55759. },
  55760. set: function (value) {
  55761. if (this._isAnimationSheetEnabled == value) {
  55762. return;
  55763. }
  55764. this._isAnimationSheetEnabled = value;
  55765. this._reset();
  55766. },
  55767. enumerable: true,
  55768. configurable: true
  55769. });
  55770. /**
  55771. * Get hosting scene
  55772. * @returns the scene
  55773. */
  55774. BaseParticleSystem.prototype.getScene = function () {
  55775. return this._scene;
  55776. };
  55777. /**
  55778. * Gets the current list of drag gradients.
  55779. * You must use addDragGradient and removeDragGradient to udpate this list
  55780. * @returns the list of drag gradients
  55781. */
  55782. BaseParticleSystem.prototype.getDragGradients = function () {
  55783. return this._dragGradients;
  55784. };
  55785. /**
  55786. * Gets the current list of limit velocity gradients.
  55787. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55788. * @returns the list of limit velocity gradients
  55789. */
  55790. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55791. return this._limitVelocityGradients;
  55792. };
  55793. /**
  55794. * Gets the current list of color gradients.
  55795. * You must use addColorGradient and removeColorGradient to udpate this list
  55796. * @returns the list of color gradients
  55797. */
  55798. BaseParticleSystem.prototype.getColorGradients = function () {
  55799. return this._colorGradients;
  55800. };
  55801. /**
  55802. * Gets the current list of size gradients.
  55803. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55804. * @returns the list of size gradients
  55805. */
  55806. BaseParticleSystem.prototype.getSizeGradients = function () {
  55807. return this._sizeGradients;
  55808. };
  55809. /**
  55810. * Gets the current list of color remap gradients.
  55811. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  55812. * @returns the list of color remap gradients
  55813. */
  55814. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  55815. return this._colorRemapGradients;
  55816. };
  55817. /**
  55818. * Gets the current list of alpha remap gradients.
  55819. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  55820. * @returns the list of alpha remap gradients
  55821. */
  55822. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  55823. return this._alphaRemapGradients;
  55824. };
  55825. /**
  55826. * Gets the current list of life time gradients.
  55827. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55828. * @returns the list of life time gradients
  55829. */
  55830. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55831. return this._lifeTimeGradients;
  55832. };
  55833. /**
  55834. * Gets the current list of angular speed gradients.
  55835. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55836. * @returns the list of angular speed gradients
  55837. */
  55838. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55839. return this._angularSpeedGradients;
  55840. };
  55841. /**
  55842. * Gets the current list of velocity gradients.
  55843. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55844. * @returns the list of velocity gradients
  55845. */
  55846. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55847. return this._velocityGradients;
  55848. };
  55849. /**
  55850. * Gets the current list of start size gradients.
  55851. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  55852. * @returns the list of start size gradients
  55853. */
  55854. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  55855. return this._startSizeGradients;
  55856. };
  55857. /**
  55858. * Gets the current list of emit rate gradients.
  55859. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  55860. * @returns the list of emit rate gradients
  55861. */
  55862. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  55863. return this._emitRateGradients;
  55864. };
  55865. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55866. /**
  55867. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55868. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55869. */
  55870. get: function () {
  55871. if (this.particleEmitterType.direction1) {
  55872. return this.particleEmitterType.direction1;
  55873. }
  55874. return BABYLON.Vector3.Zero();
  55875. },
  55876. set: function (value) {
  55877. if (this.particleEmitterType.direction1) {
  55878. this.particleEmitterType.direction1 = value;
  55879. }
  55880. },
  55881. enumerable: true,
  55882. configurable: true
  55883. });
  55884. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55885. /**
  55886. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55887. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55888. */
  55889. get: function () {
  55890. if (this.particleEmitterType.direction2) {
  55891. return this.particleEmitterType.direction2;
  55892. }
  55893. return BABYLON.Vector3.Zero();
  55894. },
  55895. set: function (value) {
  55896. if (this.particleEmitterType.direction2) {
  55897. this.particleEmitterType.direction2 = value;
  55898. }
  55899. },
  55900. enumerable: true,
  55901. configurable: true
  55902. });
  55903. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55904. /**
  55905. * 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.
  55906. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55907. */
  55908. get: function () {
  55909. if (this.particleEmitterType.minEmitBox) {
  55910. return this.particleEmitterType.minEmitBox;
  55911. }
  55912. return BABYLON.Vector3.Zero();
  55913. },
  55914. set: function (value) {
  55915. if (this.particleEmitterType.minEmitBox) {
  55916. this.particleEmitterType.minEmitBox = value;
  55917. }
  55918. },
  55919. enumerable: true,
  55920. configurable: true
  55921. });
  55922. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55923. /**
  55924. * 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.
  55925. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55926. */
  55927. get: function () {
  55928. if (this.particleEmitterType.maxEmitBox) {
  55929. return this.particleEmitterType.maxEmitBox;
  55930. }
  55931. return BABYLON.Vector3.Zero();
  55932. },
  55933. set: function (value) {
  55934. if (this.particleEmitterType.maxEmitBox) {
  55935. this.particleEmitterType.maxEmitBox = value;
  55936. }
  55937. },
  55938. enumerable: true,
  55939. configurable: true
  55940. });
  55941. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55942. /**
  55943. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55944. */
  55945. get: function () {
  55946. return this._isBillboardBased;
  55947. },
  55948. set: function (value) {
  55949. if (this._isBillboardBased === value) {
  55950. return;
  55951. }
  55952. this._isBillboardBased = value;
  55953. this._reset();
  55954. },
  55955. enumerable: true,
  55956. configurable: true
  55957. });
  55958. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  55959. /**
  55960. * Gets the image processing configuration used either in this material.
  55961. */
  55962. get: function () {
  55963. return this._imageProcessingConfiguration;
  55964. },
  55965. /**
  55966. * Sets the Default image processing configuration used either in the this material.
  55967. *
  55968. * If sets to null, the scene one is in use.
  55969. */
  55970. set: function (value) {
  55971. this._attachImageProcessingConfiguration(value);
  55972. },
  55973. enumerable: true,
  55974. configurable: true
  55975. });
  55976. /**
  55977. * Attaches a new image processing configuration to the Standard Material.
  55978. * @param configuration
  55979. */
  55980. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  55981. if (configuration === this._imageProcessingConfiguration) {
  55982. return;
  55983. }
  55984. // Pick the scene configuration if needed.
  55985. if (!configuration) {
  55986. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  55987. }
  55988. else {
  55989. this._imageProcessingConfiguration = configuration;
  55990. }
  55991. };
  55992. /** @hidden */
  55993. BaseParticleSystem.prototype._reset = function () {
  55994. };
  55995. /** @hidden */
  55996. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  55997. if (!gradients) {
  55998. return this;
  55999. }
  56000. var index = 0;
  56001. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  56002. var valueGradient = gradients_1[_i];
  56003. if (valueGradient.gradient === gradient) {
  56004. gradients.splice(index, 1);
  56005. break;
  56006. }
  56007. index++;
  56008. }
  56009. if (texture) {
  56010. texture.dispose();
  56011. }
  56012. return this;
  56013. };
  56014. /**
  56015. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  56016. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56017. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56018. * @returns the emitter
  56019. */
  56020. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  56021. var particleEmitter = new BABYLON.PointParticleEmitter();
  56022. particleEmitter.direction1 = direction1;
  56023. particleEmitter.direction2 = direction2;
  56024. this.particleEmitterType = particleEmitter;
  56025. return particleEmitter;
  56026. };
  56027. /**
  56028. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  56029. * @param radius The radius of the hemisphere to emit from
  56030. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56031. * @returns the emitter
  56032. */
  56033. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  56034. if (radius === void 0) { radius = 1; }
  56035. if (radiusRange === void 0) { radiusRange = 1; }
  56036. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  56037. this.particleEmitterType = particleEmitter;
  56038. return particleEmitter;
  56039. };
  56040. /**
  56041. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  56042. * @param radius The radius of the sphere to emit from
  56043. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56044. * @returns the emitter
  56045. */
  56046. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56047. if (radius === void 0) { radius = 1; }
  56048. if (radiusRange === void 0) { radiusRange = 1; }
  56049. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56050. this.particleEmitterType = particleEmitter;
  56051. return particleEmitter;
  56052. };
  56053. /**
  56054. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  56055. * @param radius The radius of the sphere to emit from
  56056. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56057. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56058. * @returns the emitter
  56059. */
  56060. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56061. if (radius === void 0) { radius = 1; }
  56062. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56063. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56064. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56065. this.particleEmitterType = particleEmitter;
  56066. return particleEmitter;
  56067. };
  56068. /**
  56069. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  56070. * @param radius The radius of the emission cylinder
  56071. * @param height The height of the emission cylinder
  56072. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  56073. * @param directionRandomizer How much to randomize the particle direction [0-1]
  56074. * @returns the emitter
  56075. */
  56076. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  56077. if (radius === void 0) { radius = 1; }
  56078. if (height === void 0) { height = 1; }
  56079. if (radiusRange === void 0) { radiusRange = 1; }
  56080. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56081. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  56082. this.particleEmitterType = particleEmitter;
  56083. return particleEmitter;
  56084. };
  56085. /**
  56086. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  56087. * @param radius The radius of the cylinder to emit from
  56088. * @param height The height of the emission cylinder
  56089. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  56090. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  56091. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  56092. * @returns the emitter
  56093. */
  56094. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  56095. if (radius === void 0) { radius = 1; }
  56096. if (height === void 0) { height = 1; }
  56097. if (radiusRange === void 0) { radiusRange = 1; }
  56098. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56099. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56100. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  56101. this.particleEmitterType = particleEmitter;
  56102. return particleEmitter;
  56103. };
  56104. /**
  56105. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  56106. * @param radius The radius of the cone to emit from
  56107. * @param angle The base angle of the cone
  56108. * @returns the emitter
  56109. */
  56110. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56111. if (radius === void 0) { radius = 1; }
  56112. if (angle === void 0) { angle = Math.PI / 4; }
  56113. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56114. this.particleEmitterType = particleEmitter;
  56115. return particleEmitter;
  56116. };
  56117. /**
  56118. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56119. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56120. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56121. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56122. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56123. * @returns the emitter
  56124. */
  56125. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56126. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56127. this.particleEmitterType = particleEmitter;
  56128. this.direction1 = direction1;
  56129. this.direction2 = direction2;
  56130. this.minEmitBox = minEmitBox;
  56131. this.maxEmitBox = maxEmitBox;
  56132. return particleEmitter;
  56133. };
  56134. /**
  56135. * Source color is added to the destination color without alpha affecting the result.
  56136. */
  56137. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  56138. /**
  56139. * Blend current color and particle color using particle’s alpha.
  56140. */
  56141. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  56142. /**
  56143. * Add current color and particle color multiplied by particle’s alpha.
  56144. */
  56145. BaseParticleSystem.BLENDMODE_ADD = 2;
  56146. /**
  56147. * Multiply current color with particle color
  56148. */
  56149. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  56150. return BaseParticleSystem;
  56151. }());
  56152. BABYLON.BaseParticleSystem = BaseParticleSystem;
  56153. })(BABYLON || (BABYLON = {}));
  56154. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  56155. var BABYLON;
  56156. (function (BABYLON) {
  56157. /**
  56158. * This represents a particle system in Babylon.
  56159. * 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.
  56160. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56161. * @example https://doc.babylonjs.com/babylon101/particles
  56162. */
  56163. var ParticleSystem = /** @class */ (function (_super) {
  56164. __extends(ParticleSystem, _super);
  56165. /**
  56166. * Instantiates a particle system.
  56167. * 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.
  56168. * @param name The name of the particle system
  56169. * @param capacity The max number of particles alive at the same time
  56170. * @param scene The scene the particle system belongs to
  56171. * @param customEffect a custom effect used to change the way particles are rendered by default
  56172. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56173. * @param epsilon Offset used to render the particles
  56174. */
  56175. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56176. if (customEffect === void 0) { customEffect = null; }
  56177. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56178. if (epsilon === void 0) { epsilon = 0.01; }
  56179. var _this = _super.call(this, name) || this;
  56180. /**
  56181. * @hidden
  56182. */
  56183. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  56184. /**
  56185. * An event triggered when the system is disposed
  56186. */
  56187. _this.onDisposeObservable = new BABYLON.Observable();
  56188. _this._particles = new Array();
  56189. _this._stockParticles = new Array();
  56190. _this._newPartsExcess = 0;
  56191. _this._vertexBuffers = {};
  56192. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56193. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56194. _this._scaledDirection = BABYLON.Vector3.Zero();
  56195. _this._scaledGravity = BABYLON.Vector3.Zero();
  56196. _this._currentRenderId = -1;
  56197. _this._useInstancing = false;
  56198. _this._started = false;
  56199. _this._stopped = false;
  56200. _this._actualFrame = 0;
  56201. /** @hidden */
  56202. _this._currentEmitRate1 = 0;
  56203. /** @hidden */
  56204. _this._currentEmitRate2 = 0;
  56205. /** @hidden */
  56206. _this._currentStartSize1 = 0;
  56207. /** @hidden */
  56208. _this._currentStartSize2 = 0;
  56209. _this._rawTextureWidth = 256;
  56210. _this._useRampGradients = false;
  56211. /**
  56212. * @hidden
  56213. * If the particle systems emitter should be disposed when the particle system is disposed
  56214. */
  56215. _this._disposeEmitterOnDispose = false;
  56216. // start of sub system methods
  56217. /**
  56218. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56219. * Its lifetime will start back at 0.
  56220. */
  56221. _this.recycleParticle = function (particle) {
  56222. // move particle from activeParticle list to stock particles
  56223. var lastParticle = _this._particles.pop();
  56224. if (lastParticle !== particle) {
  56225. lastParticle.copyTo(particle);
  56226. }
  56227. _this._stockParticles.push(lastParticle);
  56228. };
  56229. _this._createParticle = function () {
  56230. var particle;
  56231. if (_this._stockParticles.length !== 0) {
  56232. particle = _this._stockParticles.pop();
  56233. particle._reset();
  56234. }
  56235. else {
  56236. particle = new BABYLON.Particle(_this);
  56237. }
  56238. // Attach emitters
  56239. if (_this._subEmitters && _this._subEmitters.length > 0) {
  56240. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  56241. particle._attachedSubEmitters = [];
  56242. subEmitters.forEach(function (subEmitter) {
  56243. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  56244. var newEmitter = subEmitter.clone();
  56245. particle._attachedSubEmitters.push(newEmitter);
  56246. newEmitter.particleSystem.start();
  56247. }
  56248. });
  56249. }
  56250. return particle;
  56251. };
  56252. _this._emitFromParticle = function (particle) {
  56253. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  56254. return;
  56255. }
  56256. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  56257. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  56258. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  56259. var subSystem = subEmitter.clone();
  56260. ParticleSystem._InheritParticleInfoToSubEmitter(subSystem, particle);
  56261. subSystem.particleSystem._rootParticleSystem = _this;
  56262. _this.activeSubSystems.push(subSystem.particleSystem);
  56263. subSystem.particleSystem.start();
  56264. }
  56265. });
  56266. };
  56267. _this._capacity = capacity;
  56268. _this._epsilon = epsilon;
  56269. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56270. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56271. // Setup the default processing configuration to the scene.
  56272. _this._attachImageProcessingConfiguration(null);
  56273. _this._customEffect = customEffect;
  56274. _this._scene.particleSystems.push(_this);
  56275. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56276. _this._createIndexBuffer();
  56277. _this._createVertexBuffers();
  56278. // Default emitter type
  56279. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56280. _this.updateFunction = function (particles) {
  56281. var noiseTextureData = null;
  56282. var noiseTextureSize = null;
  56283. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56284. noiseTextureData = (_this.noiseTexture.readPixels());
  56285. noiseTextureSize = _this.noiseTexture.getSize();
  56286. }
  56287. var _loop_1 = function () {
  56288. particle = particles[index];
  56289. particle.age += _this._scaledUpdateSpeed;
  56290. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56291. _this._emitFromParticle(particle);
  56292. if (particle._attachedSubEmitters) {
  56293. particle._attachedSubEmitters.forEach(function (subEmitter) {
  56294. subEmitter.particleSystem.disposeOnStop = true;
  56295. subEmitter.particleSystem.stop();
  56296. });
  56297. particle._attachedSubEmitters = null;
  56298. }
  56299. _this.recycleParticle(particle);
  56300. index--;
  56301. return "continue";
  56302. }
  56303. else {
  56304. var ratio = particle.age / particle.lifeTime;
  56305. // Color
  56306. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56307. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56308. if (currentGradient !== particle._currentColorGradient) {
  56309. particle._currentColor1.copyFrom(particle._currentColor2);
  56310. nextGradient.getColorToRef(particle._currentColor2);
  56311. particle._currentColorGradient = currentGradient;
  56312. }
  56313. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56314. });
  56315. }
  56316. else {
  56317. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56318. particle.color.addInPlace(_this._scaledColorStep);
  56319. if (particle.color.a < 0) {
  56320. particle.color.a = 0;
  56321. }
  56322. }
  56323. // Angular speed
  56324. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56325. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56326. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56327. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56328. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56329. particle._currentAngularSpeedGradient = currentGradient;
  56330. }
  56331. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56332. });
  56333. }
  56334. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56335. // Direction
  56336. var directionScale_1 = _this._scaledUpdateSpeed;
  56337. /// Velocity
  56338. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56339. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56340. if (currentGradient !== particle._currentVelocityGradient) {
  56341. particle._currentVelocity1 = particle._currentVelocity2;
  56342. particle._currentVelocity2 = nextGradient.getFactor();
  56343. particle._currentVelocityGradient = currentGradient;
  56344. }
  56345. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56346. });
  56347. }
  56348. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56349. /// Limit velocity
  56350. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56351. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56352. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56353. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56354. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56355. particle._currentLimitVelocityGradient = currentGradient;
  56356. }
  56357. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56358. var currentVelocity = particle.direction.length();
  56359. if (currentVelocity > limitVelocity) {
  56360. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56361. }
  56362. });
  56363. }
  56364. /// Drag
  56365. if (_this._dragGradients && _this._dragGradients.length > 0) {
  56366. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  56367. if (currentGradient !== particle._currentDragGradient) {
  56368. particle._currentDrag1 = particle._currentDrag2;
  56369. particle._currentDrag2 = nextGradient.getFactor();
  56370. particle._currentDragGradient = currentGradient;
  56371. }
  56372. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  56373. _this._scaledDirection.scaleInPlace(1.0 - drag);
  56374. });
  56375. }
  56376. particle.position.addInPlace(_this._scaledDirection);
  56377. // Noise
  56378. if (noiseTextureData && noiseTextureSize) {
  56379. var localPosition = BABYLON.Tmp.Vector3[0];
  56380. var emitterPosition = BABYLON.Tmp.Vector3[1];
  56381. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  56382. particle.position.subtractToRef(emitterPosition, localPosition);
  56383. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56384. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56385. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56386. var force = BABYLON.Tmp.Vector3[0];
  56387. var scaledForce = BABYLON.Tmp.Vector3[1];
  56388. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56389. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56390. particle.direction.addInPlace(scaledForce);
  56391. }
  56392. // Gravity
  56393. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56394. particle.direction.addInPlace(_this._scaledGravity);
  56395. // Size
  56396. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56397. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56398. if (currentGradient !== particle._currentSizeGradient) {
  56399. particle._currentSize1 = particle._currentSize2;
  56400. particle._currentSize2 = nextGradient.getFactor();
  56401. particle._currentSizeGradient = currentGradient;
  56402. }
  56403. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56404. });
  56405. }
  56406. // Remap data
  56407. if (_this._useRampGradients) {
  56408. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  56409. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  56410. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56411. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56412. particle.remapData.x = min;
  56413. particle.remapData.y = max - min;
  56414. });
  56415. }
  56416. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  56417. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  56418. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56419. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56420. particle.remapData.z = min;
  56421. particle.remapData.w = max - min;
  56422. });
  56423. }
  56424. }
  56425. if (_this._isAnimationSheetEnabled) {
  56426. particle.updateCellIndex();
  56427. }
  56428. // Update the position of the attached sub-emitters to match their attached particle
  56429. if (particle._attachedSubEmitters && particle._attachedSubEmitters.length > 0) {
  56430. particle._attachedSubEmitters.forEach(function (subEmitter) {
  56431. ParticleSystem._InheritParticleInfoToSubEmitter(subEmitter, particle);
  56432. });
  56433. }
  56434. }
  56435. };
  56436. var particle;
  56437. for (var index = 0; index < particles.length; index++) {
  56438. _loop_1();
  56439. }
  56440. };
  56441. return _this;
  56442. }
  56443. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56444. /**
  56445. * Sets a callback that will be triggered when the system is disposed
  56446. */
  56447. set: function (callback) {
  56448. if (this._onDisposeObserver) {
  56449. this.onDisposeObservable.remove(this._onDisposeObserver);
  56450. }
  56451. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56452. },
  56453. enumerable: true,
  56454. configurable: true
  56455. });
  56456. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  56457. /** Gets or sets a boolean indicating that ramp gradients must be used
  56458. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  56459. */
  56460. get: function () {
  56461. return this._useRampGradients;
  56462. },
  56463. set: function (value) {
  56464. if (this._useRampGradients === value) {
  56465. return;
  56466. }
  56467. this._useRampGradients = value;
  56468. this._resetEffect();
  56469. },
  56470. enumerable: true,
  56471. configurable: true
  56472. });
  56473. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56474. //end of Sub-emitter
  56475. /**
  56476. * Gets the current list of active particles
  56477. */
  56478. get: function () {
  56479. return this._particles;
  56480. },
  56481. enumerable: true,
  56482. configurable: true
  56483. });
  56484. /**
  56485. * Returns the string "ParticleSystem"
  56486. * @returns a string containing the class name
  56487. */
  56488. ParticleSystem.prototype.getClassName = function () {
  56489. return "ParticleSystem";
  56490. };
  56491. ParticleSystem._InheritParticleInfoToSubEmitter = function (subEmitter, particle) {
  56492. if (subEmitter.particleSystem.emitter.position) {
  56493. var emitterMesh = subEmitter.particleSystem.emitter;
  56494. emitterMesh.position.copyFrom(particle.position);
  56495. if (subEmitter.inheritDirection) {
  56496. emitterMesh.position.subtractToRef(particle.direction, BABYLON.Tmp.Vector3[0]);
  56497. // Look at using Y as forward
  56498. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56499. }
  56500. }
  56501. else {
  56502. var emitterPosition = subEmitter.particleSystem.emitter;
  56503. emitterPosition.copyFrom(particle.position);
  56504. if (subEmitter.inheritDirection) {
  56505. BABYLON.Tools.Warn("subEmitter.inheritDirection is not supported with non-mesh emitter type");
  56506. }
  56507. }
  56508. // Set inheritedVelocityOffset to be used when new particles are created
  56509. particle.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56510. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56511. };
  56512. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56513. var newGradient = new BABYLON.FactorGradient();
  56514. newGradient.gradient = gradient;
  56515. newGradient.factor1 = factor;
  56516. newGradient.factor2 = factor2;
  56517. factorGradients.push(newGradient);
  56518. factorGradients.sort(function (a, b) {
  56519. if (a.gradient < b.gradient) {
  56520. return -1;
  56521. }
  56522. else if (a.gradient > b.gradient) {
  56523. return 1;
  56524. }
  56525. return 0;
  56526. });
  56527. };
  56528. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56529. if (!factorGradients) {
  56530. return;
  56531. }
  56532. var index = 0;
  56533. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56534. var factorGradient = factorGradients_1[_i];
  56535. if (factorGradient.gradient === gradient) {
  56536. factorGradients.splice(index, 1);
  56537. break;
  56538. }
  56539. index++;
  56540. }
  56541. };
  56542. /**
  56543. * Adds a new life time gradient
  56544. * @param gradient defines the gradient to use (between 0 and 1)
  56545. * @param factor defines the life time factor to affect to the specified gradient
  56546. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56547. * @returns the current particle system
  56548. */
  56549. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56550. if (!this._lifeTimeGradients) {
  56551. this._lifeTimeGradients = [];
  56552. }
  56553. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56554. return this;
  56555. };
  56556. /**
  56557. * Remove a specific life time gradient
  56558. * @param gradient defines the gradient to remove
  56559. * @returns the current particle system
  56560. */
  56561. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56562. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56563. return this;
  56564. };
  56565. /**
  56566. * Adds a new size gradient
  56567. * @param gradient defines the gradient to use (between 0 and 1)
  56568. * @param factor defines the size factor to affect to the specified gradient
  56569. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56570. * @returns the current particle system
  56571. */
  56572. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56573. if (!this._sizeGradients) {
  56574. this._sizeGradients = [];
  56575. }
  56576. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56577. return this;
  56578. };
  56579. /**
  56580. * Remove a specific size gradient
  56581. * @param gradient defines the gradient to remove
  56582. * @returns the current particle system
  56583. */
  56584. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56585. this._removeFactorGradient(this._sizeGradients, gradient);
  56586. return this;
  56587. };
  56588. /**
  56589. * Adds a new color remap gradient
  56590. * @param gradient defines the gradient to use (between 0 and 1)
  56591. * @param min defines the color remap minimal range
  56592. * @param max defines the color remap maximal range
  56593. * @returns the current particle system
  56594. */
  56595. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  56596. if (!this._colorRemapGradients) {
  56597. this._colorRemapGradients = [];
  56598. }
  56599. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  56600. return this;
  56601. };
  56602. /**
  56603. * Remove a specific color remap gradient
  56604. * @param gradient defines the gradient to remove
  56605. * @returns the current particle system
  56606. */
  56607. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  56608. this._removeFactorGradient(this._colorRemapGradients, gradient);
  56609. return this;
  56610. };
  56611. /**
  56612. * Adds a new alpha remap gradient
  56613. * @param gradient defines the gradient to use (between 0 and 1)
  56614. * @param min defines the alpha remap minimal range
  56615. * @param max defines the alpha remap maximal range
  56616. * @returns the current particle system
  56617. */
  56618. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  56619. if (!this._alphaRemapGradients) {
  56620. this._alphaRemapGradients = [];
  56621. }
  56622. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  56623. return this;
  56624. };
  56625. /**
  56626. * Remove a specific alpha remap gradient
  56627. * @param gradient defines the gradient to remove
  56628. * @returns the current particle system
  56629. */
  56630. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  56631. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  56632. return this;
  56633. };
  56634. /**
  56635. * Adds a new angular speed gradient
  56636. * @param gradient defines the gradient to use (between 0 and 1)
  56637. * @param factor defines the angular speed to affect to the specified gradient
  56638. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56639. * @returns the current particle system
  56640. */
  56641. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56642. if (!this._angularSpeedGradients) {
  56643. this._angularSpeedGradients = [];
  56644. }
  56645. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56646. return this;
  56647. };
  56648. /**
  56649. * Remove a specific angular speed gradient
  56650. * @param gradient defines the gradient to remove
  56651. * @returns the current particle system
  56652. */
  56653. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56654. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56655. return this;
  56656. };
  56657. /**
  56658. * Adds a new velocity gradient
  56659. * @param gradient defines the gradient to use (between 0 and 1)
  56660. * @param factor defines the velocity to affect to the specified gradient
  56661. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56662. * @returns the current particle system
  56663. */
  56664. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56665. if (!this._velocityGradients) {
  56666. this._velocityGradients = [];
  56667. }
  56668. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56669. return this;
  56670. };
  56671. /**
  56672. * Remove a specific velocity gradient
  56673. * @param gradient defines the gradient to remove
  56674. * @returns the current particle system
  56675. */
  56676. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56677. this._removeFactorGradient(this._velocityGradients, gradient);
  56678. return this;
  56679. };
  56680. /**
  56681. * Adds a new limit velocity gradient
  56682. * @param gradient defines the gradient to use (between 0 and 1)
  56683. * @param factor defines the limit velocity value to affect to the specified gradient
  56684. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56685. * @returns the current particle system
  56686. */
  56687. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56688. if (!this._limitVelocityGradients) {
  56689. this._limitVelocityGradients = [];
  56690. }
  56691. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56692. return this;
  56693. };
  56694. /**
  56695. * Remove a specific limit velocity gradient
  56696. * @param gradient defines the gradient to remove
  56697. * @returns the current particle system
  56698. */
  56699. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56700. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56701. return this;
  56702. };
  56703. /**
  56704. * Adds a new drag gradient
  56705. * @param gradient defines the gradient to use (between 0 and 1)
  56706. * @param factor defines the drag value to affect to the specified gradient
  56707. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56708. * @returns the current particle system
  56709. */
  56710. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  56711. if (!this._dragGradients) {
  56712. this._dragGradients = [];
  56713. }
  56714. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  56715. return this;
  56716. };
  56717. /**
  56718. * Remove a specific drag gradient
  56719. * @param gradient defines the gradient to remove
  56720. * @returns the current particle system
  56721. */
  56722. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  56723. this._removeFactorGradient(this._dragGradients, gradient);
  56724. return this;
  56725. };
  56726. /**
  56727. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  56728. * @param gradient defines the gradient to use (between 0 and 1)
  56729. * @param factor defines the emit rate value to affect to the specified gradient
  56730. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56731. * @returns the current particle system
  56732. */
  56733. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  56734. if (!this._emitRateGradients) {
  56735. this._emitRateGradients = [];
  56736. }
  56737. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  56738. if (!this._currentEmitRateGradient) {
  56739. this._currentEmitRateGradient = this._emitRateGradients[0];
  56740. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  56741. this._currentEmitRate2 = this._currentEmitRate1;
  56742. }
  56743. if (this._emitRateGradients.length === 2) {
  56744. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  56745. }
  56746. return this;
  56747. };
  56748. /**
  56749. * Remove a specific emit rate gradient
  56750. * @param gradient defines the gradient to remove
  56751. * @returns the current particle system
  56752. */
  56753. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  56754. this._removeFactorGradient(this._emitRateGradients, gradient);
  56755. return this;
  56756. };
  56757. /**
  56758. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  56759. * @param gradient defines the gradient to use (between 0 and 1)
  56760. * @param factor defines the start size value to affect to the specified gradient
  56761. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56762. * @returns the current particle system
  56763. */
  56764. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  56765. if (!this._startSizeGradients) {
  56766. this._startSizeGradients = [];
  56767. }
  56768. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  56769. if (!this._currentStartSizeGradient) {
  56770. this._currentStartSizeGradient = this._startSizeGradients[0];
  56771. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  56772. this._currentStartSize2 = this._currentStartSize1;
  56773. }
  56774. if (this._startSizeGradients.length === 2) {
  56775. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  56776. }
  56777. return this;
  56778. };
  56779. /**
  56780. * Remove a specific start size gradient
  56781. * @param gradient defines the gradient to remove
  56782. * @returns the current particle system
  56783. */
  56784. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  56785. this._removeFactorGradient(this._emitRateGradients, gradient);
  56786. return this;
  56787. };
  56788. ParticleSystem.prototype._createRampGradientTexture = function () {
  56789. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  56790. return;
  56791. }
  56792. var data = new Uint8Array(this._rawTextureWidth * 4);
  56793. var tmpColor = BABYLON.Tmp.Color3[0];
  56794. for (var x = 0; x < this._rawTextureWidth; x++) {
  56795. var ratio = x / this._rawTextureWidth;
  56796. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  56797. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  56798. data[x * 4] = tmpColor.r * 255;
  56799. data[x * 4 + 1] = tmpColor.g * 255;
  56800. data[x * 4 + 2] = tmpColor.b * 255;
  56801. data[x * 4 + 3] = 255;
  56802. });
  56803. }
  56804. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  56805. };
  56806. /**
  56807. * Gets the current list of ramp gradients.
  56808. * You must use addRampGradient and removeRampGradient to udpate this list
  56809. * @returns the list of ramp gradients
  56810. */
  56811. ParticleSystem.prototype.getRampGradients = function () {
  56812. return this._rampGradients;
  56813. };
  56814. /**
  56815. * Adds a new ramp gradient used to remap particle colors
  56816. * @param gradient defines the gradient to use (between 0 and 1)
  56817. * @param color defines the color to affect to the specified gradient
  56818. * @returns the current particle system
  56819. */
  56820. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  56821. if (!this._rampGradients) {
  56822. this._rampGradients = [];
  56823. }
  56824. var rampGradient = new BABYLON.Color3Gradient();
  56825. rampGradient.gradient = gradient;
  56826. rampGradient.color = color;
  56827. this._rampGradients.push(rampGradient);
  56828. this._rampGradients.sort(function (a, b) {
  56829. if (a.gradient < b.gradient) {
  56830. return -1;
  56831. }
  56832. else if (a.gradient > b.gradient) {
  56833. return 1;
  56834. }
  56835. return 0;
  56836. });
  56837. if (this._rampGradientsTexture) {
  56838. this._rampGradientsTexture.dispose();
  56839. this._rampGradientsTexture = null;
  56840. }
  56841. this._createRampGradientTexture();
  56842. return this;
  56843. };
  56844. /**
  56845. * Remove a specific ramp gradient
  56846. * @param gradient defines the gradient to remove
  56847. * @returns the current particle system
  56848. */
  56849. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  56850. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  56851. this._rampGradientsTexture = null;
  56852. if (this._rampGradients && this._rampGradients.length > 0) {
  56853. this._createRampGradientTexture();
  56854. }
  56855. return this;
  56856. };
  56857. /**
  56858. * Adds a new color gradient
  56859. * @param gradient defines the gradient to use (between 0 and 1)
  56860. * @param color defines the color to affect to the specified gradient
  56861. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56862. */
  56863. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56864. if (!this._colorGradients) {
  56865. this._colorGradients = [];
  56866. }
  56867. var colorGradient = new BABYLON.ColorGradient();
  56868. colorGradient.gradient = gradient;
  56869. colorGradient.color1 = color;
  56870. colorGradient.color2 = color2;
  56871. this._colorGradients.push(colorGradient);
  56872. this._colorGradients.sort(function (a, b) {
  56873. if (a.gradient < b.gradient) {
  56874. return -1;
  56875. }
  56876. else if (a.gradient > b.gradient) {
  56877. return 1;
  56878. }
  56879. return 0;
  56880. });
  56881. return this;
  56882. };
  56883. /**
  56884. * Remove a specific color gradient
  56885. * @param gradient defines the gradient to remove
  56886. */
  56887. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56888. if (!this._colorGradients) {
  56889. return this;
  56890. }
  56891. var index = 0;
  56892. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56893. var colorGradient = _a[_i];
  56894. if (colorGradient.gradient === gradient) {
  56895. this._colorGradients.splice(index, 1);
  56896. break;
  56897. }
  56898. index++;
  56899. }
  56900. return this;
  56901. };
  56902. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56903. u = Math.abs(u) * 0.5 + 0.5;
  56904. v = Math.abs(v) * 0.5 + 0.5;
  56905. var wrappedU = ((u * width) % width) | 0;
  56906. var wrappedV = ((v * height) % height) | 0;
  56907. var position = (wrappedU + wrappedV * width) * 4;
  56908. return pixels[position] / 255;
  56909. };
  56910. ParticleSystem.prototype._reset = function () {
  56911. this._resetEffect();
  56912. };
  56913. ParticleSystem.prototype._resetEffect = function () {
  56914. if (this._vertexBuffer) {
  56915. this._vertexBuffer.dispose();
  56916. this._vertexBuffer = null;
  56917. }
  56918. if (this._spriteBuffer) {
  56919. this._spriteBuffer.dispose();
  56920. this._spriteBuffer = null;
  56921. }
  56922. this._createVertexBuffers();
  56923. };
  56924. ParticleSystem.prototype._createVertexBuffers = function () {
  56925. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56926. if (this._isAnimationSheetEnabled) {
  56927. this._vertexBufferSize += 1;
  56928. }
  56929. if (!this._isBillboardBased) {
  56930. this._vertexBufferSize += 3;
  56931. }
  56932. if (this._useRampGradients) {
  56933. this._vertexBufferSize += 4;
  56934. }
  56935. var engine = this._scene.getEngine();
  56936. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56937. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56938. var dataOffset = 0;
  56939. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56940. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56941. dataOffset += 3;
  56942. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56943. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56944. dataOffset += 4;
  56945. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56946. this._vertexBuffers["angle"] = options;
  56947. dataOffset += 1;
  56948. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56949. this._vertexBuffers["size"] = size;
  56950. dataOffset += 2;
  56951. if (this._isAnimationSheetEnabled) {
  56952. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56953. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56954. dataOffset += 1;
  56955. }
  56956. if (!this._isBillboardBased) {
  56957. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56958. this._vertexBuffers["direction"] = directionBuffer;
  56959. dataOffset += 3;
  56960. }
  56961. if (this._useRampGradients) {
  56962. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56963. this._vertexBuffers["remapData"] = rampDataBuffer;
  56964. dataOffset += 4;
  56965. }
  56966. var offsets;
  56967. if (this._useInstancing) {
  56968. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56969. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56970. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56971. }
  56972. else {
  56973. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56974. dataOffset += 2;
  56975. }
  56976. this._vertexBuffers["offset"] = offsets;
  56977. };
  56978. ParticleSystem.prototype._createIndexBuffer = function () {
  56979. if (this._useInstancing) {
  56980. return;
  56981. }
  56982. var indices = [];
  56983. var index = 0;
  56984. for (var count = 0; count < this._capacity; count++) {
  56985. indices.push(index);
  56986. indices.push(index + 1);
  56987. indices.push(index + 2);
  56988. indices.push(index);
  56989. indices.push(index + 2);
  56990. indices.push(index + 3);
  56991. index += 4;
  56992. }
  56993. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56994. };
  56995. /**
  56996. * Gets the maximum number of particles active at the same time.
  56997. * @returns The max number of active particles.
  56998. */
  56999. ParticleSystem.prototype.getCapacity = function () {
  57000. return this._capacity;
  57001. };
  57002. /**
  57003. * Gets whether there are still active particles in the system.
  57004. * @returns True if it is alive, otherwise false.
  57005. */
  57006. ParticleSystem.prototype.isAlive = function () {
  57007. return this._alive;
  57008. };
  57009. /**
  57010. * Gets if the system has been started. (Note: this will still be true after stop is called)
  57011. * @returns True if it has been started, otherwise false.
  57012. */
  57013. ParticleSystem.prototype.isStarted = function () {
  57014. return this._started;
  57015. };
  57016. /**
  57017. * Starts the particle system and begins to emit
  57018. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  57019. */
  57020. ParticleSystem.prototype.start = function (delay) {
  57021. var _this = this;
  57022. if (delay === void 0) { delay = 0; }
  57023. if (delay) {
  57024. setTimeout(function () {
  57025. _this.start(0);
  57026. }, delay);
  57027. return;
  57028. }
  57029. // Convert the subEmitters field to the constant type field _subEmitters
  57030. this._subEmitters = new Array();
  57031. if (this.subEmitters) {
  57032. this.subEmitters.forEach(function (subEmitter) {
  57033. if (subEmitter instanceof ParticleSystem) {
  57034. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  57035. }
  57036. else if (subEmitter instanceof BABYLON.SubEmitter) {
  57037. _this._subEmitters.push([subEmitter]);
  57038. }
  57039. else if (subEmitter instanceof Array) {
  57040. _this._subEmitters.push(subEmitter);
  57041. }
  57042. });
  57043. }
  57044. this._started = true;
  57045. this._stopped = false;
  57046. this._actualFrame = 0;
  57047. if (this._subEmitters && this._subEmitters.length != 0) {
  57048. this.activeSubSystems = new Array();
  57049. }
  57050. if (this.preWarmCycles) {
  57051. for (var index = 0; index < this.preWarmCycles; index++) {
  57052. this.animate(true);
  57053. }
  57054. }
  57055. };
  57056. /**
  57057. * Stops the particle system.
  57058. * @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.
  57059. */
  57060. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  57061. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  57062. this._stopped = true;
  57063. if (stopSubEmitters) {
  57064. this._stopSubEmitters();
  57065. }
  57066. };
  57067. // animation sheet
  57068. /**
  57069. * Remove all active particles
  57070. */
  57071. ParticleSystem.prototype.reset = function () {
  57072. this._stockParticles = [];
  57073. this._particles = [];
  57074. };
  57075. /**
  57076. * @hidden (for internal use only)
  57077. */
  57078. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  57079. var offset = index * this._vertexBufferSize;
  57080. this._vertexData[offset++] = particle.position.x;
  57081. this._vertexData[offset++] = particle.position.y;
  57082. this._vertexData[offset++] = particle.position.z;
  57083. this._vertexData[offset++] = particle.color.r;
  57084. this._vertexData[offset++] = particle.color.g;
  57085. this._vertexData[offset++] = particle.color.b;
  57086. this._vertexData[offset++] = particle.color.a;
  57087. this._vertexData[offset++] = particle.angle;
  57088. this._vertexData[offset++] = particle.scale.x * particle.size;
  57089. this._vertexData[offset++] = particle.scale.y * particle.size;
  57090. if (this._isAnimationSheetEnabled) {
  57091. this._vertexData[offset++] = particle.cellIndex;
  57092. }
  57093. if (!this._isBillboardBased) {
  57094. if (particle._initialDirection) {
  57095. this._vertexData[offset++] = particle._initialDirection.x;
  57096. this._vertexData[offset++] = particle._initialDirection.y;
  57097. this._vertexData[offset++] = particle._initialDirection.z;
  57098. }
  57099. else {
  57100. this._vertexData[offset++] = particle.direction.x;
  57101. this._vertexData[offset++] = particle.direction.y;
  57102. this._vertexData[offset++] = particle.direction.z;
  57103. }
  57104. }
  57105. if (!this._useInstancing) {
  57106. if (this._isAnimationSheetEnabled) {
  57107. if (offsetX === 0)
  57108. offsetX = this._epsilon;
  57109. else if (offsetX === 1)
  57110. offsetX = 1 - this._epsilon;
  57111. if (offsetY === 0)
  57112. offsetY = this._epsilon;
  57113. else if (offsetY === 1)
  57114. offsetY = 1 - this._epsilon;
  57115. }
  57116. this._vertexData[offset++] = offsetX;
  57117. this._vertexData[offset++] = offsetY;
  57118. }
  57119. if (this._useRampGradients) {
  57120. this._vertexData[offset++] = particle.remapData.x;
  57121. this._vertexData[offset++] = particle.remapData.y;
  57122. this._vertexData[offset++] = particle.remapData.z;
  57123. this._vertexData[offset++] = particle.remapData.w;
  57124. }
  57125. };
  57126. ParticleSystem.prototype._stopSubEmitters = function () {
  57127. if (!this.activeSubSystems) {
  57128. return;
  57129. }
  57130. this.activeSubSystems.forEach(function (subSystem) {
  57131. subSystem.stop(true);
  57132. });
  57133. this.activeSubSystems = new Array();
  57134. };
  57135. ParticleSystem.prototype._removeFromRoot = function () {
  57136. if (!this._rootParticleSystem) {
  57137. return;
  57138. }
  57139. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  57140. if (index !== -1) {
  57141. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  57142. }
  57143. };
  57144. // End of sub system methods
  57145. ParticleSystem.prototype._update = function (newParticles) {
  57146. var _this = this;
  57147. // Update current
  57148. this._alive = this._particles.length > 0;
  57149. if (this.emitter.position) {
  57150. var emitterMesh = this.emitter;
  57151. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  57152. }
  57153. else {
  57154. var emitterPosition = this.emitter;
  57155. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57156. }
  57157. this.updateFunction(this._particles);
  57158. // Add new ones
  57159. var particle;
  57160. var _loop_2 = function () {
  57161. if (this_1._particles.length === this_1._capacity) {
  57162. return "break";
  57163. }
  57164. particle = this_1._createParticle();
  57165. this_1._particles.push(particle);
  57166. // Emitter
  57167. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  57168. if (this_1.startPositionFunction) {
  57169. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  57170. }
  57171. else {
  57172. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  57173. }
  57174. if (this_1.startDirectionFunction) {
  57175. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  57176. }
  57177. else {
  57178. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  57179. }
  57180. if (emitPower === 0) {
  57181. if (!particle._initialDirection) {
  57182. particle._initialDirection = particle.direction.clone();
  57183. }
  57184. else {
  57185. particle._initialDirection.copyFrom(particle.direction);
  57186. }
  57187. }
  57188. else {
  57189. particle._initialDirection = null;
  57190. }
  57191. particle.direction.scaleInPlace(emitPower);
  57192. // Life time
  57193. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  57194. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  57195. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  57196. var factorGradient1 = currentGradient;
  57197. var factorGradient2 = nextGradient;
  57198. var lifeTime1 = factorGradient1.getFactor();
  57199. var lifeTime2 = factorGradient2.getFactor();
  57200. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  57201. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  57202. });
  57203. }
  57204. else {
  57205. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  57206. }
  57207. // Size
  57208. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  57209. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  57210. }
  57211. else {
  57212. particle._currentSizeGradient = this_1._sizeGradients[0];
  57213. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  57214. particle.size = particle._currentSize1;
  57215. if (this_1._sizeGradients.length > 1) {
  57216. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  57217. }
  57218. else {
  57219. particle._currentSize2 = particle._currentSize1;
  57220. }
  57221. }
  57222. // Size and scale
  57223. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  57224. // Adjust scale by start size
  57225. if (this_1._startSizeGradients && this_1._startSizeGradients[0]) {
  57226. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  57227. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  57228. if (currentGradient !== _this._currentStartSizeGradient) {
  57229. _this._currentStartSize1 = _this._currentStartSize2;
  57230. _this._currentStartSize2 = nextGradient.getFactor();
  57231. _this._currentStartSizeGradient = currentGradient;
  57232. }
  57233. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  57234. particle.scale.scaleInPlace(value);
  57235. });
  57236. }
  57237. // Angle
  57238. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  57239. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  57240. }
  57241. else {
  57242. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  57243. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  57244. particle._currentAngularSpeed1 = particle.angularSpeed;
  57245. if (this_1._angularSpeedGradients.length > 1) {
  57246. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  57247. }
  57248. else {
  57249. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  57250. }
  57251. }
  57252. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  57253. // Velocity
  57254. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  57255. particle._currentVelocityGradient = this_1._velocityGradients[0];
  57256. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  57257. if (this_1._velocityGradients.length > 1) {
  57258. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  57259. }
  57260. else {
  57261. particle._currentVelocity2 = particle._currentVelocity1;
  57262. }
  57263. }
  57264. // Limit velocity
  57265. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  57266. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  57267. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  57268. if (this_1._limitVelocityGradients.length > 1) {
  57269. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  57270. }
  57271. else {
  57272. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  57273. }
  57274. }
  57275. // Drag
  57276. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  57277. particle._currentDragGradient = this_1._dragGradients[0];
  57278. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  57279. if (this_1._dragGradients.length > 1) {
  57280. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  57281. }
  57282. else {
  57283. particle._currentDrag2 = particle._currentDrag1;
  57284. }
  57285. }
  57286. // Color
  57287. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  57288. step = BABYLON.Scalar.RandomRange(0, 1.0);
  57289. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  57290. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  57291. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  57292. }
  57293. else {
  57294. particle._currentColorGradient = this_1._colorGradients[0];
  57295. particle._currentColorGradient.getColorToRef(particle.color);
  57296. particle._currentColor1.copyFrom(particle.color);
  57297. if (this_1._colorGradients.length > 1) {
  57298. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  57299. }
  57300. else {
  57301. particle._currentColor2.copyFrom(particle.color);
  57302. }
  57303. }
  57304. // Sheet
  57305. if (this_1._isAnimationSheetEnabled) {
  57306. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  57307. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  57308. }
  57309. // Inherited Velocity
  57310. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  57311. // Ramp
  57312. if (this_1._useRampGradients) {
  57313. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  57314. }
  57315. };
  57316. var this_1 = this, step;
  57317. for (var index = 0; index < newParticles; index++) {
  57318. var state_1 = _loop_2();
  57319. if (state_1 === "break")
  57320. break;
  57321. }
  57322. };
  57323. /** @hidden */
  57324. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  57325. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57326. if (isBillboardBased === void 0) { isBillboardBased = false; }
  57327. if (useRampGradients === void 0) { useRampGradients = false; }
  57328. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  57329. if (isAnimationSheetEnabled) {
  57330. attributeNamesOrOptions.push("cellIndex");
  57331. }
  57332. if (!isBillboardBased) {
  57333. attributeNamesOrOptions.push("direction");
  57334. }
  57335. if (useRampGradients) {
  57336. attributeNamesOrOptions.push("remapData");
  57337. }
  57338. return attributeNamesOrOptions;
  57339. };
  57340. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  57341. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57342. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  57343. if (isAnimationSheetEnabled) {
  57344. effectCreationOption.push("particlesInfos");
  57345. }
  57346. return effectCreationOption;
  57347. };
  57348. ParticleSystem.prototype._getEffect = function () {
  57349. if (this._customEffect) {
  57350. return this._customEffect;
  57351. }
  57352. ;
  57353. var defines = [];
  57354. if (this._scene.clipPlane) {
  57355. defines.push("#define CLIPPLANE");
  57356. }
  57357. if (this._scene.clipPlane2) {
  57358. defines.push("#define CLIPPLANE2");
  57359. }
  57360. if (this._scene.clipPlane3) {
  57361. defines.push("#define CLIPPLANE3");
  57362. }
  57363. if (this._scene.clipPlane4) {
  57364. defines.push("#define CLIPPLANE4");
  57365. }
  57366. if (this._isAnimationSheetEnabled) {
  57367. defines.push("#define ANIMATESHEET");
  57368. }
  57369. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  57370. defines.push("#define BLENDMULTIPLYMODE");
  57371. }
  57372. if (this._useRampGradients) {
  57373. defines.push("#define RAMPGRADIENT");
  57374. }
  57375. if (this._isBillboardBased) {
  57376. defines.push("#define BILLBOARD");
  57377. switch (this.billboardMode) {
  57378. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57379. defines.push("#define BILLBOARDY");
  57380. break;
  57381. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57382. default:
  57383. break;
  57384. }
  57385. }
  57386. if (this._imageProcessingConfiguration) {
  57387. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  57388. defines.push(this._imageProcessingConfigurationDefines.toString());
  57389. }
  57390. // Effect
  57391. var join = defines.join("\n");
  57392. if (this._cachedDefines !== join) {
  57393. this._cachedDefines = join;
  57394. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased, this._useRampGradients);
  57395. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  57396. var samplers = ["diffuseSampler", "rampSampler"];
  57397. if (BABYLON.ImageProcessingConfiguration) {
  57398. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  57399. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  57400. }
  57401. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  57402. }
  57403. return this._effect;
  57404. };
  57405. /**
  57406. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57407. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  57408. */
  57409. ParticleSystem.prototype.animate = function (preWarmOnly) {
  57410. var _this = this;
  57411. if (preWarmOnly === void 0) { preWarmOnly = false; }
  57412. if (!this._started)
  57413. return;
  57414. if (!preWarmOnly) {
  57415. var effect = this._getEffect();
  57416. // Check
  57417. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  57418. return;
  57419. if (this._currentRenderId === this._scene.getRenderId()) {
  57420. return;
  57421. }
  57422. this._currentRenderId = this._scene.getRenderId();
  57423. }
  57424. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57425. // Determine the number of particles we need to create
  57426. var newParticles;
  57427. if (this.manualEmitCount > -1) {
  57428. newParticles = this.manualEmitCount;
  57429. this._newPartsExcess = 0;
  57430. this.manualEmitCount = 0;
  57431. }
  57432. else {
  57433. var rate_1 = this.emitRate;
  57434. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  57435. var ratio = this._actualFrame / this.targetStopDuration;
  57436. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  57437. if (currentGradient !== _this._currentEmitRateGradient) {
  57438. _this._currentEmitRate1 = _this._currentEmitRate2;
  57439. _this._currentEmitRate2 = nextGradient.getFactor();
  57440. _this._currentEmitRateGradient = currentGradient;
  57441. }
  57442. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  57443. });
  57444. }
  57445. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  57446. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  57447. }
  57448. if (this._newPartsExcess > 1.0) {
  57449. newParticles += this._newPartsExcess >> 0;
  57450. this._newPartsExcess -= this._newPartsExcess >> 0;
  57451. }
  57452. this._alive = false;
  57453. if (!this._stopped) {
  57454. this._actualFrame += this._scaledUpdateSpeed;
  57455. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  57456. this.stop();
  57457. }
  57458. else {
  57459. newParticles = 0;
  57460. }
  57461. this._update(newParticles);
  57462. // Stopped?
  57463. if (this._stopped) {
  57464. if (!this._alive) {
  57465. this._started = false;
  57466. if (this.onAnimationEnd) {
  57467. this.onAnimationEnd();
  57468. }
  57469. if (this.disposeOnStop) {
  57470. this._scene._toBeDisposed.push(this);
  57471. }
  57472. }
  57473. }
  57474. if (!preWarmOnly) {
  57475. // Update VBO
  57476. var offset = 0;
  57477. for (var index = 0; index < this._particles.length; index++) {
  57478. var particle = this._particles[index];
  57479. this._appendParticleVertices(offset, particle);
  57480. offset += this._useInstancing ? 1 : 4;
  57481. }
  57482. if (this._vertexBuffer) {
  57483. this._vertexBuffer.update(this._vertexData);
  57484. }
  57485. }
  57486. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57487. this.stop();
  57488. }
  57489. };
  57490. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57491. this._appendParticleVertex(offset++, particle, 0, 0);
  57492. if (!this._useInstancing) {
  57493. this._appendParticleVertex(offset++, particle, 1, 0);
  57494. this._appendParticleVertex(offset++, particle, 1, 1);
  57495. this._appendParticleVertex(offset++, particle, 0, 1);
  57496. }
  57497. };
  57498. /**
  57499. * Rebuilds the particle system.
  57500. */
  57501. ParticleSystem.prototype.rebuild = function () {
  57502. this._createIndexBuffer();
  57503. if (this._vertexBuffer) {
  57504. this._vertexBuffer._rebuild();
  57505. }
  57506. };
  57507. /**
  57508. * Is this system ready to be used/rendered
  57509. * @return true if the system is ready
  57510. */
  57511. ParticleSystem.prototype.isReady = function () {
  57512. var effect = this._getEffect();
  57513. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57514. return false;
  57515. }
  57516. return true;
  57517. };
  57518. /**
  57519. * Renders the particle system in its current state.
  57520. * @returns the current number of particles
  57521. */
  57522. ParticleSystem.prototype.render = function () {
  57523. var effect = this._getEffect();
  57524. // Check
  57525. if (!this.isReady() || !this._particles.length) {
  57526. return 0;
  57527. }
  57528. var engine = this._scene.getEngine();
  57529. // Render
  57530. engine.enableEffect(effect);
  57531. engine.setState(false);
  57532. var viewMatrix = this._scene.getViewMatrix();
  57533. effect.setTexture("diffuseSampler", this.particleTexture);
  57534. effect.setMatrix("view", viewMatrix);
  57535. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57536. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57537. var baseSize = this.particleTexture.getBaseSize();
  57538. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57539. }
  57540. effect.setVector2("translationPivot", this.translationPivot);
  57541. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57542. if (this._isBillboardBased) {
  57543. var camera = this._scene.activeCamera;
  57544. effect.setVector3("eyePosition", camera.globalPosition);
  57545. }
  57546. if (this._rampGradientsTexture) {
  57547. effect.setTexture("rampSampler", this._rampGradientsTexture);
  57548. }
  57549. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57550. var invView = viewMatrix.clone();
  57551. invView.invert();
  57552. effect.setMatrix("invView", invView);
  57553. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57554. }
  57555. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57556. // image processing
  57557. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57558. this._imageProcessingConfiguration.bind(effect);
  57559. }
  57560. // Draw order
  57561. switch (this.blendMode) {
  57562. case ParticleSystem.BLENDMODE_ADD:
  57563. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57564. break;
  57565. case ParticleSystem.BLENDMODE_ONEONE:
  57566. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57567. break;
  57568. case ParticleSystem.BLENDMODE_STANDARD:
  57569. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57570. break;
  57571. case ParticleSystem.BLENDMODE_MULTIPLY:
  57572. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  57573. break;
  57574. }
  57575. if (this.forceDepthWrite) {
  57576. engine.setDepthWrite(true);
  57577. }
  57578. if (this._useInstancing) {
  57579. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57580. engine.unbindInstanceAttributes();
  57581. }
  57582. else {
  57583. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57584. }
  57585. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57586. return this._particles.length;
  57587. };
  57588. /**
  57589. * Disposes the particle system and free the associated resources
  57590. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57591. */
  57592. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57593. if (disposeTexture === void 0) { disposeTexture = true; }
  57594. if (this._vertexBuffer) {
  57595. this._vertexBuffer.dispose();
  57596. this._vertexBuffer = null;
  57597. }
  57598. if (this._spriteBuffer) {
  57599. this._spriteBuffer.dispose();
  57600. this._spriteBuffer = null;
  57601. }
  57602. if (this._indexBuffer) {
  57603. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57604. this._indexBuffer = null;
  57605. }
  57606. if (disposeTexture && this.particleTexture) {
  57607. this.particleTexture.dispose();
  57608. this.particleTexture = null;
  57609. }
  57610. if (disposeTexture && this.noiseTexture) {
  57611. this.noiseTexture.dispose();
  57612. this.noiseTexture = null;
  57613. }
  57614. this._removeFromRoot();
  57615. if (this._disposeEmitterOnDispose && !this.emitter.isDisposed) {
  57616. this.emitter.dispose();
  57617. }
  57618. // Remove from scene
  57619. var index = this._scene.particleSystems.indexOf(this);
  57620. if (index > -1) {
  57621. this._scene.particleSystems.splice(index, 1);
  57622. }
  57623. // Callback
  57624. this.onDisposeObservable.notifyObservers(this);
  57625. this.onDisposeObservable.clear();
  57626. };
  57627. // Clone
  57628. /**
  57629. * Clones the particle system.
  57630. * @param name The name of the cloned object
  57631. * @param newEmitter The new emitter to use
  57632. * @returns the cloned particle system
  57633. */
  57634. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57635. var custom = null;
  57636. var program = null;
  57637. if (this.customShader != null) {
  57638. program = this.customShader;
  57639. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57640. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57641. }
  57642. else if (this._customEffect) {
  57643. custom = this._customEffect;
  57644. }
  57645. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57646. result.customShader = program;
  57647. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57648. if (newEmitter === undefined) {
  57649. newEmitter = this.emitter;
  57650. }
  57651. result.emitter = newEmitter;
  57652. if (this.particleTexture) {
  57653. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57654. }
  57655. // Clone gradients
  57656. if (this._colorGradients) {
  57657. this._colorGradients.forEach(function (v) {
  57658. result.addColorGradient(v.gradient, v.color1, v.color2);
  57659. });
  57660. }
  57661. if (this._dragGradients) {
  57662. this._dragGradients.forEach(function (v) {
  57663. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  57664. });
  57665. }
  57666. if (this._angularSpeedGradients) {
  57667. this._angularSpeedGradients.forEach(function (v) {
  57668. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  57669. });
  57670. }
  57671. if (this._emitRateGradients) {
  57672. this._emitRateGradients.forEach(function (v) {
  57673. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  57674. });
  57675. }
  57676. if (this._lifeTimeGradients) {
  57677. this._lifeTimeGradients.forEach(function (v) {
  57678. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  57679. });
  57680. }
  57681. if (this._limitVelocityGradients) {
  57682. this._limitVelocityGradients.forEach(function (v) {
  57683. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  57684. });
  57685. }
  57686. if (this._sizeGradients) {
  57687. this._sizeGradients.forEach(function (v) {
  57688. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  57689. });
  57690. }
  57691. if (this._startSizeGradients) {
  57692. this._startSizeGradients.forEach(function (v) {
  57693. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  57694. });
  57695. }
  57696. if (this._velocityGradients) {
  57697. this._velocityGradients.forEach(function (v) {
  57698. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  57699. });
  57700. }
  57701. if (this._rampGradients) {
  57702. this._rampGradients.forEach(function (v) {
  57703. result.addRampGradient(v.gradient, v.color);
  57704. });
  57705. }
  57706. if (this._colorRemapGradients) {
  57707. this._colorRemapGradients.forEach(function (v) {
  57708. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  57709. });
  57710. }
  57711. if (this._alphaRemapGradients) {
  57712. this._alphaRemapGradients.forEach(function (v) {
  57713. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  57714. });
  57715. }
  57716. if (!this.preventAutoStart) {
  57717. result.start();
  57718. }
  57719. return result;
  57720. };
  57721. /**
  57722. * Serializes the particle system to a JSON object.
  57723. * @returns the JSON object
  57724. */
  57725. ParticleSystem.prototype.serialize = function () {
  57726. var serializationObject = {};
  57727. ParticleSystem._Serialize(serializationObject, this);
  57728. serializationObject.textureMask = this.textureMask.asArray();
  57729. serializationObject.customShader = this.customShader;
  57730. serializationObject.preventAutoStart = this.preventAutoStart;
  57731. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57732. return serializationObject;
  57733. };
  57734. /** @hidden */
  57735. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57736. serializationObject.name = particleSystem.name;
  57737. serializationObject.id = particleSystem.id;
  57738. serializationObject.capacity = particleSystem.getCapacity();
  57739. // Emitter
  57740. if (particleSystem.emitter.position) {
  57741. var emitterMesh = particleSystem.emitter;
  57742. serializationObject.emitterId = emitterMesh.id;
  57743. }
  57744. else {
  57745. var emitterPosition = particleSystem.emitter;
  57746. serializationObject.emitter = emitterPosition.asArray();
  57747. }
  57748. // Emitter
  57749. if (particleSystem.particleEmitterType) {
  57750. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57751. }
  57752. if (particleSystem.particleTexture) {
  57753. serializationObject.textureName = particleSystem.particleTexture.name;
  57754. }
  57755. // Animations
  57756. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57757. // Particle system
  57758. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57759. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57760. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57761. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57762. serializationObject.minSize = particleSystem.minSize;
  57763. serializationObject.maxSize = particleSystem.maxSize;
  57764. serializationObject.minScaleX = particleSystem.minScaleX;
  57765. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57766. serializationObject.minScaleY = particleSystem.minScaleY;
  57767. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57768. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57769. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57770. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57771. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57772. serializationObject.emitRate = particleSystem.emitRate;
  57773. serializationObject.gravity = particleSystem.gravity.asArray();
  57774. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57775. serializationObject.color1 = particleSystem.color1.asArray();
  57776. serializationObject.color2 = particleSystem.color2.asArray();
  57777. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57778. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57779. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57780. serializationObject.blendMode = particleSystem.blendMode;
  57781. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57782. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57783. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57784. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57785. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57786. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57787. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57788. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57789. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57790. var colorGradients = particleSystem.getColorGradients();
  57791. if (colorGradients) {
  57792. serializationObject.colorGradients = [];
  57793. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57794. var colorGradient = colorGradients_1[_i];
  57795. var serializedGradient = {
  57796. gradient: colorGradient.gradient,
  57797. color1: colorGradient.color1.asArray()
  57798. };
  57799. if (colorGradient.color2) {
  57800. serializedGradient.color2 = colorGradient.color2.asArray();
  57801. }
  57802. serializationObject.colorGradients.push(serializedGradient);
  57803. }
  57804. }
  57805. var rampGradients = particleSystem.getRampGradients();
  57806. if (rampGradients) {
  57807. serializationObject.rampGradients = [];
  57808. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  57809. var rampGradient = rampGradients_1[_a];
  57810. var serializedGradient = {
  57811. gradient: rampGradient.gradient,
  57812. color: rampGradient.color.asArray()
  57813. };
  57814. serializationObject.rampGradients.push(serializedGradient);
  57815. }
  57816. }
  57817. var colorRemapGradients = particleSystem.getColorRemapGradients();
  57818. if (colorRemapGradients) {
  57819. serializationObject.colorRemapGradients = [];
  57820. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  57821. var colorRemapGradient = colorRemapGradients_1[_b];
  57822. var serializedGradient = {
  57823. gradient: colorRemapGradient.gradient,
  57824. factor1: colorRemapGradient.factor1
  57825. };
  57826. if (colorRemapGradient.factor2 !== undefined) {
  57827. serializedGradient.factor2 = colorRemapGradient.factor2;
  57828. }
  57829. serializationObject.colorRemapGradients.push(serializedGradient);
  57830. }
  57831. }
  57832. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  57833. if (alphaRemapGradients) {
  57834. serializationObject.alphaRemapGradients = [];
  57835. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  57836. var alphaRemapGradient = alphaRemapGradients_1[_c];
  57837. var serializedGradient = {
  57838. gradient: alphaRemapGradient.gradient,
  57839. factor1: alphaRemapGradient.factor1
  57840. };
  57841. if (alphaRemapGradient.factor2 !== undefined) {
  57842. serializedGradient.factor2 = alphaRemapGradient.factor2;
  57843. }
  57844. serializationObject.alphaRemapGradients.push(serializedGradient);
  57845. }
  57846. }
  57847. var sizeGradients = particleSystem.getSizeGradients();
  57848. if (sizeGradients) {
  57849. serializationObject.sizeGradients = [];
  57850. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  57851. var sizeGradient = sizeGradients_1[_d];
  57852. var serializedGradient = {
  57853. gradient: sizeGradient.gradient,
  57854. factor1: sizeGradient.factor1
  57855. };
  57856. if (sizeGradient.factor2 !== undefined) {
  57857. serializedGradient.factor2 = sizeGradient.factor2;
  57858. }
  57859. serializationObject.sizeGradients.push(serializedGradient);
  57860. }
  57861. }
  57862. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57863. if (angularSpeedGradients) {
  57864. serializationObject.angularSpeedGradients = [];
  57865. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  57866. var angularSpeedGradient = angularSpeedGradients_1[_e];
  57867. var serializedGradient = {
  57868. gradient: angularSpeedGradient.gradient,
  57869. factor1: angularSpeedGradient.factor1
  57870. };
  57871. if (angularSpeedGradient.factor2 !== undefined) {
  57872. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57873. }
  57874. serializationObject.angularSpeedGradients.push(serializedGradient);
  57875. }
  57876. }
  57877. var velocityGradients = particleSystem.getVelocityGradients();
  57878. if (velocityGradients) {
  57879. serializationObject.velocityGradients = [];
  57880. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  57881. var velocityGradient = velocityGradients_1[_f];
  57882. var serializedGradient = {
  57883. gradient: velocityGradient.gradient,
  57884. factor1: velocityGradient.factor1
  57885. };
  57886. if (velocityGradient.factor2 !== undefined) {
  57887. serializedGradient.factor2 = velocityGradient.factor2;
  57888. }
  57889. serializationObject.velocityGradients.push(serializedGradient);
  57890. }
  57891. }
  57892. var dragGradients = particleSystem.getDragGradients();
  57893. if (dragGradients) {
  57894. serializationObject.dragyGradients = [];
  57895. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  57896. var dragGradient = dragGradients_1[_g];
  57897. var serializedGradient = {
  57898. gradient: dragGradient.gradient,
  57899. factor1: dragGradient.factor1
  57900. };
  57901. if (dragGradient.factor2 !== undefined) {
  57902. serializedGradient.factor2 = dragGradient.factor2;
  57903. }
  57904. serializationObject.dragGradients.push(serializedGradient);
  57905. }
  57906. }
  57907. var emitRateGradients = particleSystem.getEmitRateGradients();
  57908. if (emitRateGradients) {
  57909. serializationObject.emitRateGradients = [];
  57910. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  57911. var emitRateGradient = emitRateGradients_1[_h];
  57912. var serializedGradient = {
  57913. gradient: emitRateGradient.gradient,
  57914. factor1: emitRateGradient.factor1
  57915. };
  57916. if (emitRateGradient.factor2 !== undefined) {
  57917. serializedGradient.factor2 = emitRateGradient.factor2;
  57918. }
  57919. serializationObject.emitRateGradients.push(serializedGradient);
  57920. }
  57921. }
  57922. var startSizeGradients = particleSystem.getStartSizeGradients();
  57923. if (startSizeGradients) {
  57924. serializationObject.startSizeGradients = [];
  57925. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  57926. var startSizeGradient = startSizeGradients_1[_j];
  57927. var serializedGradient = {
  57928. gradient: startSizeGradient.gradient,
  57929. factor1: startSizeGradient.factor1
  57930. };
  57931. if (startSizeGradient.factor2 !== undefined) {
  57932. serializedGradient.factor2 = startSizeGradient.factor2;
  57933. }
  57934. serializationObject.startSizeGradients.push(serializedGradient);
  57935. }
  57936. }
  57937. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57938. if (limitVelocityGradients) {
  57939. serializationObject.limitVelocityGradients = [];
  57940. for (var _k = 0, limitVelocityGradients_1 = limitVelocityGradients; _k < limitVelocityGradients_1.length; _k++) {
  57941. var limitVelocityGradient = limitVelocityGradients_1[_k];
  57942. var serializedGradient = {
  57943. gradient: limitVelocityGradient.gradient,
  57944. factor1: limitVelocityGradient.factor1
  57945. };
  57946. if (limitVelocityGradient.factor2 !== undefined) {
  57947. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57948. }
  57949. serializationObject.limitVelocityGradients.push(serializedGradient);
  57950. }
  57951. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57952. }
  57953. if (BABYLON.ProceduralTexture && particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  57954. var noiseTexture = particleSystem.noiseTexture;
  57955. serializationObject.noiseTexture = noiseTexture.serialize();
  57956. }
  57957. };
  57958. /** @hidden */
  57959. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  57960. // Texture
  57961. if (parsedParticleSystem.textureName) {
  57962. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57963. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57964. }
  57965. // Emitter
  57966. if (parsedParticleSystem.emitterId === undefined) {
  57967. particleSystem.emitter = BABYLON.Vector3.Zero();
  57968. }
  57969. else if (parsedParticleSystem.emitterId) {
  57970. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57971. }
  57972. else {
  57973. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57974. }
  57975. // Misc.
  57976. if (parsedParticleSystem.renderingGroupId !== undefined) {
  57977. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  57978. }
  57979. if (parsedParticleSystem.isBillboardBased !== undefined) {
  57980. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  57981. }
  57982. // Animations
  57983. if (parsedParticleSystem.animations) {
  57984. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57985. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57986. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57987. }
  57988. }
  57989. if (parsedParticleSystem.autoAnimate) {
  57990. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57991. }
  57992. // Particle system
  57993. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57994. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57995. particleSystem.minSize = parsedParticleSystem.minSize;
  57996. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57997. if (parsedParticleSystem.minScaleX) {
  57998. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57999. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  58000. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  58001. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  58002. }
  58003. if (parsedParticleSystem.preWarmCycles !== undefined) {
  58004. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  58005. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  58006. }
  58007. if (parsedParticleSystem.minInitialRotation !== undefined) {
  58008. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  58009. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  58010. }
  58011. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58012. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58013. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58014. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58015. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58016. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58017. if (parsedParticleSystem.noiseStrength) {
  58018. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  58019. }
  58020. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58021. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58022. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58023. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58024. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58025. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58026. if (parsedParticleSystem.colorGradients) {
  58027. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  58028. var colorGradient = _a[_i];
  58029. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  58030. }
  58031. }
  58032. if (parsedParticleSystem.rampGradients) {
  58033. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  58034. var rampGradient = _c[_b];
  58035. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color1));
  58036. }
  58037. }
  58038. if (parsedParticleSystem.colorRemapGradients) {
  58039. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  58040. var colorRemapGradient = _e[_d];
  58041. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  58042. }
  58043. }
  58044. if (parsedParticleSystem.alphaRemapGradients) {
  58045. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  58046. var alphaRemapGradient = _g[_f];
  58047. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  58048. }
  58049. }
  58050. if (parsedParticleSystem.sizeGradients) {
  58051. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  58052. var sizeGradient = _j[_h];
  58053. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  58054. }
  58055. }
  58056. if (parsedParticleSystem.sizeGradients) {
  58057. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  58058. var sizeGradient = _l[_k];
  58059. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  58060. }
  58061. }
  58062. if (parsedParticleSystem.angularSpeedGradients) {
  58063. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  58064. var angularSpeedGradient = _o[_m];
  58065. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  58066. }
  58067. }
  58068. if (parsedParticleSystem.velocityGradients) {
  58069. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  58070. var velocityGradient = _q[_p];
  58071. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  58072. }
  58073. }
  58074. if (parsedParticleSystem.dragGradients) {
  58075. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  58076. var dragGradient = _s[_r];
  58077. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  58078. }
  58079. }
  58080. if (parsedParticleSystem.emitRateGradients) {
  58081. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  58082. var emitRateGradient = _u[_t];
  58083. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  58084. }
  58085. }
  58086. if (parsedParticleSystem.startSizeGradients) {
  58087. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  58088. var startSizeGradient = _w[_v];
  58089. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  58090. }
  58091. }
  58092. if (parsedParticleSystem.limitVelocityGradients) {
  58093. for (var _x = 0, _y = parsedParticleSystem.limitVelocityGradients; _x < _y.length; _x++) {
  58094. var limitVelocityGradient = _y[_x];
  58095. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  58096. }
  58097. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  58098. }
  58099. if (parsedParticleSystem.noiseTexture) {
  58100. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  58101. }
  58102. // Emitter
  58103. var emitterType;
  58104. if (parsedParticleSystem.particleEmitterType) {
  58105. switch (parsedParticleSystem.particleEmitterType.type) {
  58106. case "SphereParticleEmitter":
  58107. emitterType = new BABYLON.SphereParticleEmitter();
  58108. break;
  58109. case "SphereDirectedParticleEmitter":
  58110. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58111. break;
  58112. case "ConeEmitter":
  58113. case "ConeParticleEmitter":
  58114. emitterType = new BABYLON.ConeParticleEmitter();
  58115. break;
  58116. case "BoxEmitter":
  58117. case "BoxParticleEmitter":
  58118. default:
  58119. emitterType = new BABYLON.BoxParticleEmitter();
  58120. break;
  58121. }
  58122. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58123. }
  58124. else {
  58125. emitterType = new BABYLON.BoxParticleEmitter();
  58126. emitterType.parse(parsedParticleSystem);
  58127. }
  58128. particleSystem.particleEmitterType = emitterType;
  58129. // Animation sheet
  58130. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  58131. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  58132. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  58133. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  58134. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  58135. };
  58136. /**
  58137. * Parses a JSON object to create a particle system.
  58138. * @param parsedParticleSystem The JSON object to parse
  58139. * @param scene The scene to create the particle system in
  58140. * @param rootUrl The root url to use to load external dependencies like texture
  58141. * @returns the Parsed particle system
  58142. */
  58143. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58144. var name = parsedParticleSystem.name;
  58145. var custom = null;
  58146. var program = null;
  58147. if (parsedParticleSystem.customShader) {
  58148. program = parsedParticleSystem.customShader;
  58149. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  58150. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  58151. }
  58152. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  58153. particleSystem.customShader = program;
  58154. if (parsedParticleSystem.id) {
  58155. particleSystem.id = parsedParticleSystem.id;
  58156. }
  58157. // Auto start
  58158. if (parsedParticleSystem.preventAutoStart) {
  58159. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  58160. }
  58161. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  58162. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  58163. if (!particleSystem.preventAutoStart) {
  58164. particleSystem.start();
  58165. }
  58166. return particleSystem;
  58167. };
  58168. return ParticleSystem;
  58169. }(BABYLON.BaseParticleSystem));
  58170. BABYLON.ParticleSystem = ParticleSystem;
  58171. })(BABYLON || (BABYLON = {}));
  58172. //# sourceMappingURL=babylon.particleSystem.js.map
  58173. var BABYLON;
  58174. (function (BABYLON) {
  58175. /**
  58176. * Particle emitter emitting particles from the inside of a box.
  58177. * It emits the particles randomly between 2 given directions.
  58178. */
  58179. var BoxParticleEmitter = /** @class */ (function () {
  58180. /**
  58181. * Creates a new instance BoxParticleEmitter
  58182. */
  58183. function BoxParticleEmitter() {
  58184. /**
  58185. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58186. */
  58187. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58188. /**
  58189. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58190. */
  58191. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58192. /**
  58193. * 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.
  58194. */
  58195. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  58196. /**
  58197. * 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.
  58198. */
  58199. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  58200. }
  58201. /**
  58202. * Called by the particle System when the direction is computed for the created particle.
  58203. * @param worldMatrix is the world matrix of the particle system
  58204. * @param directionToUpdate is the direction vector to update with the result
  58205. * @param particle is the particle we are computed the direction for
  58206. */
  58207. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58208. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58209. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58210. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58211. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58212. };
  58213. /**
  58214. * Called by the particle System when the position is computed for the created particle.
  58215. * @param worldMatrix is the world matrix of the particle system
  58216. * @param positionToUpdate is the position vector to update with the result
  58217. * @param particle is the particle we are computed the position for
  58218. */
  58219. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58220. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  58221. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  58222. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  58223. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58224. };
  58225. /**
  58226. * Clones the current emitter and returns a copy of it
  58227. * @returns the new emitter
  58228. */
  58229. BoxParticleEmitter.prototype.clone = function () {
  58230. var newOne = new BoxParticleEmitter();
  58231. BABYLON.Tools.DeepCopy(this, newOne);
  58232. return newOne;
  58233. };
  58234. /**
  58235. * Called by the GPUParticleSystem to setup the update shader
  58236. * @param effect defines the update shader
  58237. */
  58238. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  58239. effect.setVector3("direction1", this.direction1);
  58240. effect.setVector3("direction2", this.direction2);
  58241. effect.setVector3("minEmitBox", this.minEmitBox);
  58242. effect.setVector3("maxEmitBox", this.maxEmitBox);
  58243. };
  58244. /**
  58245. * Returns a string to use to update the GPU particles update shader
  58246. * @returns a string containng the defines string
  58247. */
  58248. BoxParticleEmitter.prototype.getEffectDefines = function () {
  58249. return "#define BOXEMITTER";
  58250. };
  58251. /**
  58252. * Returns the string "BoxParticleEmitter"
  58253. * @returns a string containing the class name
  58254. */
  58255. BoxParticleEmitter.prototype.getClassName = function () {
  58256. return "BoxParticleEmitter";
  58257. };
  58258. /**
  58259. * Serializes the particle system to a JSON object.
  58260. * @returns the JSON object
  58261. */
  58262. BoxParticleEmitter.prototype.serialize = function () {
  58263. var serializationObject = {};
  58264. serializationObject.type = this.getClassName();
  58265. serializationObject.direction1 = this.direction1.asArray();
  58266. serializationObject.direction2 = this.direction2.asArray();
  58267. serializationObject.minEmitBox = this.minEmitBox.asArray();
  58268. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  58269. return serializationObject;
  58270. };
  58271. /**
  58272. * Parse properties from a JSON object
  58273. * @param serializationObject defines the JSON object
  58274. */
  58275. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  58276. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58277. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58278. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  58279. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  58280. };
  58281. return BoxParticleEmitter;
  58282. }());
  58283. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  58284. })(BABYLON || (BABYLON = {}));
  58285. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  58286. var BABYLON;
  58287. (function (BABYLON) {
  58288. /**
  58289. * Particle emitter emitting particles from the inside of a cylinder.
  58290. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  58291. */
  58292. var CylinderParticleEmitter = /** @class */ (function () {
  58293. /**
  58294. * Creates a new instance CylinderParticleEmitter
  58295. * @param radius the radius of the emission cylinder (1 by default)
  58296. * @param height the height of the emission cylinder (1 by default)
  58297. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58298. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58299. */
  58300. function CylinderParticleEmitter(
  58301. /**
  58302. * The radius of the emission cylinder.
  58303. */
  58304. radius,
  58305. /**
  58306. * The height of the emission cylinder.
  58307. */
  58308. height,
  58309. /**
  58310. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58311. */
  58312. radiusRange,
  58313. /**
  58314. * How much to randomize the particle direction [0-1].
  58315. */
  58316. directionRandomizer) {
  58317. if (radius === void 0) { radius = 1; }
  58318. if (height === void 0) { height = 1; }
  58319. if (radiusRange === void 0) { radiusRange = 1; }
  58320. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58321. this.radius = radius;
  58322. this.height = height;
  58323. this.radiusRange = radiusRange;
  58324. this.directionRandomizer = directionRandomizer;
  58325. }
  58326. /**
  58327. * Called by the particle System when the direction is computed for the created particle.
  58328. * @param worldMatrix is the world matrix of the particle system
  58329. * @param directionToUpdate is the direction vector to update with the result
  58330. * @param particle is the particle we are computed the direction for
  58331. */
  58332. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58333. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58334. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  58335. var angle = Math.atan2(direction.x, direction.z);
  58336. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  58337. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  58338. direction.x = Math.sin(angle);
  58339. direction.z = Math.cos(angle);
  58340. direction.normalize();
  58341. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58342. };
  58343. /**
  58344. * Called by the particle System when the position is computed for the created particle.
  58345. * @param worldMatrix is the world matrix of the particle system
  58346. * @param positionToUpdate is the position vector to update with the result
  58347. * @param particle is the particle we are computed the position for
  58348. */
  58349. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58350. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  58351. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58352. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  58353. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  58354. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  58355. var xPos = positionRadius * Math.cos(angle);
  58356. var zPos = positionRadius * Math.sin(angle);
  58357. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  58358. };
  58359. /**
  58360. * Clones the current emitter and returns a copy of it
  58361. * @returns the new emitter
  58362. */
  58363. CylinderParticleEmitter.prototype.clone = function () {
  58364. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  58365. BABYLON.Tools.DeepCopy(this, newOne);
  58366. return newOne;
  58367. };
  58368. /**
  58369. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58370. * @param effect defines the update shader
  58371. */
  58372. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  58373. effect.setFloat("radius", this.radius);
  58374. effect.setFloat("height", this.height);
  58375. effect.setFloat("radiusRange", this.radiusRange);
  58376. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58377. };
  58378. /**
  58379. * Returns a string to use to update the GPU particles update shader
  58380. * @returns a string containng the defines string
  58381. */
  58382. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  58383. return "#define CYLINDEREMITTER";
  58384. };
  58385. /**
  58386. * Returns the string "CylinderParticleEmitter"
  58387. * @returns a string containing the class name
  58388. */
  58389. CylinderParticleEmitter.prototype.getClassName = function () {
  58390. return "CylinderParticleEmitter";
  58391. };
  58392. /**
  58393. * Serializes the particle system to a JSON object.
  58394. * @returns the JSON object
  58395. */
  58396. CylinderParticleEmitter.prototype.serialize = function () {
  58397. var serializationObject = {};
  58398. serializationObject.type = this.getClassName();
  58399. serializationObject.radius = this.radius;
  58400. serializationObject.height = this.height;
  58401. serializationObject.radiusRange = this.radiusRange;
  58402. serializationObject.directionRandomizer = this.directionRandomizer;
  58403. return serializationObject;
  58404. };
  58405. /**
  58406. * Parse properties from a JSON object
  58407. * @param serializationObject defines the JSON object
  58408. */
  58409. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  58410. this.radius = serializationObject.radius;
  58411. this.height = serializationObject.height;
  58412. this.radiusRange = serializationObject.radiusRange;
  58413. this.directionRandomizer = serializationObject.directionRandomizer;
  58414. };
  58415. return CylinderParticleEmitter;
  58416. }());
  58417. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  58418. /**
  58419. * Particle emitter emitting particles from the inside of a cylinder.
  58420. * It emits the particles randomly between two vectors.
  58421. */
  58422. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  58423. __extends(CylinderDirectedParticleEmitter, _super);
  58424. /**
  58425. * Creates a new instance CylinderDirectedParticleEmitter
  58426. * @param radius the radius of the emission cylinder (1 by default)
  58427. * @param height the height of the emission cylinder (1 by default)
  58428. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58429. * @param direction1 the min limit of the emission direction (up vector by default)
  58430. * @param direction2 the max limit of the emission direction (up vector by default)
  58431. */
  58432. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  58433. /**
  58434. * The min limit of the emission direction.
  58435. */
  58436. direction1,
  58437. /**
  58438. * The max limit of the emission direction.
  58439. */
  58440. direction2) {
  58441. if (radius === void 0) { radius = 1; }
  58442. if (height === void 0) { height = 1; }
  58443. if (radiusRange === void 0) { radiusRange = 1; }
  58444. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58445. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58446. var _this = _super.call(this, radius, height, radiusRange) || this;
  58447. _this.direction1 = direction1;
  58448. _this.direction2 = direction2;
  58449. return _this;
  58450. }
  58451. /**
  58452. * Called by the particle System when the direction is computed for the created particle.
  58453. * @param worldMatrix is the world matrix of the particle system
  58454. * @param directionToUpdate is the direction vector to update with the result
  58455. * @param particle is the particle we are computed the direction for
  58456. */
  58457. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58458. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58459. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58460. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58461. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58462. };
  58463. /**
  58464. * Clones the current emitter and returns a copy of it
  58465. * @returns the new emitter
  58466. */
  58467. CylinderDirectedParticleEmitter.prototype.clone = function () {
  58468. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  58469. BABYLON.Tools.DeepCopy(this, newOne);
  58470. return newOne;
  58471. };
  58472. /**
  58473. * Called by the GPUParticleSystem to setup the update shader
  58474. * @param effect defines the update shader
  58475. */
  58476. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58477. effect.setFloat("radius", this.radius);
  58478. effect.setFloat("height", this.height);
  58479. effect.setFloat("radiusRange", this.radiusRange);
  58480. effect.setVector3("direction1", this.direction1);
  58481. effect.setVector3("direction2", this.direction2);
  58482. };
  58483. /**
  58484. * Returns a string to use to update the GPU particles update shader
  58485. * @returns a string containng the defines string
  58486. */
  58487. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58488. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  58489. };
  58490. /**
  58491. * Returns the string "CylinderDirectedParticleEmitter"
  58492. * @returns a string containing the class name
  58493. */
  58494. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  58495. return "CylinderDirectedParticleEmitter";
  58496. };
  58497. /**
  58498. * Serializes the particle system to a JSON object.
  58499. * @returns the JSON object
  58500. */
  58501. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  58502. var serializationObject = _super.prototype.serialize.call(this);
  58503. serializationObject.direction1 = this.direction1.asArray();
  58504. serializationObject.direction2 = this.direction2.asArray();
  58505. return serializationObject;
  58506. };
  58507. /**
  58508. * Parse properties from a JSON object
  58509. * @param serializationObject defines the JSON object
  58510. */
  58511. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58512. _super.prototype.parse.call(this, serializationObject);
  58513. this.direction1.copyFrom(serializationObject.direction1);
  58514. this.direction2.copyFrom(serializationObject.direction2);
  58515. };
  58516. return CylinderDirectedParticleEmitter;
  58517. }(CylinderParticleEmitter));
  58518. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  58519. })(BABYLON || (BABYLON = {}));
  58520. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  58521. var BABYLON;
  58522. (function (BABYLON) {
  58523. /**
  58524. * Particle emitter emitting particles from the inside of a cone.
  58525. * It emits the particles alongside the cone volume from the base to the particle.
  58526. * The emission direction might be randomized.
  58527. */
  58528. var ConeParticleEmitter = /** @class */ (function () {
  58529. /**
  58530. * Creates a new instance ConeParticleEmitter
  58531. * @param radius the radius of the emission cone (1 by default)
  58532. * @param angles the cone base angle (PI by default)
  58533. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  58534. */
  58535. function ConeParticleEmitter(radius, angle,
  58536. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  58537. directionRandomizer) {
  58538. if (radius === void 0) { radius = 1; }
  58539. if (angle === void 0) { angle = Math.PI; }
  58540. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58541. this.directionRandomizer = directionRandomizer;
  58542. /**
  58543. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  58544. */
  58545. this.radiusRange = 1;
  58546. /**
  58547. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  58548. */
  58549. this.heightRange = 1;
  58550. /**
  58551. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  58552. */
  58553. this.emitFromSpawnPointOnly = false;
  58554. this.angle = angle;
  58555. this.radius = radius;
  58556. }
  58557. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  58558. /**
  58559. * Gets or sets the radius of the emission cone
  58560. */
  58561. get: function () {
  58562. return this._radius;
  58563. },
  58564. set: function (value) {
  58565. this._radius = value;
  58566. this._buildHeight();
  58567. },
  58568. enumerable: true,
  58569. configurable: true
  58570. });
  58571. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  58572. /**
  58573. * Gets or sets the angle of the emission cone
  58574. */
  58575. get: function () {
  58576. return this._angle;
  58577. },
  58578. set: function (value) {
  58579. this._angle = value;
  58580. this._buildHeight();
  58581. },
  58582. enumerable: true,
  58583. configurable: true
  58584. });
  58585. ConeParticleEmitter.prototype._buildHeight = function () {
  58586. if (this._angle !== 0) {
  58587. this._height = this._radius / Math.tan(this._angle / 2);
  58588. }
  58589. else {
  58590. this._height = 1;
  58591. }
  58592. };
  58593. /**
  58594. * Called by the particle System when the direction is computed for the created particle.
  58595. * @param worldMatrix is the world matrix of the particle system
  58596. * @param directionToUpdate is the direction vector to update with the result
  58597. * @param particle is the particle we are computed the direction for
  58598. */
  58599. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58600. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  58601. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  58602. }
  58603. else {
  58604. // measure the direction Vector from the emitter to the particle.
  58605. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58606. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58607. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58608. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58609. direction.x += randX;
  58610. direction.y += randY;
  58611. direction.z += randZ;
  58612. direction.normalize();
  58613. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58614. }
  58615. };
  58616. /**
  58617. * Called by the particle System when the position is computed for the created particle.
  58618. * @param worldMatrix is the world matrix of the particle system
  58619. * @param positionToUpdate is the position vector to update with the result
  58620. * @param particle is the particle we are computed the position for
  58621. */
  58622. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58623. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  58624. var h;
  58625. if (!this.emitFromSpawnPointOnly) {
  58626. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  58627. // Better distribution in a cone at normal angles.
  58628. h = 1 - h * h;
  58629. }
  58630. else {
  58631. h = 0.0001;
  58632. }
  58633. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  58634. radius = radius * h;
  58635. var randX = radius * Math.sin(s);
  58636. var randZ = radius * Math.cos(s);
  58637. var randY = h * this._height;
  58638. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58639. };
  58640. /**
  58641. * Clones the current emitter and returns a copy of it
  58642. * @returns the new emitter
  58643. */
  58644. ConeParticleEmitter.prototype.clone = function () {
  58645. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  58646. BABYLON.Tools.DeepCopy(this, newOne);
  58647. return newOne;
  58648. };
  58649. /**
  58650. * Called by the GPUParticleSystem to setup the update shader
  58651. * @param effect defines the update shader
  58652. */
  58653. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  58654. effect.setFloat2("radius", this._radius, this.radiusRange);
  58655. effect.setFloat("coneAngle", this._angle);
  58656. effect.setFloat2("height", this._height, this.heightRange);
  58657. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58658. };
  58659. /**
  58660. * Returns a string to use to update the GPU particles update shader
  58661. * @returns a string containng the defines string
  58662. */
  58663. ConeParticleEmitter.prototype.getEffectDefines = function () {
  58664. var defines = "#define CONEEMITTER";
  58665. if (this.emitFromSpawnPointOnly) {
  58666. defines += "\n#define CONEEMITTERSPAWNPOINT";
  58667. }
  58668. return defines;
  58669. };
  58670. /**
  58671. * Returns the string "ConeParticleEmitter"
  58672. * @returns a string containing the class name
  58673. */
  58674. ConeParticleEmitter.prototype.getClassName = function () {
  58675. return "ConeParticleEmitter";
  58676. };
  58677. /**
  58678. * Serializes the particle system to a JSON object.
  58679. * @returns the JSON object
  58680. */
  58681. ConeParticleEmitter.prototype.serialize = function () {
  58682. var serializationObject = {};
  58683. serializationObject.type = this.getClassName();
  58684. serializationObject.radius = this._radius;
  58685. serializationObject.angle = this._angle;
  58686. serializationObject.directionRandomizer = this.directionRandomizer;
  58687. return serializationObject;
  58688. };
  58689. /**
  58690. * Parse properties from a JSON object
  58691. * @param serializationObject defines the JSON object
  58692. */
  58693. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  58694. this.radius = serializationObject.radius;
  58695. this.angle = serializationObject.angle;
  58696. this.directionRandomizer = serializationObject.directionRandomizer;
  58697. };
  58698. return ConeParticleEmitter;
  58699. }());
  58700. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  58701. })(BABYLON || (BABYLON = {}));
  58702. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  58703. var BABYLON;
  58704. (function (BABYLON) {
  58705. /**
  58706. * Particle emitter emitting particles from the inside of a sphere.
  58707. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  58708. */
  58709. var SphereParticleEmitter = /** @class */ (function () {
  58710. /**
  58711. * Creates a new instance SphereParticleEmitter
  58712. * @param radius the radius of the emission sphere (1 by default)
  58713. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58714. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58715. */
  58716. function SphereParticleEmitter(
  58717. /**
  58718. * The radius of the emission sphere.
  58719. */
  58720. radius,
  58721. /**
  58722. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58723. */
  58724. radiusRange,
  58725. /**
  58726. * How much to randomize the particle direction [0-1].
  58727. */
  58728. directionRandomizer) {
  58729. if (radius === void 0) { radius = 1; }
  58730. if (radiusRange === void 0) { radiusRange = 1; }
  58731. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58732. this.radius = radius;
  58733. this.radiusRange = radiusRange;
  58734. this.directionRandomizer = directionRandomizer;
  58735. }
  58736. /**
  58737. * Called by the particle System when the direction is computed for the created particle.
  58738. * @param worldMatrix is the world matrix of the particle system
  58739. * @param directionToUpdate is the direction vector to update with the result
  58740. * @param particle is the particle we are computed the direction for
  58741. */
  58742. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58743. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58744. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58745. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58746. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58747. direction.x += randX;
  58748. direction.y += randY;
  58749. direction.z += randZ;
  58750. direction.normalize();
  58751. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58752. };
  58753. /**
  58754. * Called by the particle System when the position is computed for the created particle.
  58755. * @param worldMatrix is the world matrix of the particle system
  58756. * @param positionToUpdate is the position vector to update with the result
  58757. * @param particle is the particle we are computed the position for
  58758. */
  58759. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58760. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58761. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58762. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58763. var theta = Math.acos(2 * v - 1);
  58764. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58765. var randY = randRadius * Math.cos(theta);
  58766. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58767. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58768. };
  58769. /**
  58770. * Clones the current emitter and returns a copy of it
  58771. * @returns the new emitter
  58772. */
  58773. SphereParticleEmitter.prototype.clone = function () {
  58774. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  58775. BABYLON.Tools.DeepCopy(this, newOne);
  58776. return newOne;
  58777. };
  58778. /**
  58779. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58780. * @param effect defines the update shader
  58781. */
  58782. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  58783. effect.setFloat("radius", this.radius);
  58784. effect.setFloat("radiusRange", this.radiusRange);
  58785. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58786. };
  58787. /**
  58788. * Returns a string to use to update the GPU particles update shader
  58789. * @returns a string containng the defines string
  58790. */
  58791. SphereParticleEmitter.prototype.getEffectDefines = function () {
  58792. return "#define SPHEREEMITTER";
  58793. };
  58794. /**
  58795. * Returns the string "SphereParticleEmitter"
  58796. * @returns a string containing the class name
  58797. */
  58798. SphereParticleEmitter.prototype.getClassName = function () {
  58799. return "SphereParticleEmitter";
  58800. };
  58801. /**
  58802. * Serializes the particle system to a JSON object.
  58803. * @returns the JSON object
  58804. */
  58805. SphereParticleEmitter.prototype.serialize = function () {
  58806. var serializationObject = {};
  58807. serializationObject.type = this.getClassName();
  58808. serializationObject.radius = this.radius;
  58809. serializationObject.radiusRange = this.radiusRange;
  58810. serializationObject.directionRandomizer = this.directionRandomizer;
  58811. return serializationObject;
  58812. };
  58813. /**
  58814. * Parse properties from a JSON object
  58815. * @param serializationObject defines the JSON object
  58816. */
  58817. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  58818. this.radius = serializationObject.radius;
  58819. this.radiusRange = serializationObject.radiusRange;
  58820. this.directionRandomizer = serializationObject.directionRandomizer;
  58821. };
  58822. return SphereParticleEmitter;
  58823. }());
  58824. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  58825. /**
  58826. * Particle emitter emitting particles from the inside of a sphere.
  58827. * It emits the particles randomly between two vectors.
  58828. */
  58829. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  58830. __extends(SphereDirectedParticleEmitter, _super);
  58831. /**
  58832. * Creates a new instance SphereDirectedParticleEmitter
  58833. * @param radius the radius of the emission sphere (1 by default)
  58834. * @param direction1 the min limit of the emission direction (up vector by default)
  58835. * @param direction2 the max limit of the emission direction (up vector by default)
  58836. */
  58837. function SphereDirectedParticleEmitter(radius,
  58838. /**
  58839. * The min limit of the emission direction.
  58840. */
  58841. direction1,
  58842. /**
  58843. * The max limit of the emission direction.
  58844. */
  58845. direction2) {
  58846. if (radius === void 0) { radius = 1; }
  58847. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58848. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58849. var _this = _super.call(this, radius) || this;
  58850. _this.direction1 = direction1;
  58851. _this.direction2 = direction2;
  58852. return _this;
  58853. }
  58854. /**
  58855. * Called by the particle System when the direction is computed for the created particle.
  58856. * @param worldMatrix is the world matrix of the particle system
  58857. * @param directionToUpdate is the direction vector to update with the result
  58858. * @param particle is the particle we are computed the direction for
  58859. */
  58860. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58861. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58862. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58863. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58864. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58865. };
  58866. /**
  58867. * Clones the current emitter and returns a copy of it
  58868. * @returns the new emitter
  58869. */
  58870. SphereDirectedParticleEmitter.prototype.clone = function () {
  58871. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  58872. BABYLON.Tools.DeepCopy(this, newOne);
  58873. return newOne;
  58874. };
  58875. /**
  58876. * Called by the GPUParticleSystem to setup the update shader
  58877. * @param effect defines the update shader
  58878. */
  58879. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58880. effect.setFloat("radius", this.radius);
  58881. effect.setFloat("radiusRange", this.radiusRange);
  58882. effect.setVector3("direction1", this.direction1);
  58883. effect.setVector3("direction2", this.direction2);
  58884. };
  58885. /**
  58886. * Returns a string to use to update the GPU particles update shader
  58887. * @returns a string containng the defines string
  58888. */
  58889. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58890. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  58891. };
  58892. /**
  58893. * Returns the string "SphereDirectedParticleEmitter"
  58894. * @returns a string containing the class name
  58895. */
  58896. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  58897. return "SphereDirectedParticleEmitter";
  58898. };
  58899. /**
  58900. * Serializes the particle system to a JSON object.
  58901. * @returns the JSON object
  58902. */
  58903. SphereDirectedParticleEmitter.prototype.serialize = function () {
  58904. var serializationObject = _super.prototype.serialize.call(this);
  58905. serializationObject.direction1 = this.direction1.asArray();
  58906. serializationObject.direction2 = this.direction2.asArray();
  58907. return serializationObject;
  58908. };
  58909. /**
  58910. * Parse properties from a JSON object
  58911. * @param serializationObject defines the JSON object
  58912. */
  58913. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58914. _super.prototype.parse.call(this, serializationObject);
  58915. this.direction1.copyFrom(serializationObject.direction1);
  58916. this.direction2.copyFrom(serializationObject.direction2);
  58917. };
  58918. return SphereDirectedParticleEmitter;
  58919. }(SphereParticleEmitter));
  58920. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  58921. })(BABYLON || (BABYLON = {}));
  58922. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  58923. var BABYLON;
  58924. (function (BABYLON) {
  58925. /**
  58926. * Particle emitter emitting particles from the inside of a hemisphere.
  58927. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  58928. */
  58929. var HemisphericParticleEmitter = /** @class */ (function () {
  58930. /**
  58931. * Creates a new instance HemisphericParticleEmitter
  58932. * @param radius the radius of the emission hemisphere (1 by default)
  58933. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58934. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58935. */
  58936. function HemisphericParticleEmitter(
  58937. /**
  58938. * The radius of the emission hemisphere.
  58939. */
  58940. radius,
  58941. /**
  58942. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58943. */
  58944. radiusRange,
  58945. /**
  58946. * How much to randomize the particle direction [0-1].
  58947. */
  58948. directionRandomizer) {
  58949. if (radius === void 0) { radius = 1; }
  58950. if (radiusRange === void 0) { radiusRange = 1; }
  58951. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58952. this.radius = radius;
  58953. this.radiusRange = radiusRange;
  58954. this.directionRandomizer = directionRandomizer;
  58955. }
  58956. /**
  58957. * Called by the particle System when the direction is computed for the created particle.
  58958. * @param worldMatrix is the world matrix of the particle system
  58959. * @param directionToUpdate is the direction vector to update with the result
  58960. * @param particle is the particle we are computed the direction for
  58961. */
  58962. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58963. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58964. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58965. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58966. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58967. direction.x += randX;
  58968. direction.y += randY;
  58969. direction.z += randZ;
  58970. direction.normalize();
  58971. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58972. };
  58973. /**
  58974. * Called by the particle System when the position is computed for the created particle.
  58975. * @param worldMatrix is the world matrix of the particle system
  58976. * @param positionToUpdate is the position vector to update with the result
  58977. * @param particle is the particle we are computed the position for
  58978. */
  58979. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58980. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58981. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58982. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58983. var theta = Math.acos(2 * v - 1);
  58984. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58985. var randY = randRadius * Math.cos(theta);
  58986. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58987. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  58988. };
  58989. /**
  58990. * Clones the current emitter and returns a copy of it
  58991. * @returns the new emitter
  58992. */
  58993. HemisphericParticleEmitter.prototype.clone = function () {
  58994. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  58995. BABYLON.Tools.DeepCopy(this, newOne);
  58996. return newOne;
  58997. };
  58998. /**
  58999. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59000. * @param effect defines the update shader
  59001. */
  59002. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  59003. effect.setFloat("radius", this.radius);
  59004. effect.setFloat("radiusRange", this.radiusRange);
  59005. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59006. };
  59007. /**
  59008. * Returns a string to use to update the GPU particles update shader
  59009. * @returns a string containng the defines string
  59010. */
  59011. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  59012. return "#define HEMISPHERICEMITTER";
  59013. };
  59014. /**
  59015. * Returns the string "HemisphericParticleEmitter"
  59016. * @returns a string containing the class name
  59017. */
  59018. HemisphericParticleEmitter.prototype.getClassName = function () {
  59019. return "HemisphericParticleEmitter";
  59020. };
  59021. /**
  59022. * Serializes the particle system to a JSON object.
  59023. * @returns the JSON object
  59024. */
  59025. HemisphericParticleEmitter.prototype.serialize = function () {
  59026. var serializationObject = {};
  59027. serializationObject.type = this.getClassName();
  59028. serializationObject.radius = this.radius;
  59029. serializationObject.radiusRange = this.radiusRange;
  59030. serializationObject.directionRandomizer = this.directionRandomizer;
  59031. return serializationObject;
  59032. };
  59033. /**
  59034. * Parse properties from a JSON object
  59035. * @param serializationObject defines the JSON object
  59036. */
  59037. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  59038. this.radius = serializationObject.radius;
  59039. this.radiusRange = serializationObject.radiusRange;
  59040. this.directionRandomizer = serializationObject.directionRandomizer;
  59041. };
  59042. return HemisphericParticleEmitter;
  59043. }());
  59044. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  59045. })(BABYLON || (BABYLON = {}));
  59046. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  59047. var BABYLON;
  59048. (function (BABYLON) {
  59049. /**
  59050. * Particle emitter emitting particles from a point.
  59051. * It emits the particles randomly between 2 given directions.
  59052. */
  59053. var PointParticleEmitter = /** @class */ (function () {
  59054. /**
  59055. * Creates a new instance PointParticleEmitter
  59056. */
  59057. function PointParticleEmitter() {
  59058. /**
  59059. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59060. */
  59061. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  59062. /**
  59063. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59064. */
  59065. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  59066. }
  59067. /**
  59068. * Called by the particle System when the direction is computed for the created particle.
  59069. * @param worldMatrix is the world matrix of the particle system
  59070. * @param directionToUpdate is the direction vector to update with the result
  59071. * @param particle is the particle we are computed the direction for
  59072. */
  59073. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59074. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59075. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59076. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59077. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59078. };
  59079. /**
  59080. * Called by the particle System when the position is computed for the created particle.
  59081. * @param worldMatrix is the world matrix of the particle system
  59082. * @param positionToUpdate is the position vector to update with the result
  59083. * @param particle is the particle we are computed the position for
  59084. */
  59085. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59086. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  59087. };
  59088. /**
  59089. * Clones the current emitter and returns a copy of it
  59090. * @returns the new emitter
  59091. */
  59092. PointParticleEmitter.prototype.clone = function () {
  59093. var newOne = new PointParticleEmitter();
  59094. BABYLON.Tools.DeepCopy(this, newOne);
  59095. return newOne;
  59096. };
  59097. /**
  59098. * Called by the GPUParticleSystem to setup the update shader
  59099. * @param effect defines the update shader
  59100. */
  59101. PointParticleEmitter.prototype.applyToShader = function (effect) {
  59102. effect.setVector3("direction1", this.direction1);
  59103. effect.setVector3("direction2", this.direction2);
  59104. };
  59105. /**
  59106. * Returns a string to use to update the GPU particles update shader
  59107. * @returns a string containng the defines string
  59108. */
  59109. PointParticleEmitter.prototype.getEffectDefines = function () {
  59110. return "#define POINTEMITTER";
  59111. };
  59112. /**
  59113. * Returns the string "PointParticleEmitter"
  59114. * @returns a string containing the class name
  59115. */
  59116. PointParticleEmitter.prototype.getClassName = function () {
  59117. return "PointParticleEmitter";
  59118. };
  59119. /**
  59120. * Serializes the particle system to a JSON object.
  59121. * @returns the JSON object
  59122. */
  59123. PointParticleEmitter.prototype.serialize = function () {
  59124. var serializationObject = {};
  59125. serializationObject.type = this.getClassName();
  59126. serializationObject.direction1 = this.direction1.asArray();
  59127. serializationObject.direction2 = this.direction2.asArray();
  59128. return serializationObject;
  59129. };
  59130. /**
  59131. * Parse properties from a JSON object
  59132. * @param serializationObject defines the JSON object
  59133. */
  59134. PointParticleEmitter.prototype.parse = function (serializationObject) {
  59135. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  59136. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  59137. };
  59138. return PointParticleEmitter;
  59139. }());
  59140. BABYLON.PointParticleEmitter = PointParticleEmitter;
  59141. })(BABYLON || (BABYLON = {}));
  59142. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  59143. var BABYLON;
  59144. (function (BABYLON) {
  59145. // Adds the parsers to the scene parsers.
  59146. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  59147. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  59148. if (!individualParser) {
  59149. return;
  59150. }
  59151. // Particles Systems
  59152. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  59153. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  59154. var parsedParticleSystem = parsedData.particleSystems[index];
  59155. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  59156. }
  59157. }
  59158. });
  59159. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  59160. if (parsedParticleSystem.activeParticleCount) {
  59161. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  59162. return ps;
  59163. }
  59164. else {
  59165. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  59166. return ps;
  59167. }
  59168. });
  59169. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  59170. if (uniformsNames === void 0) { uniformsNames = []; }
  59171. if (samplers === void 0) { samplers = []; }
  59172. if (defines === void 0) { defines = ""; }
  59173. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  59174. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  59175. if (defines.indexOf(" BILLBOARD") === -1) {
  59176. defines += "\n#define BILLBOARD\n";
  59177. }
  59178. if (samplers.indexOf("diffuseSampler") === -1) {
  59179. samplers.push("diffuseSampler");
  59180. }
  59181. return this.createEffect({
  59182. vertex: "particles",
  59183. fragmentElement: fragmentName
  59184. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  59185. };
  59186. })(BABYLON || (BABYLON = {}));
  59187. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  59188. var BABYLON;
  59189. (function (BABYLON) {
  59190. /**
  59191. * Type of sub emitter
  59192. */
  59193. var SubEmitterType;
  59194. (function (SubEmitterType) {
  59195. /**
  59196. * Attached to the particle over it's lifetime
  59197. */
  59198. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  59199. /**
  59200. * Created when the particle dies
  59201. */
  59202. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  59203. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  59204. /**
  59205. * Sub emitter class used to emit particles from an existing particle
  59206. */
  59207. var SubEmitter = /** @class */ (function () {
  59208. /**
  59209. * Creates a sub emitter
  59210. * @param particleSystem the particle system to be used by the sub emitter
  59211. */
  59212. function SubEmitter(
  59213. /**
  59214. * the particle system to be used by the sub emitter
  59215. */
  59216. particleSystem) {
  59217. this.particleSystem = particleSystem;
  59218. /**
  59219. * Type of the submitter (Default: END)
  59220. */
  59221. this.type = SubEmitterType.END;
  59222. /**
  59223. * 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)
  59224. * Note: This only is supported when using an emitter of type Mesh
  59225. */
  59226. this.inheritDirection = false;
  59227. /**
  59228. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  59229. */
  59230. this.inheritedVelocityAmount = 0;
  59231. }
  59232. /**
  59233. * Clones the sub emitter
  59234. * @returns the cloned sub emitter
  59235. */
  59236. SubEmitter.prototype.clone = function () {
  59237. // Clone particle system
  59238. var emitter = this.particleSystem.emitter;
  59239. if (!emitter) {
  59240. emitter = new BABYLON.Vector3();
  59241. }
  59242. else if (emitter instanceof BABYLON.Vector3) {
  59243. emitter = emitter.clone();
  59244. }
  59245. else if (emitter instanceof BABYLON.AbstractMesh) {
  59246. emitter = new BABYLON.Mesh("", emitter._scene);
  59247. }
  59248. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  59249. // Clone properties
  59250. clone.type = this.type;
  59251. clone.inheritDirection = this.inheritDirection;
  59252. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  59253. clone.particleSystem._disposeEmitterOnDispose = true;
  59254. return clone;
  59255. };
  59256. return SubEmitter;
  59257. }());
  59258. BABYLON.SubEmitter = SubEmitter;
  59259. })(BABYLON || (BABYLON = {}));
  59260. //# sourceMappingURL=babylon.subEmitter.js.map
  59261. var BABYLON;
  59262. (function (BABYLON) {
  59263. var ShaderMaterial = /** @class */ (function (_super) {
  59264. __extends(ShaderMaterial, _super);
  59265. function ShaderMaterial(name, scene, shaderPath, options) {
  59266. var _this = _super.call(this, name, scene) || this;
  59267. _this._textures = {};
  59268. _this._textureArrays = {};
  59269. _this._floats = {};
  59270. _this._ints = {};
  59271. _this._floatsArrays = {};
  59272. _this._colors3 = {};
  59273. _this._colors3Arrays = {};
  59274. _this._colors4 = {};
  59275. _this._vectors2 = {};
  59276. _this._vectors3 = {};
  59277. _this._vectors4 = {};
  59278. _this._matrices = {};
  59279. _this._matrices3x3 = {};
  59280. _this._matrices2x2 = {};
  59281. _this._vectors2Arrays = {};
  59282. _this._vectors3Arrays = {};
  59283. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59284. _this._shaderPath = shaderPath;
  59285. options.needAlphaBlending = options.needAlphaBlending || false;
  59286. options.needAlphaTesting = options.needAlphaTesting || false;
  59287. options.attributes = options.attributes || ["position", "normal", "uv"];
  59288. options.uniforms = options.uniforms || ["worldViewProjection"];
  59289. options.uniformBuffers = options.uniformBuffers || [];
  59290. options.samplers = options.samplers || [];
  59291. options.defines = options.defines || [];
  59292. _this._options = options;
  59293. return _this;
  59294. }
  59295. ShaderMaterial.prototype.getClassName = function () {
  59296. return "ShaderMaterial";
  59297. };
  59298. ShaderMaterial.prototype.needAlphaBlending = function () {
  59299. return this._options.needAlphaBlending;
  59300. };
  59301. ShaderMaterial.prototype.needAlphaTesting = function () {
  59302. return this._options.needAlphaTesting;
  59303. };
  59304. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59305. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59306. this._options.uniforms.push(uniformName);
  59307. }
  59308. };
  59309. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59310. if (this._options.samplers.indexOf(name) === -1) {
  59311. this._options.samplers.push(name);
  59312. }
  59313. this._textures[name] = texture;
  59314. return this;
  59315. };
  59316. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59317. if (this._options.samplers.indexOf(name) === -1) {
  59318. this._options.samplers.push(name);
  59319. }
  59320. this._checkUniform(name);
  59321. this._textureArrays[name] = textures;
  59322. return this;
  59323. };
  59324. ShaderMaterial.prototype.setFloat = function (name, value) {
  59325. this._checkUniform(name);
  59326. this._floats[name] = value;
  59327. return this;
  59328. };
  59329. ShaderMaterial.prototype.setInt = function (name, value) {
  59330. this._checkUniform(name);
  59331. this._ints[name] = value;
  59332. return this;
  59333. };
  59334. ShaderMaterial.prototype.setFloats = function (name, value) {
  59335. this._checkUniform(name);
  59336. this._floatsArrays[name] = value;
  59337. return this;
  59338. };
  59339. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59340. this._checkUniform(name);
  59341. this._colors3[name] = value;
  59342. return this;
  59343. };
  59344. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59345. this._checkUniform(name);
  59346. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59347. color.toArray(arr, arr.length);
  59348. return arr;
  59349. }, []);
  59350. return this;
  59351. };
  59352. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59353. this._checkUniform(name);
  59354. this._colors4[name] = value;
  59355. return this;
  59356. };
  59357. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59358. this._checkUniform(name);
  59359. this._vectors2[name] = value;
  59360. return this;
  59361. };
  59362. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59363. this._checkUniform(name);
  59364. this._vectors3[name] = value;
  59365. return this;
  59366. };
  59367. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59368. this._checkUniform(name);
  59369. this._vectors4[name] = value;
  59370. return this;
  59371. };
  59372. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59373. this._checkUniform(name);
  59374. this._matrices[name] = value;
  59375. return this;
  59376. };
  59377. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59378. this._checkUniform(name);
  59379. this._matrices3x3[name] = value;
  59380. return this;
  59381. };
  59382. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59383. this._checkUniform(name);
  59384. this._matrices2x2[name] = value;
  59385. return this;
  59386. };
  59387. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59388. this._checkUniform(name);
  59389. this._vectors2Arrays[name] = value;
  59390. return this;
  59391. };
  59392. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59393. this._checkUniform(name);
  59394. this._vectors3Arrays[name] = value;
  59395. return this;
  59396. };
  59397. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59398. if (!mesh) {
  59399. return true;
  59400. }
  59401. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59402. return false;
  59403. }
  59404. return false;
  59405. };
  59406. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59407. var scene = this.getScene();
  59408. var engine = scene.getEngine();
  59409. if (!this.checkReadyOnEveryCall) {
  59410. if (this._renderId === scene.getRenderId()) {
  59411. if (this._checkCache(scene, mesh, useInstances)) {
  59412. return true;
  59413. }
  59414. }
  59415. }
  59416. // Instances
  59417. var defines = [];
  59418. var attribs = [];
  59419. var fallbacks = new BABYLON.EffectFallbacks();
  59420. if (useInstances) {
  59421. defines.push("#define INSTANCES");
  59422. }
  59423. for (var index = 0; index < this._options.defines.length; index++) {
  59424. defines.push(this._options.defines[index]);
  59425. }
  59426. for (var index = 0; index < this._options.attributes.length; index++) {
  59427. attribs.push(this._options.attributes[index]);
  59428. }
  59429. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59430. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59431. defines.push("#define VERTEXCOLOR");
  59432. }
  59433. // Bones
  59434. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59435. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59436. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59437. if (mesh.numBoneInfluencers > 4) {
  59438. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59439. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59440. }
  59441. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59442. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59443. fallbacks.addCPUSkinningFallback(0, mesh);
  59444. if (this._options.uniforms.indexOf("mBones") === -1) {
  59445. this._options.uniforms.push("mBones");
  59446. }
  59447. }
  59448. else {
  59449. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59450. }
  59451. // Textures
  59452. for (var name in this._textures) {
  59453. if (!this._textures[name].isReady()) {
  59454. return false;
  59455. }
  59456. }
  59457. // Alpha test
  59458. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59459. defines.push("#define ALPHATEST");
  59460. }
  59461. var previousEffect = this._effect;
  59462. var join = defines.join("\n");
  59463. this._effect = engine.createEffect(this._shaderPath, {
  59464. attributes: attribs,
  59465. uniformsNames: this._options.uniforms,
  59466. uniformBuffersNames: this._options.uniformBuffers,
  59467. samplers: this._options.samplers,
  59468. defines: join,
  59469. fallbacks: fallbacks,
  59470. onCompiled: this.onCompiled,
  59471. onError: this.onError
  59472. }, engine);
  59473. if (!this._effect.isReady()) {
  59474. return false;
  59475. }
  59476. if (previousEffect !== this._effect) {
  59477. scene.resetCachedMaterial();
  59478. }
  59479. this._renderId = scene.getRenderId();
  59480. return true;
  59481. };
  59482. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59483. var scene = this.getScene();
  59484. if (!this._effect) {
  59485. return;
  59486. }
  59487. if (this._options.uniforms.indexOf("world") !== -1) {
  59488. this._effect.setMatrix("world", world);
  59489. }
  59490. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59491. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59492. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59493. }
  59494. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59495. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59496. }
  59497. };
  59498. ShaderMaterial.prototype.bind = function (world, mesh) {
  59499. // Std values
  59500. this.bindOnlyWorldMatrix(world);
  59501. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59502. if (this._options.uniforms.indexOf("view") !== -1) {
  59503. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59504. }
  59505. if (this._options.uniforms.indexOf("projection") !== -1) {
  59506. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59507. }
  59508. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59509. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59510. }
  59511. // Bones
  59512. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59513. var name;
  59514. // Texture
  59515. for (name in this._textures) {
  59516. this._effect.setTexture(name, this._textures[name]);
  59517. }
  59518. // Texture arrays
  59519. for (name in this._textureArrays) {
  59520. this._effect.setTextureArray(name, this._textureArrays[name]);
  59521. }
  59522. // Int
  59523. for (name in this._ints) {
  59524. this._effect.setInt(name, this._ints[name]);
  59525. }
  59526. // Float
  59527. for (name in this._floats) {
  59528. this._effect.setFloat(name, this._floats[name]);
  59529. }
  59530. // Floats
  59531. for (name in this._floatsArrays) {
  59532. this._effect.setArray(name, this._floatsArrays[name]);
  59533. }
  59534. // Color3
  59535. for (name in this._colors3) {
  59536. this._effect.setColor3(name, this._colors3[name]);
  59537. }
  59538. for (name in this._colors3Arrays) {
  59539. this._effect.setArray3(name, this._colors3Arrays[name]);
  59540. }
  59541. // Color4
  59542. for (name in this._colors4) {
  59543. var color = this._colors4[name];
  59544. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59545. }
  59546. // Vector2
  59547. for (name in this._vectors2) {
  59548. this._effect.setVector2(name, this._vectors2[name]);
  59549. }
  59550. // Vector3
  59551. for (name in this._vectors3) {
  59552. this._effect.setVector3(name, this._vectors3[name]);
  59553. }
  59554. // Vector4
  59555. for (name in this._vectors4) {
  59556. this._effect.setVector4(name, this._vectors4[name]);
  59557. }
  59558. // Matrix
  59559. for (name in this._matrices) {
  59560. this._effect.setMatrix(name, this._matrices[name]);
  59561. }
  59562. // Matrix 3x3
  59563. for (name in this._matrices3x3) {
  59564. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59565. }
  59566. // Matrix 2x2
  59567. for (name in this._matrices2x2) {
  59568. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59569. }
  59570. // Vector2Array
  59571. for (name in this._vectors2Arrays) {
  59572. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59573. }
  59574. // Vector3Array
  59575. for (name in this._vectors3Arrays) {
  59576. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59577. }
  59578. }
  59579. this._afterBind(mesh);
  59580. };
  59581. ShaderMaterial.prototype.getActiveTextures = function () {
  59582. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59583. for (var name in this._textures) {
  59584. activeTextures.push(this._textures[name]);
  59585. }
  59586. for (var name in this._textureArrays) {
  59587. var array = this._textureArrays[name];
  59588. for (var index = 0; index < array.length; index++) {
  59589. activeTextures.push(array[index]);
  59590. }
  59591. }
  59592. return activeTextures;
  59593. };
  59594. ShaderMaterial.prototype.hasTexture = function (texture) {
  59595. if (_super.prototype.hasTexture.call(this, texture)) {
  59596. return true;
  59597. }
  59598. for (var name in this._textures) {
  59599. if (this._textures[name] === texture) {
  59600. return true;
  59601. }
  59602. }
  59603. for (var name in this._textureArrays) {
  59604. var array = this._textureArrays[name];
  59605. for (var index = 0; index < array.length; index++) {
  59606. if (array[index] === texture) {
  59607. return true;
  59608. }
  59609. }
  59610. }
  59611. return false;
  59612. };
  59613. ShaderMaterial.prototype.clone = function (name) {
  59614. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59615. return newShaderMaterial;
  59616. };
  59617. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59618. if (forceDisposeTextures) {
  59619. var name;
  59620. for (name in this._textures) {
  59621. this._textures[name].dispose();
  59622. }
  59623. for (name in this._textureArrays) {
  59624. var array = this._textureArrays[name];
  59625. for (var index = 0; index < array.length; index++) {
  59626. array[index].dispose();
  59627. }
  59628. }
  59629. }
  59630. this._textures = {};
  59631. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59632. };
  59633. ShaderMaterial.prototype.serialize = function () {
  59634. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59635. serializationObject.customType = "BABYLON.ShaderMaterial";
  59636. serializationObject.options = this._options;
  59637. serializationObject.shaderPath = this._shaderPath;
  59638. var name;
  59639. // Texture
  59640. serializationObject.textures = {};
  59641. for (name in this._textures) {
  59642. serializationObject.textures[name] = this._textures[name].serialize();
  59643. }
  59644. // Texture arrays
  59645. serializationObject.textureArrays = {};
  59646. for (name in this._textureArrays) {
  59647. serializationObject.textureArrays[name] = [];
  59648. var array = this._textureArrays[name];
  59649. for (var index = 0; index < array.length; index++) {
  59650. serializationObject.textureArrays[name].push(array[index].serialize());
  59651. }
  59652. }
  59653. // Float
  59654. serializationObject.floats = {};
  59655. for (name in this._floats) {
  59656. serializationObject.floats[name] = this._floats[name];
  59657. }
  59658. // Float s
  59659. serializationObject.FloatArrays = {};
  59660. for (name in this._floatsArrays) {
  59661. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59662. }
  59663. // Color3
  59664. serializationObject.colors3 = {};
  59665. for (name in this._colors3) {
  59666. serializationObject.colors3[name] = this._colors3[name].asArray();
  59667. }
  59668. // Color3 array
  59669. serializationObject.colors3Arrays = {};
  59670. for (name in this._colors3Arrays) {
  59671. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59672. }
  59673. // Color4
  59674. serializationObject.colors4 = {};
  59675. for (name in this._colors4) {
  59676. serializationObject.colors4[name] = this._colors4[name].asArray();
  59677. }
  59678. // Vector2
  59679. serializationObject.vectors2 = {};
  59680. for (name in this._vectors2) {
  59681. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59682. }
  59683. // Vector3
  59684. serializationObject.vectors3 = {};
  59685. for (name in this._vectors3) {
  59686. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59687. }
  59688. // Vector4
  59689. serializationObject.vectors4 = {};
  59690. for (name in this._vectors4) {
  59691. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59692. }
  59693. // Matrix
  59694. serializationObject.matrices = {};
  59695. for (name in this._matrices) {
  59696. serializationObject.matrices[name] = this._matrices[name].asArray();
  59697. }
  59698. // Matrix 3x3
  59699. serializationObject.matrices3x3 = {};
  59700. for (name in this._matrices3x3) {
  59701. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59702. }
  59703. // Matrix 2x2
  59704. serializationObject.matrices2x2 = {};
  59705. for (name in this._matrices2x2) {
  59706. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59707. }
  59708. // Vector2Array
  59709. serializationObject.vectors2Arrays = {};
  59710. for (name in this._vectors2Arrays) {
  59711. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59712. }
  59713. // Vector3Array
  59714. serializationObject.vectors3Arrays = {};
  59715. for (name in this._vectors3Arrays) {
  59716. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59717. }
  59718. return serializationObject;
  59719. };
  59720. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59721. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59722. var name;
  59723. // Texture
  59724. for (name in source.textures) {
  59725. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59726. }
  59727. // Texture arrays
  59728. for (name in source.textureArrays) {
  59729. var array = source.textureArrays[name];
  59730. var textureArray = new Array();
  59731. for (var index = 0; index < array.length; index++) {
  59732. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59733. }
  59734. material.setTextureArray(name, textureArray);
  59735. }
  59736. // Float
  59737. for (name in source.floats) {
  59738. material.setFloat(name, source.floats[name]);
  59739. }
  59740. // Float s
  59741. for (name in source.floatsArrays) {
  59742. material.setFloats(name, source.floatsArrays[name]);
  59743. }
  59744. // Color3
  59745. for (name in source.colors3) {
  59746. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59747. }
  59748. // Color3 arrays
  59749. for (name in source.colors3Arrays) {
  59750. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59751. if (i % 3 === 0) {
  59752. arr.push([num]);
  59753. }
  59754. else {
  59755. arr[arr.length - 1].push(num);
  59756. }
  59757. return arr;
  59758. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59759. material.setColor3Array(name, colors);
  59760. }
  59761. // Color4
  59762. for (name in source.colors4) {
  59763. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59764. }
  59765. // Vector2
  59766. for (name in source.vectors2) {
  59767. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59768. }
  59769. // Vector3
  59770. for (name in source.vectors3) {
  59771. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59772. }
  59773. // Vector4
  59774. for (name in source.vectors4) {
  59775. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59776. }
  59777. // Matrix
  59778. for (name in source.matrices) {
  59779. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59780. }
  59781. // Matrix 3x3
  59782. for (name in source.matrices3x3) {
  59783. material.setMatrix3x3(name, source.matrices3x3[name]);
  59784. }
  59785. // Matrix 2x2
  59786. for (name in source.matrices2x2) {
  59787. material.setMatrix2x2(name, source.matrices2x2[name]);
  59788. }
  59789. // Vector2Array
  59790. for (name in source.vectors2Arrays) {
  59791. material.setArray2(name, source.vectors2Arrays[name]);
  59792. }
  59793. // Vector3Array
  59794. for (name in source.vectors3Arrays) {
  59795. material.setArray3(name, source.vectors3Arrays[name]);
  59796. }
  59797. return material;
  59798. };
  59799. return ShaderMaterial;
  59800. }(BABYLON.Material));
  59801. BABYLON.ShaderMaterial = ShaderMaterial;
  59802. })(BABYLON || (BABYLON = {}));
  59803. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59804. var BABYLON;
  59805. (function (BABYLON) {
  59806. var GroundMesh = /** @class */ (function (_super) {
  59807. __extends(GroundMesh, _super);
  59808. function GroundMesh(name, scene) {
  59809. var _this = _super.call(this, name, scene) || this;
  59810. _this.generateOctree = false;
  59811. return _this;
  59812. }
  59813. GroundMesh.prototype.getClassName = function () {
  59814. return "GroundMesh";
  59815. };
  59816. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59817. get: function () {
  59818. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59819. },
  59820. enumerable: true,
  59821. configurable: true
  59822. });
  59823. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59824. get: function () {
  59825. return this._subdivisionsX;
  59826. },
  59827. enumerable: true,
  59828. configurable: true
  59829. });
  59830. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59831. get: function () {
  59832. return this._subdivisionsY;
  59833. },
  59834. enumerable: true,
  59835. configurable: true
  59836. });
  59837. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59838. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59839. this._subdivisionsX = chunksCount;
  59840. this._subdivisionsY = chunksCount;
  59841. this.subdivide(chunksCount);
  59842. // Call the octree system optimization if it is defined.
  59843. var thisAsAny = this;
  59844. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  59845. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59846. }
  59847. };
  59848. /**
  59849. * Returns a height (y) value in the Worl system :
  59850. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59851. * Returns the ground y position if (x, z) are outside the ground surface.
  59852. */
  59853. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59854. var world = this.getWorldMatrix();
  59855. var invMat = BABYLON.Tmp.Matrix[5];
  59856. world.invertToRef(invMat);
  59857. var tmpVect = BABYLON.Tmp.Vector3[8];
  59858. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59859. x = tmpVect.x;
  59860. z = tmpVect.z;
  59861. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59862. return this.position.y;
  59863. }
  59864. if (!this._heightQuads || this._heightQuads.length == 0) {
  59865. this._initHeightQuads();
  59866. this._computeHeightQuads();
  59867. }
  59868. var facet = this._getFacetAt(x, z);
  59869. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59870. // return y in the World system
  59871. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59872. return tmpVect.y;
  59873. };
  59874. /**
  59875. * Returns a normalized vector (Vector3) orthogonal to the ground
  59876. * at the ground coordinates (x, z) expressed in the World system.
  59877. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59878. */
  59879. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59880. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59881. this.getNormalAtCoordinatesToRef(x, z, normal);
  59882. return normal;
  59883. };
  59884. /**
  59885. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59886. * at the ground coordinates (x, z) expressed in the World system.
  59887. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59888. * Returns the GroundMesh.
  59889. */
  59890. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59891. var world = this.getWorldMatrix();
  59892. var tmpMat = BABYLON.Tmp.Matrix[5];
  59893. world.invertToRef(tmpMat);
  59894. var tmpVect = BABYLON.Tmp.Vector3[8];
  59895. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59896. x = tmpVect.x;
  59897. z = tmpVect.z;
  59898. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59899. return this;
  59900. }
  59901. if (!this._heightQuads || this._heightQuads.length == 0) {
  59902. this._initHeightQuads();
  59903. this._computeHeightQuads();
  59904. }
  59905. var facet = this._getFacetAt(x, z);
  59906. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59907. return this;
  59908. };
  59909. /**
  59910. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59911. * if the ground has been updated.
  59912. * This can be used in the render loop.
  59913. * Returns the GroundMesh.
  59914. */
  59915. GroundMesh.prototype.updateCoordinateHeights = function () {
  59916. if (!this._heightQuads || this._heightQuads.length == 0) {
  59917. this._initHeightQuads();
  59918. }
  59919. this._computeHeightQuads();
  59920. return this;
  59921. };
  59922. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59923. GroundMesh.prototype._getFacetAt = function (x, z) {
  59924. // retrieve col and row from x, z coordinates in the ground local system
  59925. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59926. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59927. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59928. var facet;
  59929. if (z < quad.slope.x * x + quad.slope.y) {
  59930. facet = quad.facet1;
  59931. }
  59932. else {
  59933. facet = quad.facet2;
  59934. }
  59935. return facet;
  59936. };
  59937. // Creates and populates the heightMap array with "facet" elements :
  59938. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59939. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59940. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59941. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59942. // Returns the GroundMesh.
  59943. GroundMesh.prototype._initHeightQuads = function () {
  59944. var subdivisionsX = this._subdivisionsX;
  59945. var subdivisionsY = this._subdivisionsY;
  59946. this._heightQuads = new Array();
  59947. for (var row = 0; row < subdivisionsY; row++) {
  59948. for (var col = 0; col < subdivisionsX; col++) {
  59949. 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) };
  59950. this._heightQuads[row * subdivisionsX + col] = quad;
  59951. }
  59952. }
  59953. return this;
  59954. };
  59955. // Compute each quad element values and update the the heightMap array :
  59956. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59957. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59958. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59959. // Returns the GroundMesh.
  59960. GroundMesh.prototype._computeHeightQuads = function () {
  59961. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59962. if (!positions) {
  59963. return this;
  59964. }
  59965. var v1 = BABYLON.Tmp.Vector3[3];
  59966. var v2 = BABYLON.Tmp.Vector3[2];
  59967. var v3 = BABYLON.Tmp.Vector3[1];
  59968. var v4 = BABYLON.Tmp.Vector3[0];
  59969. var v1v2 = BABYLON.Tmp.Vector3[4];
  59970. var v1v3 = BABYLON.Tmp.Vector3[5];
  59971. var v1v4 = BABYLON.Tmp.Vector3[6];
  59972. var norm1 = BABYLON.Tmp.Vector3[7];
  59973. var norm2 = BABYLON.Tmp.Vector3[8];
  59974. var i = 0;
  59975. var j = 0;
  59976. var k = 0;
  59977. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59978. var h = 0;
  59979. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59980. var d2 = 0;
  59981. var subdivisionsX = this._subdivisionsX;
  59982. var subdivisionsY = this._subdivisionsY;
  59983. for (var row = 0; row < subdivisionsY; row++) {
  59984. for (var col = 0; col < subdivisionsX; col++) {
  59985. i = col * 3;
  59986. j = row * (subdivisionsX + 1) * 3;
  59987. k = (row + 1) * (subdivisionsX + 1) * 3;
  59988. v1.x = positions[j + i];
  59989. v1.y = positions[j + i + 1];
  59990. v1.z = positions[j + i + 2];
  59991. v2.x = positions[j + i + 3];
  59992. v2.y = positions[j + i + 4];
  59993. v2.z = positions[j + i + 5];
  59994. v3.x = positions[k + i];
  59995. v3.y = positions[k + i + 1];
  59996. v3.z = positions[k + i + 2];
  59997. v4.x = positions[k + i + 3];
  59998. v4.y = positions[k + i + 4];
  59999. v4.z = positions[k + i + 5];
  60000. // 2D slope V1V4
  60001. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60002. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60003. // facet equations :
  60004. // we compute each facet normal vector
  60005. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60006. // we compute the value d by applying the equation to v1 which belongs to the plane
  60007. // then we store the facet equation in a Vector4
  60008. v2.subtractToRef(v1, v1v2);
  60009. v3.subtractToRef(v1, v1v3);
  60010. v4.subtractToRef(v1, v1v4);
  60011. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60012. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60013. norm1.normalize();
  60014. norm2.normalize();
  60015. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60016. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60017. var quad = this._heightQuads[row * subdivisionsX + col];
  60018. quad.slope.copyFromFloats(cd, h);
  60019. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60020. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60021. }
  60022. }
  60023. return this;
  60024. };
  60025. GroundMesh.prototype.serialize = function (serializationObject) {
  60026. _super.prototype.serialize.call(this, serializationObject);
  60027. serializationObject.subdivisionsX = this._subdivisionsX;
  60028. serializationObject.subdivisionsY = this._subdivisionsY;
  60029. serializationObject.minX = this._minX;
  60030. serializationObject.maxX = this._maxX;
  60031. serializationObject.minZ = this._minZ;
  60032. serializationObject.maxZ = this._maxZ;
  60033. serializationObject.width = this._width;
  60034. serializationObject.height = this._height;
  60035. };
  60036. GroundMesh.Parse = function (parsedMesh, scene) {
  60037. var result = new GroundMesh(parsedMesh.name, scene);
  60038. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60039. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60040. result._minX = parsedMesh.minX;
  60041. result._maxX = parsedMesh.maxX;
  60042. result._minZ = parsedMesh.minZ;
  60043. result._maxZ = parsedMesh.maxZ;
  60044. result._width = parsedMesh.width;
  60045. result._height = parsedMesh.height;
  60046. return result;
  60047. };
  60048. return GroundMesh;
  60049. }(BABYLON.Mesh));
  60050. BABYLON.GroundMesh = GroundMesh;
  60051. })(BABYLON || (BABYLON = {}));
  60052. //# sourceMappingURL=babylon.groundMesh.js.map
  60053. var BABYLON;
  60054. (function (BABYLON) {
  60055. /**
  60056. * Creates an instance based on a source mesh.
  60057. */
  60058. var InstancedMesh = /** @class */ (function (_super) {
  60059. __extends(InstancedMesh, _super);
  60060. function InstancedMesh(name, source) {
  60061. var _this = _super.call(this, name, source.getScene()) || this;
  60062. source.instances.push(_this);
  60063. _this._sourceMesh = source;
  60064. _this.position.copyFrom(source.position);
  60065. _this.rotation.copyFrom(source.rotation);
  60066. _this.scaling.copyFrom(source.scaling);
  60067. if (source.rotationQuaternion) {
  60068. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60069. }
  60070. _this.infiniteDistance = source.infiniteDistance;
  60071. _this.setPivotMatrix(source.getPivotMatrix());
  60072. _this.refreshBoundingInfo();
  60073. _this._syncSubMeshes();
  60074. return _this;
  60075. }
  60076. /**
  60077. * Returns the string "InstancedMesh".
  60078. */
  60079. InstancedMesh.prototype.getClassName = function () {
  60080. return "InstancedMesh";
  60081. };
  60082. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60083. // Methods
  60084. get: function () {
  60085. return this._sourceMesh.receiveShadows;
  60086. },
  60087. enumerable: true,
  60088. configurable: true
  60089. });
  60090. Object.defineProperty(InstancedMesh.prototype, "material", {
  60091. get: function () {
  60092. return this._sourceMesh.material;
  60093. },
  60094. enumerable: true,
  60095. configurable: true
  60096. });
  60097. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60098. get: function () {
  60099. return this._sourceMesh.visibility;
  60100. },
  60101. enumerable: true,
  60102. configurable: true
  60103. });
  60104. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60105. get: function () {
  60106. return this._sourceMesh.skeleton;
  60107. },
  60108. enumerable: true,
  60109. configurable: true
  60110. });
  60111. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60112. get: function () {
  60113. return this._sourceMesh.renderingGroupId;
  60114. },
  60115. set: function (value) {
  60116. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60117. return;
  60118. }
  60119. //no-op with warning
  60120. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60121. },
  60122. enumerable: true,
  60123. configurable: true
  60124. });
  60125. /**
  60126. * Returns the total number of vertices (integer).
  60127. */
  60128. InstancedMesh.prototype.getTotalVertices = function () {
  60129. return this._sourceMesh.getTotalVertices();
  60130. };
  60131. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60132. get: function () {
  60133. return this._sourceMesh;
  60134. },
  60135. enumerable: true,
  60136. configurable: true
  60137. });
  60138. /**
  60139. * Is this node ready to be used/rendered
  60140. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60141. * @return {boolean} is it ready
  60142. */
  60143. InstancedMesh.prototype.isReady = function (completeCheck) {
  60144. if (completeCheck === void 0) { completeCheck = false; }
  60145. return this._sourceMesh.isReady(completeCheck, true);
  60146. };
  60147. /**
  60148. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60149. */
  60150. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60151. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60152. };
  60153. /**
  60154. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60155. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60156. * The `data` are either a numeric array either a Float32Array.
  60157. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60158. * 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).
  60159. * Note that a new underlying VertexBuffer object is created each call.
  60160. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60161. *
  60162. * Possible `kind` values :
  60163. * - BABYLON.VertexBuffer.PositionKind
  60164. * - BABYLON.VertexBuffer.UVKind
  60165. * - BABYLON.VertexBuffer.UV2Kind
  60166. * - BABYLON.VertexBuffer.UV3Kind
  60167. * - BABYLON.VertexBuffer.UV4Kind
  60168. * - BABYLON.VertexBuffer.UV5Kind
  60169. * - BABYLON.VertexBuffer.UV6Kind
  60170. * - BABYLON.VertexBuffer.ColorKind
  60171. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60172. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60173. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60174. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60175. *
  60176. * Returns the Mesh.
  60177. */
  60178. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60179. if (this.sourceMesh) {
  60180. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60181. }
  60182. return this.sourceMesh;
  60183. };
  60184. /**
  60185. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60186. * If the mesh has no geometry, it is simply returned as it is.
  60187. * The `data` are either a numeric array either a Float32Array.
  60188. * No new underlying VertexBuffer object is created.
  60189. * 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.
  60190. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60191. *
  60192. * Possible `kind` values :
  60193. * - BABYLON.VertexBuffer.PositionKind
  60194. * - BABYLON.VertexBuffer.UVKind
  60195. * - BABYLON.VertexBuffer.UV2Kind
  60196. * - BABYLON.VertexBuffer.UV3Kind
  60197. * - BABYLON.VertexBuffer.UV4Kind
  60198. * - BABYLON.VertexBuffer.UV5Kind
  60199. * - BABYLON.VertexBuffer.UV6Kind
  60200. * - BABYLON.VertexBuffer.ColorKind
  60201. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60202. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60203. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60204. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60205. *
  60206. * Returns the Mesh.
  60207. */
  60208. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60209. if (this.sourceMesh) {
  60210. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60211. }
  60212. return this.sourceMesh;
  60213. };
  60214. /**
  60215. * Sets the mesh indices.
  60216. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60217. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60218. * This method creates a new index buffer each call.
  60219. * Returns the Mesh.
  60220. */
  60221. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60222. if (totalVertices === void 0) { totalVertices = null; }
  60223. if (this.sourceMesh) {
  60224. this.sourceMesh.setIndices(indices, totalVertices);
  60225. }
  60226. return this.sourceMesh;
  60227. };
  60228. /**
  60229. * Boolean : True if the mesh owns the requested kind of data.
  60230. */
  60231. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60232. return this._sourceMesh.isVerticesDataPresent(kind);
  60233. };
  60234. /**
  60235. * Returns an array of indices (IndicesArray).
  60236. */
  60237. InstancedMesh.prototype.getIndices = function () {
  60238. return this._sourceMesh.getIndices();
  60239. };
  60240. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60241. get: function () {
  60242. return this._sourceMesh._positions;
  60243. },
  60244. enumerable: true,
  60245. configurable: true
  60246. });
  60247. /**
  60248. * Sets a new updated BoundingInfo to the mesh.
  60249. * Returns the mesh.
  60250. */
  60251. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60252. var meshBB = this._sourceMesh.getBoundingInfo();
  60253. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60254. this._updateBoundingInfo();
  60255. return this;
  60256. };
  60257. /** @hidden */
  60258. InstancedMesh.prototype._preActivate = function () {
  60259. if (this._currentLOD) {
  60260. this._currentLOD._preActivate();
  60261. }
  60262. return this;
  60263. };
  60264. /** @hidden */
  60265. InstancedMesh.prototype._activate = function (renderId) {
  60266. if (this._currentLOD) {
  60267. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60268. }
  60269. return this;
  60270. };
  60271. /**
  60272. * Returns the current associated LOD AbstractMesh.
  60273. */
  60274. InstancedMesh.prototype.getLOD = function (camera) {
  60275. if (!camera) {
  60276. return this;
  60277. }
  60278. var boundingInfo = this.getBoundingInfo();
  60279. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60280. if (this._currentLOD === this.sourceMesh) {
  60281. return this;
  60282. }
  60283. return this._currentLOD;
  60284. };
  60285. /** @hidden */
  60286. InstancedMesh.prototype._syncSubMeshes = function () {
  60287. this.releaseSubMeshes();
  60288. if (this._sourceMesh.subMeshes) {
  60289. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60290. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60291. }
  60292. }
  60293. return this;
  60294. };
  60295. /** @hidden */
  60296. InstancedMesh.prototype._generatePointsArray = function () {
  60297. return this._sourceMesh._generatePointsArray();
  60298. };
  60299. /**
  60300. * Creates a new InstancedMesh from the current mesh.
  60301. * - name (string) : the cloned mesh name
  60302. * - newParent (optional Node) : the optional Node to parent the clone to.
  60303. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60304. *
  60305. * Returns the clone.
  60306. */
  60307. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60308. var result = this._sourceMesh.createInstance(name);
  60309. // Deep copy
  60310. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60311. // Bounding info
  60312. this.refreshBoundingInfo();
  60313. // Parent
  60314. if (newParent) {
  60315. result.parent = newParent;
  60316. }
  60317. if (!doNotCloneChildren) {
  60318. // Children
  60319. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60320. var mesh = this.getScene().meshes[index];
  60321. if (mesh.parent === this) {
  60322. mesh.clone(mesh.name, result);
  60323. }
  60324. }
  60325. }
  60326. result.computeWorldMatrix(true);
  60327. return result;
  60328. };
  60329. /**
  60330. * Disposes the InstancedMesh.
  60331. * Returns nothing.
  60332. */
  60333. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60334. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60335. // Remove from mesh
  60336. var index = this._sourceMesh.instances.indexOf(this);
  60337. this._sourceMesh.instances.splice(index, 1);
  60338. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60339. };
  60340. return InstancedMesh;
  60341. }(BABYLON.AbstractMesh));
  60342. BABYLON.InstancedMesh = InstancedMesh;
  60343. })(BABYLON || (BABYLON = {}));
  60344. //# sourceMappingURL=babylon.instancedMesh.js.map
  60345. var BABYLON;
  60346. (function (BABYLON) {
  60347. var LinesMesh = /** @class */ (function (_super) {
  60348. __extends(LinesMesh, _super);
  60349. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60350. if (scene === void 0) { scene = null; }
  60351. if (parent === void 0) { parent = null; }
  60352. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60353. _this.useVertexColor = useVertexColor;
  60354. _this.useVertexAlpha = useVertexAlpha;
  60355. _this.color = new BABYLON.Color3(1, 1, 1);
  60356. _this.alpha = 1;
  60357. if (source) {
  60358. _this.color = source.color.clone();
  60359. _this.alpha = source.alpha;
  60360. _this.useVertexColor = source.useVertexColor;
  60361. _this.useVertexAlpha = source.useVertexAlpha;
  60362. }
  60363. _this._intersectionThreshold = 0.1;
  60364. var defines = [];
  60365. var options = {
  60366. attributes: [BABYLON.VertexBuffer.PositionKind],
  60367. uniforms: ["world", "viewProjection"],
  60368. needAlphaBlending: true,
  60369. defines: defines
  60370. };
  60371. if (useVertexAlpha === false) {
  60372. options.needAlphaBlending = false;
  60373. }
  60374. if (!useVertexColor) {
  60375. options.uniforms.push("color");
  60376. }
  60377. else {
  60378. options.defines.push("#define VERTEXCOLOR");
  60379. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60380. }
  60381. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60382. return _this;
  60383. }
  60384. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60385. /**
  60386. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60387. * This margin is expressed in world space coordinates, so its value may vary.
  60388. * Default value is 0.1
  60389. * @returns the intersection Threshold value.
  60390. */
  60391. get: function () {
  60392. return this._intersectionThreshold;
  60393. },
  60394. /**
  60395. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60396. * This margin is expressed in world space coordinates, so its value may vary.
  60397. * @param value the new threshold to apply
  60398. */
  60399. set: function (value) {
  60400. if (this._intersectionThreshold === value) {
  60401. return;
  60402. }
  60403. this._intersectionThreshold = value;
  60404. if (this.geometry) {
  60405. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60406. }
  60407. },
  60408. enumerable: true,
  60409. configurable: true
  60410. });
  60411. /**
  60412. * Returns the string "LineMesh"
  60413. */
  60414. LinesMesh.prototype.getClassName = function () {
  60415. return "LinesMesh";
  60416. };
  60417. Object.defineProperty(LinesMesh.prototype, "material", {
  60418. /**
  60419. * @hidden
  60420. */
  60421. get: function () {
  60422. return this._colorShader;
  60423. },
  60424. /**
  60425. * @hidden
  60426. */
  60427. set: function (value) {
  60428. // Do nothing
  60429. },
  60430. enumerable: true,
  60431. configurable: true
  60432. });
  60433. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60434. /**
  60435. * @hidden
  60436. */
  60437. get: function () {
  60438. return false;
  60439. },
  60440. enumerable: true,
  60441. configurable: true
  60442. });
  60443. LinesMesh.prototype.createInstance = function (name) {
  60444. throw new Error("LinesMeshes do not support createInstance.");
  60445. };
  60446. /** @hidden */
  60447. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60448. if (!this._geometry) {
  60449. return this;
  60450. }
  60451. // VBOs
  60452. this._geometry._bind(this._colorShader.getEffect());
  60453. // Color
  60454. if (!this.useVertexColor) {
  60455. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60456. }
  60457. return this;
  60458. };
  60459. /** @hidden */
  60460. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60461. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60462. return this;
  60463. }
  60464. var engine = this.getScene().getEngine();
  60465. // Draw order
  60466. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60467. return this;
  60468. };
  60469. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60470. this._colorShader.dispose();
  60471. _super.prototype.dispose.call(this, doNotRecurse);
  60472. };
  60473. /**
  60474. * Returns a new LineMesh object cloned from the current one.
  60475. */
  60476. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60477. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60478. };
  60479. return LinesMesh;
  60480. }(BABYLON.Mesh));
  60481. BABYLON.LinesMesh = LinesMesh;
  60482. })(BABYLON || (BABYLON = {}));
  60483. //# sourceMappingURL=babylon.linesMesh.js.map
  60484. var BABYLON;
  60485. (function (BABYLON) {
  60486. /**
  60487. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60488. * The underlying implementation relies on an associative array to ensure the best performances.
  60489. * The value can be anything including 'null' but except 'undefined'
  60490. */
  60491. var StringDictionary = /** @class */ (function () {
  60492. function StringDictionary() {
  60493. this._count = 0;
  60494. this._data = {};
  60495. }
  60496. /**
  60497. * This will clear this dictionary and copy the content from the 'source' one.
  60498. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60499. * @param source the dictionary to take the content from and copy to this dictionary
  60500. */
  60501. StringDictionary.prototype.copyFrom = function (source) {
  60502. var _this = this;
  60503. this.clear();
  60504. source.forEach(function (t, v) { return _this.add(t, v); });
  60505. };
  60506. /**
  60507. * Get a value based from its key
  60508. * @param key the given key to get the matching value from
  60509. * @return the value if found, otherwise undefined is returned
  60510. */
  60511. StringDictionary.prototype.get = function (key) {
  60512. var val = this._data[key];
  60513. if (val !== undefined) {
  60514. return val;
  60515. }
  60516. return undefined;
  60517. };
  60518. /**
  60519. * Get a value from its key or add it if it doesn't exist.
  60520. * This method will ensure you that a given key/data will be present in the dictionary.
  60521. * @param key the given key to get the matching value from
  60522. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60523. * The factory will only be invoked if there's no data for the given key.
  60524. * @return the value corresponding to the key.
  60525. */
  60526. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60527. var val = this.get(key);
  60528. if (val !== undefined) {
  60529. return val;
  60530. }
  60531. val = factory(key);
  60532. if (val) {
  60533. this.add(key, val);
  60534. }
  60535. return val;
  60536. };
  60537. /**
  60538. * Get a value from its key if present in the dictionary otherwise add it
  60539. * @param key the key to get the value from
  60540. * @param val if there's no such key/value pair in the dictionary add it with this value
  60541. * @return the value corresponding to the key
  60542. */
  60543. StringDictionary.prototype.getOrAdd = function (key, val) {
  60544. var curVal = this.get(key);
  60545. if (curVal !== undefined) {
  60546. return curVal;
  60547. }
  60548. this.add(key, val);
  60549. return val;
  60550. };
  60551. /**
  60552. * Check if there's a given key in the dictionary
  60553. * @param key the key to check for
  60554. * @return true if the key is present, false otherwise
  60555. */
  60556. StringDictionary.prototype.contains = function (key) {
  60557. return this._data[key] !== undefined;
  60558. };
  60559. /**
  60560. * Add a new key and its corresponding value
  60561. * @param key the key to add
  60562. * @param value the value corresponding to the key
  60563. * @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
  60564. */
  60565. StringDictionary.prototype.add = function (key, value) {
  60566. if (this._data[key] !== undefined) {
  60567. return false;
  60568. }
  60569. this._data[key] = value;
  60570. ++this._count;
  60571. return true;
  60572. };
  60573. StringDictionary.prototype.set = function (key, value) {
  60574. if (this._data[key] === undefined) {
  60575. return false;
  60576. }
  60577. this._data[key] = value;
  60578. return true;
  60579. };
  60580. /**
  60581. * Get the element of the given key and remove it from the dictionary
  60582. * @param key
  60583. */
  60584. StringDictionary.prototype.getAndRemove = function (key) {
  60585. var val = this.get(key);
  60586. if (val !== undefined) {
  60587. delete this._data[key];
  60588. --this._count;
  60589. return val;
  60590. }
  60591. return null;
  60592. };
  60593. /**
  60594. * Remove a key/value from the dictionary.
  60595. * @param key the key to remove
  60596. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60597. */
  60598. StringDictionary.prototype.remove = function (key) {
  60599. if (this.contains(key)) {
  60600. delete this._data[key];
  60601. --this._count;
  60602. return true;
  60603. }
  60604. return false;
  60605. };
  60606. /**
  60607. * Clear the whole content of the dictionary
  60608. */
  60609. StringDictionary.prototype.clear = function () {
  60610. this._data = {};
  60611. this._count = 0;
  60612. };
  60613. Object.defineProperty(StringDictionary.prototype, "count", {
  60614. get: function () {
  60615. return this._count;
  60616. },
  60617. enumerable: true,
  60618. configurable: true
  60619. });
  60620. /**
  60621. * Execute a callback on each key/val of the dictionary.
  60622. * Note that you can remove any element in this dictionary in the callback implementation
  60623. * @param callback the callback to execute on a given key/value pair
  60624. */
  60625. StringDictionary.prototype.forEach = function (callback) {
  60626. for (var cur in this._data) {
  60627. var val = this._data[cur];
  60628. callback(cur, val);
  60629. }
  60630. };
  60631. /**
  60632. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60633. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60634. * Note that you can remove any element in this dictionary in the callback implementation
  60635. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60636. */
  60637. StringDictionary.prototype.first = function (callback) {
  60638. for (var cur in this._data) {
  60639. var val = this._data[cur];
  60640. var res = callback(cur, val);
  60641. if (res) {
  60642. return res;
  60643. }
  60644. }
  60645. return null;
  60646. };
  60647. return StringDictionary;
  60648. }());
  60649. BABYLON.StringDictionary = StringDictionary;
  60650. })(BABYLON || (BABYLON = {}));
  60651. //# sourceMappingURL=babylon.stringDictionary.js.map
  60652. var BABYLON;
  60653. (function (BABYLON) {
  60654. var Debug;
  60655. (function (Debug) {
  60656. /**
  60657. * Class used to render a debug view of a given skeleton
  60658. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  60659. */
  60660. var SkeletonViewer = /** @class */ (function () {
  60661. /**
  60662. * Creates a new SkeletonViewer
  60663. * @param skeleton defines the skeleton to render
  60664. * @param mesh defines the mesh attached to the skeleton
  60665. * @param scene defines the hosting scene
  60666. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  60667. * @param renderingGroupId defines the rendering group id to use with the viewer
  60668. */
  60669. function SkeletonViewer(
  60670. /** defines the skeleton to render */
  60671. skeleton,
  60672. /** defines the mesh attached to the skeleton */
  60673. mesh, scene,
  60674. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  60675. autoUpdateBonesMatrices,
  60676. /** defines the rendering group id to use with the viewer */
  60677. renderingGroupId) {
  60678. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60679. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60680. this.skeleton = skeleton;
  60681. this.mesh = mesh;
  60682. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60683. this.renderingGroupId = renderingGroupId;
  60684. /** Gets or sets the color used to render the skeleton */
  60685. this.color = BABYLON.Color3.White();
  60686. this._debugLines = new Array();
  60687. this._isEnabled = false;
  60688. this._scene = scene;
  60689. this.update();
  60690. this._renderFunction = this.update.bind(this);
  60691. }
  60692. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60693. get: function () {
  60694. return this._isEnabled;
  60695. },
  60696. /** Gets or sets a boolean indicating if the viewer is enabled */
  60697. set: function (value) {
  60698. if (this._isEnabled === value) {
  60699. return;
  60700. }
  60701. this._isEnabled = value;
  60702. if (value) {
  60703. this._scene.registerBeforeRender(this._renderFunction);
  60704. }
  60705. else {
  60706. this._scene.unregisterBeforeRender(this._renderFunction);
  60707. }
  60708. },
  60709. enumerable: true,
  60710. configurable: true
  60711. });
  60712. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60713. if (x === void 0) { x = 0; }
  60714. if (y === void 0) { y = 0; }
  60715. if (z === void 0) { z = 0; }
  60716. var tmat = BABYLON.Tmp.Matrix[0];
  60717. var parentBone = bone.getParent();
  60718. tmat.copyFrom(bone.getLocalMatrix());
  60719. if (x !== 0 || y !== 0 || z !== 0) {
  60720. var tmat2 = BABYLON.Tmp.Matrix[1];
  60721. BABYLON.Matrix.IdentityToRef(tmat2);
  60722. tmat2.m[12] = x;
  60723. tmat2.m[13] = y;
  60724. tmat2.m[14] = z;
  60725. tmat2.multiplyToRef(tmat, tmat);
  60726. }
  60727. if (parentBone) {
  60728. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60729. }
  60730. tmat.multiplyToRef(meshMat, tmat);
  60731. position.x = tmat.m[12];
  60732. position.y = tmat.m[13];
  60733. position.z = tmat.m[14];
  60734. };
  60735. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60736. var len = bones.length;
  60737. var meshPos = this.mesh.position;
  60738. for (var i = 0; i < len; i++) {
  60739. var bone = bones[i];
  60740. var points = this._debugLines[i];
  60741. if (!points) {
  60742. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60743. this._debugLines[i] = points;
  60744. }
  60745. this._getBonePosition(points[0], bone, meshMat);
  60746. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60747. points[0].subtractInPlace(meshPos);
  60748. points[1].subtractInPlace(meshPos);
  60749. }
  60750. };
  60751. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60752. var len = bones.length;
  60753. var boneNum = 0;
  60754. var meshPos = this.mesh.position;
  60755. for (var i = len - 1; i >= 0; i--) {
  60756. var childBone = bones[i];
  60757. var parentBone = childBone.getParent();
  60758. if (!parentBone) {
  60759. continue;
  60760. }
  60761. var points = this._debugLines[boneNum];
  60762. if (!points) {
  60763. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60764. this._debugLines[boneNum] = points;
  60765. }
  60766. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  60767. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  60768. points[0].subtractInPlace(meshPos);
  60769. points[1].subtractInPlace(meshPos);
  60770. boneNum++;
  60771. }
  60772. };
  60773. /** Update the viewer to sync with current skeleton state */
  60774. SkeletonViewer.prototype.update = function () {
  60775. if (this.autoUpdateBonesMatrices) {
  60776. this.skeleton.computeAbsoluteTransforms();
  60777. }
  60778. if (this.skeleton.bones[0].length === undefined) {
  60779. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60780. }
  60781. else {
  60782. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60783. }
  60784. if (!this._debugMesh) {
  60785. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  60786. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60787. }
  60788. else {
  60789. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60790. }
  60791. this._debugMesh.position.copyFrom(this.mesh.position);
  60792. this._debugMesh.color = this.color;
  60793. };
  60794. /** Release associated resources */
  60795. SkeletonViewer.prototype.dispose = function () {
  60796. if (this._debugMesh) {
  60797. this.isEnabled = false;
  60798. this._debugMesh.dispose();
  60799. this._debugMesh = null;
  60800. }
  60801. };
  60802. return SkeletonViewer;
  60803. }());
  60804. Debug.SkeletonViewer = SkeletonViewer;
  60805. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60806. })(BABYLON || (BABYLON = {}));
  60807. //# sourceMappingURL=babylon.skeletonViewer.js.map
  60808. /**
  60809. * Module Debug contains the (visual) components to debug a scene correctly
  60810. */
  60811. var BABYLON;
  60812. (function (BABYLON) {
  60813. var Debug;
  60814. (function (Debug) {
  60815. /**
  60816. * The Axes viewer will show 3 axes in a specific point in space
  60817. */
  60818. var AxesViewer = /** @class */ (function () {
  60819. /**
  60820. * Creates a new AxesViewer
  60821. * @param scene defines the hosting scene
  60822. * @param scaleLines defines a number used to scale line length (1 by default)
  60823. */
  60824. function AxesViewer(scene, scaleLines) {
  60825. if (scaleLines === void 0) { scaleLines = 1; }
  60826. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60827. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60828. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60829. /**
  60830. * Gets or sets a number used to scale line length
  60831. */
  60832. this.scaleLines = 1;
  60833. this.scaleLines = scaleLines;
  60834. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  60835. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  60836. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  60837. this._xmesh.renderingGroupId = 2;
  60838. this._ymesh.renderingGroupId = 2;
  60839. this._zmesh.renderingGroupId = 2;
  60840. this._xmesh.material.checkReadyOnlyOnce = true;
  60841. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60842. this._ymesh.material.checkReadyOnlyOnce = true;
  60843. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60844. this._zmesh.material.checkReadyOnlyOnce = true;
  60845. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60846. this.scene = scene;
  60847. }
  60848. /**
  60849. * Force the viewer to update
  60850. * @param position defines the position of the viewer
  60851. * @param xaxis defines the x axis of the viewer
  60852. * @param yaxis defines the y axis of the viewer
  60853. * @param zaxis defines the z axis of the viewer
  60854. */
  60855. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60856. var scaleLines = this.scaleLines;
  60857. if (this._xmesh) {
  60858. this._xmesh.position.copyFrom(position);
  60859. }
  60860. if (this._ymesh) {
  60861. this._ymesh.position.copyFrom(position);
  60862. }
  60863. if (this._zmesh) {
  60864. this._zmesh.position.copyFrom(position);
  60865. }
  60866. var point2 = this._xline[1];
  60867. point2.x = xaxis.x * scaleLines;
  60868. point2.y = xaxis.y * scaleLines;
  60869. point2.z = xaxis.z * scaleLines;
  60870. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  60871. point2 = this._yline[1];
  60872. point2.x = yaxis.x * scaleLines;
  60873. point2.y = yaxis.y * scaleLines;
  60874. point2.z = yaxis.z * scaleLines;
  60875. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  60876. point2 = this._zline[1];
  60877. point2.x = zaxis.x * scaleLines;
  60878. point2.y = zaxis.y * scaleLines;
  60879. point2.z = zaxis.z * scaleLines;
  60880. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  60881. };
  60882. /** Releases resources */
  60883. AxesViewer.prototype.dispose = function () {
  60884. if (this._xmesh) {
  60885. this._xmesh.dispose();
  60886. }
  60887. if (this._ymesh) {
  60888. this._ymesh.dispose();
  60889. }
  60890. if (this._zmesh) {
  60891. this._zmesh.dispose();
  60892. }
  60893. this._xmesh = null;
  60894. this._ymesh = null;
  60895. this._zmesh = null;
  60896. this.scene = null;
  60897. };
  60898. return AxesViewer;
  60899. }());
  60900. Debug.AxesViewer = AxesViewer;
  60901. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60902. })(BABYLON || (BABYLON = {}));
  60903. //# sourceMappingURL=babylon.axesViewer.js.map
  60904. var BABYLON;
  60905. (function (BABYLON) {
  60906. var Debug;
  60907. (function (Debug) {
  60908. /**
  60909. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  60910. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  60911. */
  60912. var BoneAxesViewer = /** @class */ (function (_super) {
  60913. __extends(BoneAxesViewer, _super);
  60914. /**
  60915. * Creates a new BoneAxesViewer
  60916. * @param scene defines the hosting scene
  60917. * @param bone defines the target bone
  60918. * @param mesh defines the target mesh
  60919. * @param scaleLines defines a scaling factor for line length (1 by default)
  60920. */
  60921. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  60922. if (scaleLines === void 0) { scaleLines = 1; }
  60923. var _this = _super.call(this, scene, scaleLines) || this;
  60924. /** Gets current position */
  60925. _this.pos = BABYLON.Vector3.Zero();
  60926. /** Gets direction of X axis */
  60927. _this.xaxis = BABYLON.Vector3.Zero();
  60928. /** Gets direction of Y axis */
  60929. _this.yaxis = BABYLON.Vector3.Zero();
  60930. /** Gets direction of Z axis */
  60931. _this.zaxis = BABYLON.Vector3.Zero();
  60932. _this.mesh = mesh;
  60933. _this.bone = bone;
  60934. return _this;
  60935. }
  60936. /**
  60937. * Force the viewer to update
  60938. */
  60939. BoneAxesViewer.prototype.update = function () {
  60940. if (!this.mesh || !this.bone) {
  60941. return;
  60942. }
  60943. var bone = this.bone;
  60944. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  60945. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  60946. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  60947. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  60948. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  60949. };
  60950. /** Releases resources */
  60951. BoneAxesViewer.prototype.dispose = function () {
  60952. if (this.mesh) {
  60953. this.mesh = null;
  60954. this.bone = null;
  60955. _super.prototype.dispose.call(this);
  60956. }
  60957. };
  60958. return BoneAxesViewer;
  60959. }(Debug.AxesViewer));
  60960. Debug.BoneAxesViewer = BoneAxesViewer;
  60961. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60962. })(BABYLON || (BABYLON = {}));
  60963. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  60964. var BABYLON;
  60965. (function (BABYLON) {
  60966. var RayHelper = /** @class */ (function () {
  60967. function RayHelper(ray) {
  60968. this.ray = ray;
  60969. }
  60970. RayHelper.CreateAndShow = function (ray, scene, color) {
  60971. var helper = new RayHelper(ray);
  60972. helper.show(scene, color);
  60973. return helper;
  60974. };
  60975. RayHelper.prototype.show = function (scene, color) {
  60976. if (!this._renderFunction && this.ray) {
  60977. var ray = this.ray;
  60978. this._renderFunction = this._render.bind(this);
  60979. this._scene = scene;
  60980. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  60981. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  60982. if (this._renderFunction) {
  60983. this._scene.registerBeforeRender(this._renderFunction);
  60984. }
  60985. }
  60986. if (color && this._renderLine) {
  60987. this._renderLine.color.copyFrom(color);
  60988. }
  60989. };
  60990. RayHelper.prototype.hide = function () {
  60991. if (this._renderFunction && this._scene) {
  60992. this._scene.unregisterBeforeRender(this._renderFunction);
  60993. this._scene = null;
  60994. this._renderFunction = null;
  60995. if (this._renderLine) {
  60996. this._renderLine.dispose();
  60997. this._renderLine = null;
  60998. }
  60999. this._renderPoints = [];
  61000. }
  61001. };
  61002. RayHelper.prototype._render = function () {
  61003. var ray = this.ray;
  61004. if (!ray) {
  61005. return;
  61006. }
  61007. var point = this._renderPoints[1];
  61008. var len = Math.min(ray.length, 1000000);
  61009. point.copyFrom(ray.direction);
  61010. point.scaleInPlace(len);
  61011. point.addInPlace(ray.origin);
  61012. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  61013. };
  61014. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  61015. this._attachedToMesh = mesh;
  61016. var ray = this.ray;
  61017. if (!ray) {
  61018. return;
  61019. }
  61020. if (!ray.direction) {
  61021. ray.direction = BABYLON.Vector3.Zero();
  61022. }
  61023. if (!ray.origin) {
  61024. ray.origin = BABYLON.Vector3.Zero();
  61025. }
  61026. if (length) {
  61027. ray.length = length;
  61028. }
  61029. if (!meshSpaceOrigin) {
  61030. meshSpaceOrigin = BABYLON.Vector3.Zero();
  61031. }
  61032. if (!meshSpaceDirection) {
  61033. // -1 so that this will work with Mesh.lookAt
  61034. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  61035. }
  61036. if (!this._meshSpaceDirection) {
  61037. this._meshSpaceDirection = meshSpaceDirection.clone();
  61038. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  61039. }
  61040. else {
  61041. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  61042. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  61043. }
  61044. if (!this._updateToMeshFunction) {
  61045. this._updateToMeshFunction = this._updateToMesh.bind(this);
  61046. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  61047. }
  61048. this._updateToMesh();
  61049. };
  61050. RayHelper.prototype.detachFromMesh = function () {
  61051. if (this._attachedToMesh) {
  61052. if (this._updateToMeshFunction) {
  61053. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  61054. }
  61055. this._attachedToMesh = null;
  61056. this._updateToMeshFunction = null;
  61057. }
  61058. };
  61059. RayHelper.prototype._updateToMesh = function () {
  61060. var ray = this.ray;
  61061. if (!this._attachedToMesh || !ray) {
  61062. return;
  61063. }
  61064. if (this._attachedToMesh._isDisposed) {
  61065. this.detachFromMesh();
  61066. return;
  61067. }
  61068. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  61069. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  61070. };
  61071. RayHelper.prototype.dispose = function () {
  61072. this.hide();
  61073. this.detachFromMesh();
  61074. this.ray = null;
  61075. };
  61076. return RayHelper;
  61077. }());
  61078. BABYLON.RayHelper = RayHelper;
  61079. })(BABYLON || (BABYLON = {}));
  61080. //# sourceMappingURL=babylon.rayHelper.js.map
  61081. var BABYLON;
  61082. (function (BABYLON) {
  61083. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  61084. get: function () {
  61085. if (!this._debugLayer) {
  61086. this._debugLayer = new DebugLayer(this);
  61087. }
  61088. return this._debugLayer;
  61089. },
  61090. enumerable: true,
  61091. configurable: true
  61092. });
  61093. var DebugLayer = /** @class */ (function () {
  61094. function DebugLayer(scene) {
  61095. var _this = this;
  61096. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  61097. this.onPropertyChangedObservable = new BABYLON.Observable();
  61098. this._scene = scene;
  61099. this._scene.onDisposeObservable.add(function () {
  61100. // Debug layer
  61101. if (_this._scene._debugLayer) {
  61102. _this._scene._debugLayer.hide();
  61103. }
  61104. });
  61105. }
  61106. /** Creates the inspector window. */
  61107. DebugLayer.prototype._createInspector = function (config) {
  61108. if (config === void 0) { config = {}; }
  61109. var popup = config.popup || false;
  61110. var initialTab = config.initialTab || 0;
  61111. var parentElement = config.parentElement || null;
  61112. if (!this._inspector) {
  61113. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  61114. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  61115. } // else nothing to do as instance is already created
  61116. };
  61117. DebugLayer.prototype.isVisible = function () {
  61118. if (!this._inspector) {
  61119. return false;
  61120. }
  61121. return true;
  61122. };
  61123. DebugLayer.prototype.hide = function () {
  61124. if (this._inspector) {
  61125. try {
  61126. this._inspector.dispose();
  61127. }
  61128. catch (e) {
  61129. // If the inspector has been removed directly from the inspector tool
  61130. }
  61131. this.onPropertyChangedObservable.clear();
  61132. this._inspector = null;
  61133. }
  61134. };
  61135. /**
  61136. *
  61137. * Launch the debugLayer.
  61138. *
  61139. * initialTab:
  61140. * | Value | Tab Name |
  61141. * | --- | --- |
  61142. * | 0 | Scene |
  61143. * | 1 | Console |
  61144. * | 2 | Stats |
  61145. * | 3 | Textures |
  61146. * | 4 | Mesh |
  61147. * | 5 | Light |
  61148. * | 6 | Material |
  61149. * | 7 | GLTF |
  61150. * | 8 | GUI |
  61151. * | 9 | Physics |
  61152. * | 10 | Camera |
  61153. * | 11 | Audio |
  61154. *
  61155. */
  61156. DebugLayer.prototype.show = function (config) {
  61157. if (config === void 0) { config = {}; }
  61158. if (typeof this.BJSINSPECTOR == 'undefined') {
  61159. // Load inspector and add it to the DOM
  61160. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  61161. }
  61162. else {
  61163. // Otherwise creates the inspector
  61164. this._createInspector(config);
  61165. }
  61166. };
  61167. /**
  61168. * Gets the active tab
  61169. * @return the index of the active tab or -1 if the inspector is hidden
  61170. */
  61171. DebugLayer.prototype.getActiveTab = function () {
  61172. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  61173. };
  61174. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  61175. return DebugLayer;
  61176. }());
  61177. BABYLON.DebugLayer = DebugLayer;
  61178. })(BABYLON || (BABYLON = {}));
  61179. //# sourceMappingURL=babylon.debugLayer.js.map
  61180. var BABYLON;
  61181. (function (BABYLON) {
  61182. var Debug;
  61183. (function (Debug) {
  61184. /**
  61185. * Used to show the physics impostor around the specific mesh
  61186. */
  61187. var PhysicsViewer = /** @class */ (function () {
  61188. /**
  61189. * Creates a new PhysicsViewer
  61190. * @param scene defines the hosting scene
  61191. */
  61192. function PhysicsViewer(scene) {
  61193. /** @hidden */
  61194. this._impostors = [];
  61195. /** @hidden */
  61196. this._meshes = [];
  61197. /** @hidden */
  61198. this._numMeshes = 0;
  61199. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61200. var physicEngine = this._scene.getPhysicsEngine();
  61201. if (physicEngine) {
  61202. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  61203. }
  61204. }
  61205. /** @hidden */
  61206. PhysicsViewer.prototype._updateDebugMeshes = function () {
  61207. var plugin = this._physicsEnginePlugin;
  61208. for (var i = 0; i < this._numMeshes; i++) {
  61209. var impostor = this._impostors[i];
  61210. if (!impostor) {
  61211. continue;
  61212. }
  61213. if (impostor.isDisposed) {
  61214. this.hideImpostor(this._impostors[i--]);
  61215. }
  61216. else {
  61217. var mesh = this._meshes[i];
  61218. if (mesh && plugin) {
  61219. plugin.syncMeshWithImpostor(mesh, impostor);
  61220. }
  61221. }
  61222. }
  61223. };
  61224. /**
  61225. * Renders a specified physic impostor
  61226. * @param impostor defines the impostor to render
  61227. */
  61228. PhysicsViewer.prototype.showImpostor = function (impostor) {
  61229. if (!this._scene) {
  61230. return;
  61231. }
  61232. for (var i = 0; i < this._numMeshes; i++) {
  61233. if (this._impostors[i] == impostor) {
  61234. return;
  61235. }
  61236. }
  61237. var debugMesh = this._getDebugMesh(impostor, this._scene);
  61238. if (debugMesh) {
  61239. this._impostors[this._numMeshes] = impostor;
  61240. this._meshes[this._numMeshes] = debugMesh;
  61241. if (this._numMeshes === 0) {
  61242. this._renderFunction = this._updateDebugMeshes.bind(this);
  61243. this._scene.registerBeforeRender(this._renderFunction);
  61244. }
  61245. this._numMeshes++;
  61246. }
  61247. };
  61248. /**
  61249. * Hides a specified physic impostor
  61250. * @param impostor defines the impostor to hide
  61251. */
  61252. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  61253. if (!impostor || !this._scene) {
  61254. return;
  61255. }
  61256. var removed = false;
  61257. for (var i = 0; i < this._numMeshes; i++) {
  61258. if (this._impostors[i] == impostor) {
  61259. var mesh = this._meshes[i];
  61260. if (!mesh) {
  61261. continue;
  61262. }
  61263. this._scene.removeMesh(mesh);
  61264. mesh.dispose();
  61265. this._numMeshes--;
  61266. if (this._numMeshes > 0) {
  61267. this._meshes[i] = this._meshes[this._numMeshes];
  61268. this._impostors[i] = this._impostors[this._numMeshes];
  61269. this._meshes[this._numMeshes] = null;
  61270. this._impostors[this._numMeshes] = null;
  61271. }
  61272. else {
  61273. this._meshes[0] = null;
  61274. this._impostors[0] = null;
  61275. }
  61276. removed = true;
  61277. break;
  61278. }
  61279. }
  61280. if (removed && this._numMeshes === 0) {
  61281. this._scene.unregisterBeforeRender(this._renderFunction);
  61282. }
  61283. };
  61284. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  61285. if (!this._debugMaterial) {
  61286. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  61287. this._debugMaterial.wireframe = true;
  61288. }
  61289. return this._debugMaterial;
  61290. };
  61291. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  61292. if (!this._debugBoxMesh) {
  61293. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  61294. this._debugBoxMesh.renderingGroupId = 1;
  61295. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61296. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  61297. scene.removeMesh(this._debugBoxMesh);
  61298. }
  61299. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  61300. };
  61301. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  61302. if (!this._debugSphereMesh) {
  61303. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  61304. this._debugSphereMesh.renderingGroupId = 1;
  61305. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61306. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  61307. scene.removeMesh(this._debugSphereMesh);
  61308. }
  61309. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  61310. };
  61311. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  61312. var mesh = null;
  61313. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  61314. mesh = this._getDebugBoxMesh(scene);
  61315. impostor.getBoxSizeToRef(mesh.scaling);
  61316. }
  61317. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  61318. mesh = this._getDebugSphereMesh(scene);
  61319. var radius = impostor.getRadius();
  61320. mesh.scaling.x = radius * 2;
  61321. mesh.scaling.y = radius * 2;
  61322. mesh.scaling.z = radius * 2;
  61323. }
  61324. return mesh;
  61325. };
  61326. /** Releases all resources */
  61327. PhysicsViewer.prototype.dispose = function () {
  61328. for (var i = 0; i < this._numMeshes; i++) {
  61329. this.hideImpostor(this._impostors[i]);
  61330. }
  61331. if (this._debugBoxMesh) {
  61332. this._debugBoxMesh.dispose();
  61333. }
  61334. if (this._debugSphereMesh) {
  61335. this._debugSphereMesh.dispose();
  61336. }
  61337. if (this._debugMaterial) {
  61338. this._debugMaterial.dispose();
  61339. }
  61340. this._impostors.length = 0;
  61341. this._scene = null;
  61342. this._physicsEnginePlugin = null;
  61343. };
  61344. return PhysicsViewer;
  61345. }());
  61346. Debug.PhysicsViewer = PhysicsViewer;
  61347. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61348. })(BABYLON || (BABYLON = {}));
  61349. //# sourceMappingURL=babylon.physicsViewer.js.map
  61350. var BABYLON;
  61351. (function (BABYLON) {
  61352. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  61353. get: function () {
  61354. return this._forceShowBoundingBoxes || false;
  61355. },
  61356. set: function (value) {
  61357. this._forceShowBoundingBoxes = value;
  61358. // Lazyly creates a BB renderer if needed.
  61359. if (value) {
  61360. this.getBoundingBoxRenderer();
  61361. }
  61362. },
  61363. enumerable: true,
  61364. configurable: true
  61365. });
  61366. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  61367. if (!this._boundingBoxRenderer) {
  61368. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  61369. }
  61370. return this._boundingBoxRenderer;
  61371. };
  61372. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  61373. get: function () {
  61374. return this._showBoundingBox || false;
  61375. },
  61376. set: function (value) {
  61377. this._showBoundingBox = value;
  61378. // Lazyly creates a BB renderer if needed.
  61379. if (value) {
  61380. this.getScene().getBoundingBoxRenderer();
  61381. }
  61382. },
  61383. enumerable: true,
  61384. configurable: true
  61385. });
  61386. var BoundingBoxRenderer = /** @class */ (function () {
  61387. function BoundingBoxRenderer(scene) {
  61388. /**
  61389. * The component name helpfull to identify the component in the list of scene components.
  61390. */
  61391. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  61392. this.frontColor = new BABYLON.Color3(1, 1, 1);
  61393. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  61394. this.showBackLines = true;
  61395. this.renderList = new BABYLON.SmartArray(32);
  61396. this._vertexBuffers = {};
  61397. this.scene = scene;
  61398. scene._addComponent(this);
  61399. }
  61400. /**
  61401. * Registers the component in a given scene
  61402. */
  61403. BoundingBoxRenderer.prototype.register = function () {
  61404. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  61405. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  61406. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  61407. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  61408. };
  61409. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  61410. if (mesh.showSubMeshesBoundingBox) {
  61411. var boundingInfo = subMesh.getBoundingInfo();
  61412. if (boundingInfo !== null && boundingInfo !== undefined) {
  61413. this.renderList.push(boundingInfo.boundingBox);
  61414. }
  61415. }
  61416. };
  61417. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  61418. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  61419. var boundingInfo = sourceMesh.getBoundingInfo();
  61420. this.renderList.push(boundingInfo.boundingBox);
  61421. }
  61422. };
  61423. BoundingBoxRenderer.prototype._prepareRessources = function () {
  61424. if (this._colorShader) {
  61425. return;
  61426. }
  61427. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  61428. attributes: [BABYLON.VertexBuffer.PositionKind],
  61429. uniforms: ["world", "viewProjection", "color"]
  61430. });
  61431. var engine = this.scene.getEngine();
  61432. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  61433. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  61434. this._createIndexBuffer();
  61435. };
  61436. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  61437. var engine = this.scene.getEngine();
  61438. 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]);
  61439. };
  61440. /**
  61441. * Rebuilds the elements related to this component in case of
  61442. * context lost for instance.
  61443. */
  61444. BoundingBoxRenderer.prototype.rebuild = function () {
  61445. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61446. if (vb) {
  61447. vb._rebuild();
  61448. }
  61449. this._createIndexBuffer();
  61450. };
  61451. BoundingBoxRenderer.prototype.reset = function () {
  61452. this.renderList.reset();
  61453. };
  61454. BoundingBoxRenderer.prototype.render = function () {
  61455. if (this.renderList.length === 0) {
  61456. return;
  61457. }
  61458. this._prepareRessources();
  61459. if (!this._colorShader.isReady()) {
  61460. return;
  61461. }
  61462. var engine = this.scene.getEngine();
  61463. engine.setDepthWrite(false);
  61464. this._colorShader._preBind();
  61465. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  61466. var boundingBox = this.renderList.data[boundingBoxIndex];
  61467. var min = boundingBox.minimum;
  61468. var max = boundingBox.maximum;
  61469. var diff = max.subtract(min);
  61470. var median = min.add(diff.scale(0.5));
  61471. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61472. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61473. .multiply(boundingBox.getWorldMatrix());
  61474. // VBOs
  61475. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61476. if (this.showBackLines) {
  61477. // Back
  61478. engine.setDepthFunctionToGreaterOrEqual();
  61479. this.scene.resetCachedMaterial();
  61480. this._colorShader.setColor4("color", this.backColor.toColor4());
  61481. this._colorShader.bind(worldMatrix);
  61482. // Draw order
  61483. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61484. }
  61485. // Front
  61486. engine.setDepthFunctionToLess();
  61487. this.scene.resetCachedMaterial();
  61488. this._colorShader.setColor4("color", this.frontColor.toColor4());
  61489. this._colorShader.bind(worldMatrix);
  61490. // Draw order
  61491. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61492. }
  61493. this._colorShader.unbind();
  61494. engine.setDepthFunctionToLessOrEqual();
  61495. engine.setDepthWrite(true);
  61496. };
  61497. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  61498. this._prepareRessources();
  61499. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  61500. return;
  61501. }
  61502. var engine = this.scene.getEngine();
  61503. engine.setDepthWrite(false);
  61504. engine.setColorWrite(false);
  61505. this._colorShader._preBind();
  61506. var boundingBox = mesh._boundingInfo.boundingBox;
  61507. var min = boundingBox.minimum;
  61508. var max = boundingBox.maximum;
  61509. var diff = max.subtract(min);
  61510. var median = min.add(diff.scale(0.5));
  61511. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61512. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61513. .multiply(boundingBox.getWorldMatrix());
  61514. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61515. engine.setDepthFunctionToLess();
  61516. this.scene.resetCachedMaterial();
  61517. this._colorShader.bind(worldMatrix);
  61518. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61519. this._colorShader.unbind();
  61520. engine.setDepthFunctionToLessOrEqual();
  61521. engine.setDepthWrite(true);
  61522. engine.setColorWrite(true);
  61523. };
  61524. BoundingBoxRenderer.prototype.dispose = function () {
  61525. if (!this._colorShader) {
  61526. return;
  61527. }
  61528. this.renderList.dispose();
  61529. this._colorShader.dispose();
  61530. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61531. if (buffer) {
  61532. buffer.dispose();
  61533. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61534. }
  61535. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  61536. };
  61537. return BoundingBoxRenderer;
  61538. }());
  61539. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  61540. })(BABYLON || (BABYLON = {}));
  61541. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  61542. var BABYLON;
  61543. (function (BABYLON) {
  61544. BABYLON.Engine.prototype.createTransformFeedback = function () {
  61545. return this._gl.createTransformFeedback();
  61546. };
  61547. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  61548. this._gl.deleteTransformFeedback(value);
  61549. };
  61550. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  61551. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  61552. };
  61553. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  61554. if (usePoints === void 0) { usePoints = true; }
  61555. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  61556. };
  61557. BABYLON.Engine.prototype.endTransformFeedback = function () {
  61558. this._gl.endTransformFeedback();
  61559. };
  61560. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  61561. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  61562. };
  61563. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  61564. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  61565. };
  61566. })(BABYLON || (BABYLON = {}));
  61567. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  61568. var BABYLON;
  61569. (function (BABYLON) {
  61570. /**
  61571. * This represents a GPU particle system in Babylon
  61572. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  61573. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  61574. */
  61575. var GPUParticleSystem = /** @class */ (function (_super) {
  61576. __extends(GPUParticleSystem, _super);
  61577. /**
  61578. * Instantiates a GPU particle system.
  61579. * 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.
  61580. * @param name The name of the particle system
  61581. * @param options The options used to create the system
  61582. * @param scene The scene the particle system belongs to
  61583. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  61584. */
  61585. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  61586. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61587. var _this = _super.call(this, name) || this;
  61588. /**
  61589. * The layer mask we are rendering the particles through.
  61590. */
  61591. _this.layerMask = 0x0FFFFFFF;
  61592. _this._accumulatedCount = 0;
  61593. _this._targetIndex = 0;
  61594. _this._currentRenderId = -1;
  61595. _this._started = false;
  61596. _this._stopped = false;
  61597. _this._timeDelta = 0;
  61598. _this._attributesStrideSize = 21;
  61599. _this._actualFrame = 0;
  61600. _this._rawTextureWidth = 256;
  61601. /**
  61602. * An event triggered when the system is disposed.
  61603. */
  61604. _this.onDisposeObservable = new BABYLON.Observable();
  61605. /**
  61606. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  61607. * to override the particles.
  61608. */
  61609. _this.forceDepthWrite = false;
  61610. _this._preWarmDone = false;
  61611. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61612. // Setup the default processing configuration to the scene.
  61613. _this._attachImageProcessingConfiguration(null);
  61614. _this._engine = _this._scene.getEngine();
  61615. if (!options.randomTextureSize) {
  61616. delete options.randomTextureSize;
  61617. }
  61618. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  61619. var optionsAsNumber = options;
  61620. if (isFinite(optionsAsNumber)) {
  61621. fullOptions.capacity = optionsAsNumber;
  61622. }
  61623. _this._capacity = fullOptions.capacity;
  61624. _this._activeCount = fullOptions.capacity;
  61625. _this._currentActiveCount = 0;
  61626. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  61627. _this._scene.particleSystems.push(_this);
  61628. _this._updateEffectOptions = {
  61629. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset"],
  61630. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  61631. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  61632. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  61633. uniformBuffersNames: [],
  61634. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  61635. defines: "",
  61636. fallbacks: null,
  61637. onCompiled: null,
  61638. onError: null,
  61639. indexParameters: null,
  61640. maxSimultaneousLights: 0,
  61641. transformFeedbackVaryings: []
  61642. };
  61643. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  61644. // Random data
  61645. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  61646. var d = [];
  61647. for (var i = 0; i < maxTextureSize; ++i) {
  61648. d.push(Math.random());
  61649. d.push(Math.random());
  61650. d.push(Math.random());
  61651. d.push(Math.random());
  61652. }
  61653. _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);
  61654. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61655. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61656. d = [];
  61657. for (var i = 0; i < maxTextureSize; ++i) {
  61658. d.push(Math.random());
  61659. d.push(Math.random());
  61660. d.push(Math.random());
  61661. d.push(Math.random());
  61662. }
  61663. _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);
  61664. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61665. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61666. _this._randomTextureSize = maxTextureSize;
  61667. return _this;
  61668. }
  61669. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  61670. /**
  61671. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  61672. */
  61673. get: function () {
  61674. if (!BABYLON.Engine.LastCreatedEngine) {
  61675. return false;
  61676. }
  61677. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  61678. },
  61679. enumerable: true,
  61680. configurable: true
  61681. });
  61682. /**
  61683. * Gets the maximum number of particles active at the same time.
  61684. * @returns The max number of active particles.
  61685. */
  61686. GPUParticleSystem.prototype.getCapacity = function () {
  61687. return this._capacity;
  61688. };
  61689. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  61690. /**
  61691. * Gets or set the number of active particles
  61692. */
  61693. get: function () {
  61694. return this._activeCount;
  61695. },
  61696. set: function (value) {
  61697. this._activeCount = Math.min(value, this._capacity);
  61698. },
  61699. enumerable: true,
  61700. configurable: true
  61701. });
  61702. /**
  61703. * Is this system ready to be used/rendered
  61704. * @return true if the system is ready
  61705. */
  61706. GPUParticleSystem.prototype.isReady = function () {
  61707. if (!this._updateEffect) {
  61708. this._recreateUpdateEffect();
  61709. this._recreateRenderEffect();
  61710. return false;
  61711. }
  61712. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61713. return false;
  61714. }
  61715. return true;
  61716. };
  61717. /**
  61718. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61719. * @returns True if it has been started, otherwise false.
  61720. */
  61721. GPUParticleSystem.prototype.isStarted = function () {
  61722. return this._started;
  61723. };
  61724. /**
  61725. * Starts the particle system and begins to emit
  61726. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  61727. */
  61728. GPUParticleSystem.prototype.start = function (delay) {
  61729. var _this = this;
  61730. if (delay === void 0) { delay = 0; }
  61731. if (delay) {
  61732. setTimeout(function () {
  61733. _this.start(0);
  61734. }, delay);
  61735. return;
  61736. }
  61737. this._started = true;
  61738. this._stopped = false;
  61739. this._preWarmDone = false;
  61740. };
  61741. /**
  61742. * Stops the particle system.
  61743. */
  61744. GPUParticleSystem.prototype.stop = function () {
  61745. this._stopped = true;
  61746. };
  61747. /**
  61748. * Remove all active particles
  61749. */
  61750. GPUParticleSystem.prototype.reset = function () {
  61751. this._releaseBuffers();
  61752. this._releaseVAOs();
  61753. this._currentActiveCount = 0;
  61754. this._targetIndex = 0;
  61755. };
  61756. /**
  61757. * Returns the string "GPUParticleSystem"
  61758. * @returns a string containing the class name
  61759. */
  61760. GPUParticleSystem.prototype.getClassName = function () {
  61761. return "GPUParticleSystem";
  61762. };
  61763. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  61764. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  61765. this._releaseBuffers();
  61766. return this;
  61767. };
  61768. /**
  61769. * Adds a new color gradient
  61770. * @param gradient defines the gradient to use (between 0 and 1)
  61771. * @param color defines the color to affect to the specified gradient
  61772. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61773. * @returns the current particle system
  61774. */
  61775. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61776. if (!this._colorGradients) {
  61777. this._colorGradients = [];
  61778. }
  61779. var colorGradient = new BABYLON.ColorGradient();
  61780. colorGradient.gradient = gradient;
  61781. colorGradient.color1 = color1;
  61782. this._colorGradients.push(colorGradient);
  61783. this._colorGradients.sort(function (a, b) {
  61784. if (a.gradient < b.gradient) {
  61785. return -1;
  61786. }
  61787. else if (a.gradient > b.gradient) {
  61788. return 1;
  61789. }
  61790. return 0;
  61791. });
  61792. if (this._colorGradientsTexture) {
  61793. this._colorGradientsTexture.dispose();
  61794. this._colorGradientsTexture = null;
  61795. }
  61796. this._releaseBuffers();
  61797. return this;
  61798. };
  61799. /**
  61800. * Remove a specific color gradient
  61801. * @param gradient defines the gradient to remove
  61802. * @returns the current particle system
  61803. */
  61804. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  61805. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  61806. this._colorGradientsTexture = null;
  61807. return this;
  61808. };
  61809. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  61810. var valueGradient = new BABYLON.FactorGradient();
  61811. valueGradient.gradient = gradient;
  61812. valueGradient.factor1 = factor;
  61813. factorGradients.push(valueGradient);
  61814. factorGradients.sort(function (a, b) {
  61815. if (a.gradient < b.gradient) {
  61816. return -1;
  61817. }
  61818. else if (a.gradient > b.gradient) {
  61819. return 1;
  61820. }
  61821. return 0;
  61822. });
  61823. this._releaseBuffers();
  61824. };
  61825. /**
  61826. * Adds a new size gradient
  61827. * @param gradient defines the gradient to use (between 0 and 1)
  61828. * @param factor defines the size factor to affect to the specified gradient
  61829. * @returns the current particle system
  61830. */
  61831. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  61832. if (!this._sizeGradients) {
  61833. this._sizeGradients = [];
  61834. }
  61835. this._addFactorGradient(this._sizeGradients, gradient, factor);
  61836. if (this._sizeGradientsTexture) {
  61837. this._sizeGradientsTexture.dispose();
  61838. this._sizeGradientsTexture = null;
  61839. }
  61840. this._releaseBuffers();
  61841. return this;
  61842. };
  61843. /**
  61844. * Remove a specific size gradient
  61845. * @param gradient defines the gradient to remove
  61846. * @returns the current particle system
  61847. */
  61848. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61849. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  61850. this._sizeGradientsTexture = null;
  61851. return this;
  61852. };
  61853. /**
  61854. * Adds a new angular speed gradient
  61855. * @param gradient defines the gradient to use (between 0 and 1)
  61856. * @param factor defines the angular speed to affect to the specified gradient
  61857. * @returns the current particle system
  61858. */
  61859. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  61860. if (!this._angularSpeedGradients) {
  61861. this._angularSpeedGradients = [];
  61862. }
  61863. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  61864. if (this._angularSpeedGradientsTexture) {
  61865. this._angularSpeedGradientsTexture.dispose();
  61866. this._angularSpeedGradientsTexture = null;
  61867. }
  61868. this._releaseBuffers();
  61869. return this;
  61870. };
  61871. /**
  61872. * Remove a specific angular speed gradient
  61873. * @param gradient defines the gradient to remove
  61874. * @returns the current particle system
  61875. */
  61876. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61877. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  61878. this._angularSpeedGradientsTexture = null;
  61879. return this;
  61880. };
  61881. /**
  61882. * Adds a new velocity gradient
  61883. * @param gradient defines the gradient to use (between 0 and 1)
  61884. * @param factor defines the velocity to affect to the specified gradient
  61885. * @returns the current particle system
  61886. */
  61887. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  61888. if (!this._velocityGradients) {
  61889. this._velocityGradients = [];
  61890. }
  61891. this._addFactorGradient(this._velocityGradients, gradient, factor);
  61892. if (this._velocityGradientsTexture) {
  61893. this._velocityGradientsTexture.dispose();
  61894. this._velocityGradientsTexture = null;
  61895. }
  61896. this._releaseBuffers();
  61897. return this;
  61898. };
  61899. /**
  61900. * Remove a specific velocity gradient
  61901. * @param gradient defines the gradient to remove
  61902. * @returns the current particle system
  61903. */
  61904. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61905. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  61906. this._velocityGradientsTexture = null;
  61907. return this;
  61908. };
  61909. /**
  61910. * Adds a new limit velocity gradient
  61911. * @param gradient defines the gradient to use (between 0 and 1)
  61912. * @param factor defines the limit velocity value to affect to the specified gradient
  61913. * @returns the current particle system
  61914. */
  61915. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  61916. if (!this._limitVelocityGradients) {
  61917. this._limitVelocityGradients = [];
  61918. }
  61919. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  61920. if (this._limitVelocityGradientsTexture) {
  61921. this._limitVelocityGradientsTexture.dispose();
  61922. this._limitVelocityGradientsTexture = null;
  61923. }
  61924. this._releaseBuffers();
  61925. return this;
  61926. };
  61927. /**
  61928. * Remove a specific limit velocity gradient
  61929. * @param gradient defines the gradient to remove
  61930. * @returns the current particle system
  61931. */
  61932. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61933. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  61934. this._limitVelocityGradientsTexture = null;
  61935. return this;
  61936. };
  61937. /**
  61938. * Adds a new drag gradient
  61939. * @param gradient defines the gradient to use (between 0 and 1)
  61940. * @param factor defines the drag value to affect to the specified gradient
  61941. * @returns the current particle system
  61942. */
  61943. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  61944. if (!this._dragGradients) {
  61945. this._dragGradients = [];
  61946. }
  61947. this._addFactorGradient(this._dragGradients, gradient, factor);
  61948. if (this._dragGradientsTexture) {
  61949. this._dragGradientsTexture.dispose();
  61950. this._dragGradientsTexture = null;
  61951. }
  61952. this._releaseBuffers();
  61953. return this;
  61954. };
  61955. /**
  61956. * Remove a specific drag gradient
  61957. * @param gradient defines the gradient to remove
  61958. * @returns the current particle system
  61959. */
  61960. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  61961. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  61962. this._dragGradientsTexture = null;
  61963. return this;
  61964. };
  61965. /**
  61966. * Not supported by GPUParticleSystem
  61967. * @param gradient defines the gradient to use (between 0 and 1)
  61968. * @param factor defines the emit rate value to affect to the specified gradient
  61969. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61970. * @returns the current particle system
  61971. */
  61972. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  61973. // Do nothing as emit rate is not supported by GPUParticleSystem
  61974. return this;
  61975. };
  61976. /**
  61977. * Not supported by GPUParticleSystem
  61978. * @param gradient defines the gradient to remove
  61979. * @returns the current particle system
  61980. */
  61981. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  61982. // Do nothing as emit rate is not supported by GPUParticleSystem
  61983. return this;
  61984. };
  61985. /**
  61986. * Not supported by GPUParticleSystem
  61987. * @param gradient defines the gradient to use (between 0 and 1)
  61988. * @param factor defines the start size value to affect to the specified gradient
  61989. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61990. * @returns the current particle system
  61991. */
  61992. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  61993. // Do nothing as start size is not supported by GPUParticleSystem
  61994. return this;
  61995. };
  61996. /**
  61997. * Not supported by GPUParticleSystem
  61998. * @param gradient defines the gradient to remove
  61999. * @returns the current particle system
  62000. */
  62001. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  62002. // Do nothing as start size is not supported by GPUParticleSystem
  62003. return this;
  62004. };
  62005. /**
  62006. * Not supported by GPUParticleSystem
  62007. * @param gradient defines the gradient to use (between 0 and 1)
  62008. * @param min defines the color remap minimal range
  62009. * @param max defines the color remap maximal range
  62010. * @returns the current particle system
  62011. */
  62012. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  62013. // Do nothing as start size is not supported by GPUParticleSystem
  62014. return this;
  62015. };
  62016. /**
  62017. * Not supported by GPUParticleSystem
  62018. * @param gradient defines the gradient to remove
  62019. * @returns the current particle system
  62020. */
  62021. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  62022. // Do nothing as start size is not supported by GPUParticleSystem
  62023. return this;
  62024. };
  62025. /**
  62026. * Not supported by GPUParticleSystem
  62027. * @param gradient defines the gradient to use (between 0 and 1)
  62028. * @param min defines the alpha remap minimal range
  62029. * @param max defines the alpha remap maximal range
  62030. * @returns the current particle system
  62031. */
  62032. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  62033. // Do nothing as start size is not supported by GPUParticleSystem
  62034. return this;
  62035. };
  62036. /**
  62037. * Not supported by GPUParticleSystem
  62038. * @param gradient defines the gradient to remove
  62039. * @returns the current particle system
  62040. */
  62041. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  62042. // Do nothing as start size is not supported by GPUParticleSystem
  62043. return this;
  62044. };
  62045. /**
  62046. * Not supported by GPUParticleSystem
  62047. * @param gradient defines the gradient to use (between 0 and 1)
  62048. * @param color defines the color to affect to the specified gradient
  62049. * @returns the current particle system
  62050. */
  62051. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  62052. //Not supported by GPUParticleSystem
  62053. return this;
  62054. };
  62055. /**
  62056. * Not supported by GPUParticleSystem
  62057. * @param gradient defines the gradient to remove
  62058. * @returns the current particle system
  62059. */
  62060. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  62061. //Not supported by GPUParticleSystem
  62062. return this;
  62063. };
  62064. /**
  62065. * Not supported by GPUParticleSystem
  62066. * @returns the list of ramp gradients
  62067. */
  62068. GPUParticleSystem.prototype.getRampGradients = function () {
  62069. return null;
  62070. };
  62071. GPUParticleSystem.prototype._reset = function () {
  62072. this._releaseBuffers();
  62073. };
  62074. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  62075. var updateVertexBuffers = {};
  62076. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  62077. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  62078. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  62079. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  62080. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  62081. var offset = 12;
  62082. if (!this._colorGradientsTexture) {
  62083. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  62084. offset += 4;
  62085. }
  62086. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  62087. offset += 3;
  62088. if (!this._isBillboardBased) {
  62089. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  62090. offset += 3;
  62091. }
  62092. if (this._angularSpeedGradientsTexture) {
  62093. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  62094. offset += 1;
  62095. }
  62096. else {
  62097. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  62098. offset += 2;
  62099. }
  62100. if (this._isAnimationSheetEnabled) {
  62101. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  62102. offset += 1;
  62103. if (this.spriteRandomStartCell) {
  62104. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  62105. offset += 1;
  62106. }
  62107. }
  62108. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  62109. this._engine.bindArrayBuffer(null);
  62110. return vao;
  62111. };
  62112. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  62113. var renderVertexBuffers = {};
  62114. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  62115. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  62116. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  62117. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  62118. var offset = 12;
  62119. if (!this._colorGradientsTexture) {
  62120. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  62121. offset += 4;
  62122. }
  62123. offset += 3; // Direction
  62124. if (!this._isBillboardBased) {
  62125. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  62126. offset += 3;
  62127. }
  62128. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  62129. if (this._angularSpeedGradientsTexture) {
  62130. offset++;
  62131. }
  62132. else {
  62133. offset += 2;
  62134. }
  62135. if (this._isAnimationSheetEnabled) {
  62136. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  62137. offset += 1;
  62138. if (this.spriteRandomStartCell) {
  62139. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  62140. offset += 1;
  62141. }
  62142. }
  62143. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  62144. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  62145. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  62146. this._engine.bindArrayBuffer(null);
  62147. return vao;
  62148. };
  62149. GPUParticleSystem.prototype._initialize = function (force) {
  62150. if (force === void 0) { force = false; }
  62151. if (this._buffer0 && !force) {
  62152. return;
  62153. }
  62154. var engine = this._scene.getEngine();
  62155. var data = new Array();
  62156. if (!this.isBillboardBased) {
  62157. this._attributesStrideSize += 3;
  62158. }
  62159. if (this._colorGradientsTexture) {
  62160. this._attributesStrideSize -= 4;
  62161. }
  62162. if (this._angularSpeedGradientsTexture) {
  62163. this._attributesStrideSize -= 1;
  62164. }
  62165. if (this._isAnimationSheetEnabled) {
  62166. this._attributesStrideSize += 1;
  62167. if (this.spriteRandomStartCell) {
  62168. this._attributesStrideSize += 1;
  62169. }
  62170. }
  62171. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  62172. // position
  62173. data.push(0.0);
  62174. data.push(0.0);
  62175. data.push(0.0);
  62176. // Age and life
  62177. data.push(0.0); // create the particle as a dead one to create a new one at start
  62178. data.push(0.0);
  62179. // Seed
  62180. data.push(Math.random());
  62181. data.push(Math.random());
  62182. data.push(Math.random());
  62183. data.push(Math.random());
  62184. // Size
  62185. data.push(0.0);
  62186. data.push(0.0);
  62187. data.push(0.0);
  62188. if (!this._colorGradientsTexture) {
  62189. // color
  62190. data.push(0.0);
  62191. data.push(0.0);
  62192. data.push(0.0);
  62193. data.push(0.0);
  62194. }
  62195. // direction
  62196. data.push(0.0);
  62197. data.push(0.0);
  62198. data.push(0.0);
  62199. if (!this.isBillboardBased) {
  62200. // initialDirection
  62201. data.push(0.0);
  62202. data.push(0.0);
  62203. data.push(0.0);
  62204. }
  62205. // angle
  62206. data.push(0.0);
  62207. if (!this._angularSpeedGradientsTexture) {
  62208. data.push(0.0);
  62209. }
  62210. if (this._isAnimationSheetEnabled) {
  62211. data.push(0.0);
  62212. if (this.spriteRandomStartCell) {
  62213. data.push(0.0);
  62214. }
  62215. }
  62216. }
  62217. // Sprite data
  62218. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  62219. -0.5, 0.5, 0, 1,
  62220. -0.5, -0.5, 0, 0,
  62221. 0.5, -0.5, 1, 0]);
  62222. // Buffers
  62223. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62224. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62225. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  62226. // Update VAO
  62227. this._updateVAO = [];
  62228. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  62229. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  62230. // Render VAO
  62231. this._renderVAO = [];
  62232. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  62233. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  62234. // Links
  62235. this._sourceBuffer = this._buffer0;
  62236. this._targetBuffer = this._buffer1;
  62237. };
  62238. /** @hidden */
  62239. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  62240. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  62241. if (this._isBillboardBased) {
  62242. defines += "\n#define BILLBOARD";
  62243. }
  62244. if (this._colorGradientsTexture) {
  62245. defines += "\n#define COLORGRADIENTS";
  62246. }
  62247. if (this._sizeGradientsTexture) {
  62248. defines += "\n#define SIZEGRADIENTS";
  62249. }
  62250. if (this._angularSpeedGradientsTexture) {
  62251. defines += "\n#define ANGULARSPEEDGRADIENTS";
  62252. }
  62253. if (this._velocityGradientsTexture) {
  62254. defines += "\n#define VELOCITYGRADIENTS";
  62255. }
  62256. if (this._limitVelocityGradientsTexture) {
  62257. defines += "\n#define LIMITVELOCITYGRADIENTS";
  62258. }
  62259. if (this._dragGradientsTexture) {
  62260. defines += "\n#define DRAGGRADIENTS";
  62261. }
  62262. if (this.isAnimationSheetEnabled) {
  62263. defines += "\n#define ANIMATESHEET";
  62264. if (this.spriteRandomStartCell) {
  62265. defines += "\n#define ANIMATESHEETRANDOMSTART";
  62266. }
  62267. }
  62268. if (this.noiseTexture) {
  62269. defines += "\n#define NOISE";
  62270. }
  62271. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  62272. return;
  62273. }
  62274. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  62275. if (!this._colorGradientsTexture) {
  62276. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  62277. }
  62278. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  62279. if (!this._isBillboardBased) {
  62280. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  62281. }
  62282. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  62283. if (this.isAnimationSheetEnabled) {
  62284. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  62285. if (this.spriteRandomStartCell) {
  62286. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  62287. }
  62288. }
  62289. this._updateEffectOptions.defines = defines;
  62290. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  62291. };
  62292. /** @hidden */
  62293. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  62294. var defines = "";
  62295. if (this._scene.clipPlane) {
  62296. defines = "\n#define CLIPPLANE";
  62297. }
  62298. if (this._scene.clipPlane2) {
  62299. defines = "\n#define CLIPPLANE2";
  62300. }
  62301. if (this._scene.clipPlane3) {
  62302. defines = "\n#define CLIPPLANE3";
  62303. }
  62304. if (this._scene.clipPlane4) {
  62305. defines = "\n#define CLIPPLANE4";
  62306. }
  62307. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  62308. defines = "\n#define BLENDMULTIPLYMODE";
  62309. }
  62310. if (this._isBillboardBased) {
  62311. defines += "\n#define BILLBOARD";
  62312. switch (this.billboardMode) {
  62313. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  62314. defines += "\n#define BILLBOARDY";
  62315. break;
  62316. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  62317. default:
  62318. break;
  62319. }
  62320. }
  62321. if (this._colorGradientsTexture) {
  62322. defines += "\n#define COLORGRADIENTS";
  62323. }
  62324. if (this.isAnimationSheetEnabled) {
  62325. defines += "\n#define ANIMATESHEET";
  62326. }
  62327. if (this._imageProcessingConfiguration) {
  62328. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  62329. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  62330. }
  62331. if (this._renderEffect && this._renderEffect.defines === defines) {
  62332. return;
  62333. }
  62334. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  62335. var samplers = ["textureSampler", "colorGradientSampler"];
  62336. if (BABYLON.ImageProcessingConfiguration) {
  62337. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  62338. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  62339. }
  62340. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  62341. };
  62342. /**
  62343. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  62344. * @param preWarm defines if we are in the pre-warmimg phase
  62345. */
  62346. GPUParticleSystem.prototype.animate = function (preWarm) {
  62347. if (preWarm === void 0) { preWarm = false; }
  62348. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  62349. this._actualFrame += this._timeDelta;
  62350. if (!this._stopped) {
  62351. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  62352. this.stop();
  62353. }
  62354. }
  62355. };
  62356. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  62357. var texture = this[textureName];
  62358. if (!factorGradients || !factorGradients.length || texture) {
  62359. return;
  62360. }
  62361. var data = new Float32Array(this._rawTextureWidth);
  62362. for (var x = 0; x < this._rawTextureWidth; x++) {
  62363. var ratio = x / this._rawTextureWidth;
  62364. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  62365. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  62366. });
  62367. }
  62368. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62369. };
  62370. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  62371. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  62372. };
  62373. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  62374. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  62375. };
  62376. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  62377. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  62378. };
  62379. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  62380. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  62381. };
  62382. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  62383. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  62384. };
  62385. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  62386. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  62387. return;
  62388. }
  62389. var data = new Uint8Array(this._rawTextureWidth * 4);
  62390. var tmpColor = BABYLON.Tmp.Color4[0];
  62391. for (var x = 0; x < this._rawTextureWidth; x++) {
  62392. var ratio = x / this._rawTextureWidth;
  62393. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  62394. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  62395. data[x * 4] = tmpColor.r * 255;
  62396. data[x * 4 + 1] = tmpColor.g * 255;
  62397. data[x * 4 + 2] = tmpColor.b * 255;
  62398. data[x * 4 + 3] = tmpColor.a * 255;
  62399. });
  62400. }
  62401. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62402. };
  62403. /**
  62404. * Renders the particle system in its current state
  62405. * @param preWarm defines if the system should only update the particles but not render them
  62406. * @returns the current number of particles
  62407. */
  62408. GPUParticleSystem.prototype.render = function (preWarm) {
  62409. if (preWarm === void 0) { preWarm = false; }
  62410. if (!this._started) {
  62411. return 0;
  62412. }
  62413. this._createColorGradientTexture();
  62414. this._createSizeGradientTexture();
  62415. this._createAngularSpeedGradientTexture();
  62416. this._createVelocityGradientTexture();
  62417. this._createLimitVelocityGradientTexture();
  62418. this._createDragGradientTexture();
  62419. this._recreateUpdateEffect();
  62420. this._recreateRenderEffect();
  62421. if (!this.isReady()) {
  62422. return 0;
  62423. }
  62424. if (!preWarm) {
  62425. if (!this._preWarmDone && this.preWarmCycles) {
  62426. for (var index = 0; index < this.preWarmCycles; index++) {
  62427. this.animate(true);
  62428. this.render(true);
  62429. }
  62430. this._preWarmDone = true;
  62431. }
  62432. if (this._currentRenderId === this._scene.getRenderId()) {
  62433. return 0;
  62434. }
  62435. this._currentRenderId = this._scene.getRenderId();
  62436. }
  62437. // Get everything ready to render
  62438. this._initialize();
  62439. this._accumulatedCount += this.emitRate * this._timeDelta;
  62440. if (this._accumulatedCount > 1) {
  62441. var intPart = this._accumulatedCount | 0;
  62442. this._accumulatedCount -= intPart;
  62443. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  62444. }
  62445. if (!this._currentActiveCount) {
  62446. return 0;
  62447. }
  62448. // Enable update effect
  62449. this._engine.enableEffect(this._updateEffect);
  62450. this._engine.setState(false);
  62451. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  62452. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  62453. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  62454. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  62455. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  62456. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  62457. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  62458. if (!this._colorGradientsTexture) {
  62459. this._updateEffect.setDirectColor4("color1", this.color1);
  62460. this._updateEffect.setDirectColor4("color2", this.color2);
  62461. }
  62462. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  62463. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  62464. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  62465. this._updateEffect.setVector3("gravity", this.gravity);
  62466. if (this._sizeGradientsTexture) {
  62467. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  62468. }
  62469. if (this._angularSpeedGradientsTexture) {
  62470. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  62471. }
  62472. if (this._velocityGradientsTexture) {
  62473. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  62474. }
  62475. if (this._limitVelocityGradientsTexture) {
  62476. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  62477. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  62478. }
  62479. if (this._dragGradientsTexture) {
  62480. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  62481. }
  62482. if (this.particleEmitterType) {
  62483. this.particleEmitterType.applyToShader(this._updateEffect);
  62484. }
  62485. if (this._isAnimationSheetEnabled) {
  62486. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  62487. }
  62488. if (this.noiseTexture) {
  62489. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  62490. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  62491. }
  62492. var emitterWM;
  62493. if (this.emitter.position) {
  62494. var emitterMesh = this.emitter;
  62495. emitterWM = emitterMesh.getWorldMatrix();
  62496. }
  62497. else {
  62498. var emitterPosition = this.emitter;
  62499. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  62500. }
  62501. this._updateEffect.setMatrix("emitterWM", emitterWM);
  62502. // Bind source VAO
  62503. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  62504. // Update
  62505. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  62506. this._engine.setRasterizerState(false);
  62507. this._engine.beginTransformFeedback(true);
  62508. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  62509. this._engine.endTransformFeedback();
  62510. this._engine.setRasterizerState(true);
  62511. this._engine.bindTransformFeedbackBuffer(null);
  62512. if (!preWarm) {
  62513. // Enable render effect
  62514. this._engine.enableEffect(this._renderEffect);
  62515. var viewMatrix = this._scene.getViewMatrix();
  62516. this._renderEffect.setMatrix("view", viewMatrix);
  62517. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  62518. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  62519. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  62520. if (this._colorGradientsTexture) {
  62521. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  62522. }
  62523. else {
  62524. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  62525. }
  62526. if (this._isAnimationSheetEnabled && this.particleTexture) {
  62527. var baseSize = this.particleTexture.getBaseSize();
  62528. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  62529. }
  62530. if (this._isBillboardBased) {
  62531. var camera = this._scene.activeCamera;
  62532. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  62533. }
  62534. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  62535. var invView = viewMatrix.clone();
  62536. invView.invert();
  62537. this._renderEffect.setMatrix("invView", invView);
  62538. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  62539. }
  62540. // image processing
  62541. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  62542. this._imageProcessingConfiguration.bind(this._renderEffect);
  62543. }
  62544. // Draw order
  62545. switch (this.blendMode) {
  62546. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  62547. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  62548. break;
  62549. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  62550. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  62551. break;
  62552. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  62553. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62554. break;
  62555. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  62556. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  62557. break;
  62558. }
  62559. if (this.forceDepthWrite) {
  62560. this._engine.setDepthWrite(true);
  62561. }
  62562. // Bind source VAO
  62563. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  62564. // Render
  62565. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  62566. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62567. }
  62568. // Switch VAOs
  62569. this._targetIndex++;
  62570. if (this._targetIndex === 2) {
  62571. this._targetIndex = 0;
  62572. }
  62573. // Switch buffers
  62574. var tmpBuffer = this._sourceBuffer;
  62575. this._sourceBuffer = this._targetBuffer;
  62576. this._targetBuffer = tmpBuffer;
  62577. return this._currentActiveCount;
  62578. };
  62579. /**
  62580. * Rebuilds the particle system
  62581. */
  62582. GPUParticleSystem.prototype.rebuild = function () {
  62583. this._initialize(true);
  62584. };
  62585. GPUParticleSystem.prototype._releaseBuffers = function () {
  62586. if (this._buffer0) {
  62587. this._buffer0.dispose();
  62588. this._buffer0 = null;
  62589. }
  62590. if (this._buffer1) {
  62591. this._buffer1.dispose();
  62592. this._buffer1 = null;
  62593. }
  62594. if (this._spriteBuffer) {
  62595. this._spriteBuffer.dispose();
  62596. this._spriteBuffer = null;
  62597. }
  62598. };
  62599. GPUParticleSystem.prototype._releaseVAOs = function () {
  62600. if (!this._updateVAO) {
  62601. return;
  62602. }
  62603. for (var index = 0; index < this._updateVAO.length; index++) {
  62604. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  62605. }
  62606. this._updateVAO = [];
  62607. for (var index = 0; index < this._renderVAO.length; index++) {
  62608. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  62609. }
  62610. this._renderVAO = [];
  62611. };
  62612. /**
  62613. * Disposes the particle system and free the associated resources
  62614. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  62615. */
  62616. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  62617. if (disposeTexture === void 0) { disposeTexture = true; }
  62618. var index = this._scene.particleSystems.indexOf(this);
  62619. if (index > -1) {
  62620. this._scene.particleSystems.splice(index, 1);
  62621. }
  62622. this._releaseBuffers();
  62623. this._releaseVAOs();
  62624. if (this._colorGradientsTexture) {
  62625. this._colorGradientsTexture.dispose();
  62626. this._colorGradientsTexture = null;
  62627. }
  62628. if (this._sizeGradientsTexture) {
  62629. this._sizeGradientsTexture.dispose();
  62630. this._sizeGradientsTexture = null;
  62631. }
  62632. if (this._angularSpeedGradientsTexture) {
  62633. this._angularSpeedGradientsTexture.dispose();
  62634. this._angularSpeedGradientsTexture = null;
  62635. }
  62636. if (this._velocityGradientsTexture) {
  62637. this._velocityGradientsTexture.dispose();
  62638. this._velocityGradientsTexture = null;
  62639. }
  62640. if (this._limitVelocityGradientsTexture) {
  62641. this._limitVelocityGradientsTexture.dispose();
  62642. this._limitVelocityGradientsTexture = null;
  62643. }
  62644. if (this._dragGradientsTexture) {
  62645. this._dragGradientsTexture.dispose();
  62646. this._dragGradientsTexture = null;
  62647. }
  62648. if (this._randomTexture) {
  62649. this._randomTexture.dispose();
  62650. this._randomTexture = null;
  62651. }
  62652. if (this._randomTexture2) {
  62653. this._randomTexture2.dispose();
  62654. this._randomTexture2 = null;
  62655. }
  62656. if (disposeTexture && this.particleTexture) {
  62657. this.particleTexture.dispose();
  62658. this.particleTexture = null;
  62659. }
  62660. if (disposeTexture && this.noiseTexture) {
  62661. this.noiseTexture.dispose();
  62662. this.noiseTexture = null;
  62663. }
  62664. // Callback
  62665. this.onDisposeObservable.notifyObservers(this);
  62666. this.onDisposeObservable.clear();
  62667. };
  62668. /**
  62669. * Clones the particle system.
  62670. * @param name The name of the cloned object
  62671. * @param newEmitter The new emitter to use
  62672. * @returns the cloned particle system
  62673. */
  62674. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  62675. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  62676. BABYLON.Tools.DeepCopy(this, result);
  62677. if (newEmitter === undefined) {
  62678. newEmitter = this.emitter;
  62679. }
  62680. result.emitter = newEmitter;
  62681. if (this.particleTexture) {
  62682. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  62683. }
  62684. return result;
  62685. };
  62686. /**
  62687. * Serializes the particle system to a JSON object.
  62688. * @returns the JSON object
  62689. */
  62690. GPUParticleSystem.prototype.serialize = function () {
  62691. var serializationObject = {};
  62692. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  62693. serializationObject.activeParticleCount = this.activeParticleCount;
  62694. return serializationObject;
  62695. };
  62696. /**
  62697. * Parses a JSON object to create a GPU particle system.
  62698. * @param parsedParticleSystem The JSON object to parse
  62699. * @param scene The scene to create the particle system in
  62700. * @param rootUrl The root url to use to load external dependencies like texture
  62701. * @returns the parsed GPU particle system
  62702. */
  62703. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  62704. var name = parsedParticleSystem.name;
  62705. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  62706. if (parsedParticleSystem.activeParticleCount) {
  62707. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  62708. }
  62709. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62710. return particleSystem;
  62711. };
  62712. return GPUParticleSystem;
  62713. }(BABYLON.BaseParticleSystem));
  62714. BABYLON.GPUParticleSystem = GPUParticleSystem;
  62715. })(BABYLON || (BABYLON = {}));
  62716. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  62717. var BABYLON;
  62718. (function (BABYLON) {
  62719. /**
  62720. * Represents one particle of a solid particle system.
  62721. */
  62722. var SolidParticle = /** @class */ (function () {
  62723. /**
  62724. * Creates a Solid Particle object.
  62725. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  62726. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  62727. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  62728. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  62729. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  62730. * @param shapeId (integer) is the model shape identifier in the SPS.
  62731. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  62732. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  62733. */
  62734. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  62735. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  62736. /**
  62737. * particle global index
  62738. */
  62739. this.idx = 0;
  62740. /**
  62741. * The color of the particle
  62742. */
  62743. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  62744. /**
  62745. * The world space position of the particle.
  62746. */
  62747. this.position = BABYLON.Vector3.Zero();
  62748. /**
  62749. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  62750. */
  62751. this.rotation = BABYLON.Vector3.Zero();
  62752. /**
  62753. * The scaling of the particle.
  62754. */
  62755. this.scaling = BABYLON.Vector3.One();
  62756. /**
  62757. * The uvs of the particle.
  62758. */
  62759. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  62760. /**
  62761. * The current speed of the particle.
  62762. */
  62763. this.velocity = BABYLON.Vector3.Zero();
  62764. /**
  62765. * The pivot point in the particle local space.
  62766. */
  62767. this.pivot = BABYLON.Vector3.Zero();
  62768. /**
  62769. * Must the particle be translated from its pivot point in its local space ?
  62770. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  62771. * Default : false
  62772. */
  62773. this.translateFromPivot = false;
  62774. /**
  62775. * Is the particle active or not ?
  62776. */
  62777. this.alive = true;
  62778. /**
  62779. * Is the particle visible or not ?
  62780. */
  62781. this.isVisible = true;
  62782. /**
  62783. * Index of this particle in the global "positions" array (Internal use)
  62784. * @hidden
  62785. */
  62786. this._pos = 0;
  62787. /**
  62788. * @hidden Index of this particle in the global "indices" array (Internal use)
  62789. */
  62790. this._ind = 0;
  62791. /**
  62792. * ModelShape id of this particle
  62793. */
  62794. this.shapeId = 0;
  62795. /**
  62796. * Index of the particle in its shape id (Internal use)
  62797. */
  62798. this.idxInShape = 0;
  62799. /**
  62800. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  62801. */
  62802. this._stillInvisible = false;
  62803. /**
  62804. * @hidden Last computed particle rotation matrix
  62805. */
  62806. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  62807. /**
  62808. * Parent particle Id, if any.
  62809. * Default null.
  62810. */
  62811. this.parentId = null;
  62812. /**
  62813. * @hidden Internal global position in the SPS.
  62814. */
  62815. this._globalPosition = BABYLON.Vector3.Zero();
  62816. this.idx = particleIndex;
  62817. this._pos = positionIndex;
  62818. this._ind = indiceIndex;
  62819. this._model = model;
  62820. this.shapeId = shapeId;
  62821. this.idxInShape = idxInShape;
  62822. this._sps = sps;
  62823. if (modelBoundingInfo) {
  62824. this._modelBoundingInfo = modelBoundingInfo;
  62825. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  62826. }
  62827. }
  62828. Object.defineProperty(SolidParticle.prototype, "scale", {
  62829. /**
  62830. * Legacy support, changed scale to scaling
  62831. */
  62832. get: function () {
  62833. return this.scaling;
  62834. },
  62835. /**
  62836. * Legacy support, changed scale to scaling
  62837. */
  62838. set: function (scale) {
  62839. this.scaling = scale;
  62840. },
  62841. enumerable: true,
  62842. configurable: true
  62843. });
  62844. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  62845. /**
  62846. * Legacy support, changed quaternion to rotationQuaternion
  62847. */
  62848. get: function () {
  62849. return this.rotationQuaternion;
  62850. },
  62851. /**
  62852. * Legacy support, changed quaternion to rotationQuaternion
  62853. */
  62854. set: function (q) {
  62855. this.rotationQuaternion = q;
  62856. },
  62857. enumerable: true,
  62858. configurable: true
  62859. });
  62860. /**
  62861. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  62862. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  62863. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  62864. * @returns true if it intersects
  62865. */
  62866. SolidParticle.prototype.intersectsMesh = function (target) {
  62867. if (!this._boundingInfo || !target._boundingInfo) {
  62868. return false;
  62869. }
  62870. if (this._sps._bSphereOnly) {
  62871. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  62872. }
  62873. return this._boundingInfo.intersects(target._boundingInfo, false);
  62874. };
  62875. return SolidParticle;
  62876. }());
  62877. BABYLON.SolidParticle = SolidParticle;
  62878. /**
  62879. * Represents the shape of the model used by one particle of a solid particle system.
  62880. * SPS internal tool, don't use it manually.
  62881. */
  62882. var ModelShape = /** @class */ (function () {
  62883. /**
  62884. * 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.
  62885. * SPS internal tool, don't use it manually.
  62886. * @hidden
  62887. */
  62888. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  62889. /**
  62890. * length of the shape in the model indices array (internal use)
  62891. * @hidden
  62892. */
  62893. this._indicesLength = 0;
  62894. this.shapeID = id;
  62895. this._shape = shape;
  62896. this._indicesLength = indicesLength;
  62897. this._shapeUV = shapeUV;
  62898. this._positionFunction = posFunction;
  62899. this._vertexFunction = vtxFunction;
  62900. }
  62901. return ModelShape;
  62902. }());
  62903. BABYLON.ModelShape = ModelShape;
  62904. /**
  62905. * Represents a Depth Sorted Particle in the solid particle system.
  62906. */
  62907. var DepthSortedParticle = /** @class */ (function () {
  62908. function DepthSortedParticle() {
  62909. /**
  62910. * Index of the particle in the "indices" array
  62911. */
  62912. this.ind = 0;
  62913. /**
  62914. * Length of the particle shape in the "indices" array
  62915. */
  62916. this.indicesLength = 0;
  62917. /**
  62918. * Squared distance from the particle to the camera
  62919. */
  62920. this.sqDistance = 0.0;
  62921. }
  62922. return DepthSortedParticle;
  62923. }());
  62924. BABYLON.DepthSortedParticle = DepthSortedParticle;
  62925. })(BABYLON || (BABYLON = {}));
  62926. //# sourceMappingURL=babylon.solidParticle.js.map
  62927. var BABYLON;
  62928. (function (BABYLON) {
  62929. /**
  62930. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  62931. *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.
  62932. * The SPS is also a particle system. It provides some methods to manage the particles.
  62933. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  62934. *
  62935. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  62936. */
  62937. var SolidParticleSystem = /** @class */ (function () {
  62938. /**
  62939. * Creates a SPS (Solid Particle System) object.
  62940. * @param name (String) is the SPS name, this will be the underlying mesh name.
  62941. * @param scene (Scene) is the scene in which the SPS is added.
  62942. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  62943. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  62944. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  62945. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  62946. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  62947. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  62948. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  62949. */
  62950. function SolidParticleSystem(name, scene, options) {
  62951. /**
  62952. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  62953. * Example : var p = SPS.particles[i];
  62954. */
  62955. this.particles = new Array();
  62956. /**
  62957. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  62958. */
  62959. this.nbParticles = 0;
  62960. /**
  62961. * If the particles must ever face the camera (default false). Useful for planar particles.
  62962. */
  62963. this.billboard = false;
  62964. /**
  62965. * Recompute normals when adding a shape
  62966. */
  62967. this.recomputeNormals = true;
  62968. /**
  62969. * This a counter ofr your own usage. It's not set by any SPS functions.
  62970. */
  62971. this.counter = 0;
  62972. /**
  62973. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  62974. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  62975. */
  62976. this.vars = {};
  62977. /**
  62978. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  62979. * @hidden
  62980. */
  62981. this._bSphereOnly = false;
  62982. /**
  62983. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  62984. * @hidden
  62985. */
  62986. this._bSphereRadiusFactor = 1.0;
  62987. this._positions = new Array();
  62988. this._indices = new Array();
  62989. this._normals = new Array();
  62990. this._colors = new Array();
  62991. this._uvs = new Array();
  62992. this._index = 0; // indices index
  62993. this._updatable = true;
  62994. this._pickable = false;
  62995. this._isVisibilityBoxLocked = false;
  62996. this._alwaysVisible = false;
  62997. this._depthSort = false;
  62998. this._shapeCounter = 0;
  62999. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  63000. this._color = new BABYLON.Color4(0, 0, 0, 0);
  63001. this._computeParticleColor = true;
  63002. this._computeParticleTexture = true;
  63003. this._computeParticleRotation = true;
  63004. this._computeParticleVertex = false;
  63005. this._computeBoundingBox = false;
  63006. this._depthSortParticles = true;
  63007. this._cam_axisZ = BABYLON.Vector3.Zero();
  63008. this._cam_axisY = BABYLON.Vector3.Zero();
  63009. this._cam_axisX = BABYLON.Vector3.Zero();
  63010. this._axisZ = BABYLON.Axis.Z;
  63011. this._camDir = BABYLON.Vector3.Zero();
  63012. this._camInvertedPosition = BABYLON.Vector3.Zero();
  63013. this._rotMatrix = new BABYLON.Matrix();
  63014. this._invertMatrix = new BABYLON.Matrix();
  63015. this._rotated = BABYLON.Vector3.Zero();
  63016. this._quaternion = new BABYLON.Quaternion();
  63017. this._vertex = BABYLON.Vector3.Zero();
  63018. this._normal = BABYLON.Vector3.Zero();
  63019. this._yaw = 0.0;
  63020. this._pitch = 0.0;
  63021. this._roll = 0.0;
  63022. this._halfroll = 0.0;
  63023. this._halfpitch = 0.0;
  63024. this._halfyaw = 0.0;
  63025. this._sinRoll = 0.0;
  63026. this._cosRoll = 0.0;
  63027. this._sinPitch = 0.0;
  63028. this._cosPitch = 0.0;
  63029. this._sinYaw = 0.0;
  63030. this._cosYaw = 0.0;
  63031. this._mustUnrotateFixedNormals = false;
  63032. this._minimum = BABYLON.Vector3.Zero();
  63033. this._maximum = BABYLON.Vector3.Zero();
  63034. this._minBbox = BABYLON.Vector3.Zero();
  63035. this._maxBbox = BABYLON.Vector3.Zero();
  63036. this._particlesIntersect = false;
  63037. this._depthSortFunction = function (p1, p2) {
  63038. return (p2.sqDistance - p1.sqDistance);
  63039. };
  63040. this._needs32Bits = false;
  63041. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  63042. this._scaledPivot = BABYLON.Vector3.Zero();
  63043. this._particleHasParent = false;
  63044. this.name = name;
  63045. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63046. this._camera = scene.activeCamera;
  63047. this._pickable = options ? options.isPickable : false;
  63048. this._depthSort = options ? options.enableDepthSort : false;
  63049. this._particlesIntersect = options ? options.particleIntersection : false;
  63050. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  63051. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  63052. if (options && options.updatable !== undefined) {
  63053. this._updatable = options.updatable;
  63054. }
  63055. else {
  63056. this._updatable = true;
  63057. }
  63058. if (this._pickable) {
  63059. this.pickedParticles = [];
  63060. }
  63061. if (this._depthSort) {
  63062. this.depthSortedParticles = [];
  63063. }
  63064. }
  63065. /**
  63066. * Builds the SPS underlying mesh. Returns a standard Mesh.
  63067. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  63068. * @returns the created mesh
  63069. */
  63070. SolidParticleSystem.prototype.buildMesh = function () {
  63071. if (this.nbParticles === 0) {
  63072. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  63073. this.addShape(triangle, 1);
  63074. triangle.dispose();
  63075. }
  63076. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  63077. this._positions32 = new Float32Array(this._positions);
  63078. this._uvs32 = new Float32Array(this._uvs);
  63079. this._colors32 = new Float32Array(this._colors);
  63080. if (this.recomputeNormals) {
  63081. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  63082. }
  63083. this._normals32 = new Float32Array(this._normals);
  63084. this._fixedNormal32 = new Float32Array(this._normals);
  63085. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  63086. this._unrotateFixedNormals();
  63087. }
  63088. var vertexData = new BABYLON.VertexData();
  63089. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  63090. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  63091. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  63092. if (this._uvs32.length > 0) {
  63093. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  63094. }
  63095. if (this._colors32.length > 0) {
  63096. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  63097. }
  63098. var mesh = new BABYLON.Mesh(this.name, this._scene);
  63099. vertexData.applyToMesh(mesh, this._updatable);
  63100. this.mesh = mesh;
  63101. this.mesh.isPickable = this._pickable;
  63102. // free memory
  63103. if (!this._depthSort) {
  63104. this._indices = null;
  63105. }
  63106. this._positions = null;
  63107. this._normals = null;
  63108. this._uvs = null;
  63109. this._colors = null;
  63110. if (!this._updatable) {
  63111. this.particles.length = 0;
  63112. }
  63113. return mesh;
  63114. };
  63115. /**
  63116. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  63117. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  63118. * Thus the particles generated from `digest()` have their property `position` set yet.
  63119. * @param mesh ( Mesh ) is the mesh to be digested
  63120. * @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
  63121. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  63122. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  63123. * @returns the current SPS
  63124. */
  63125. SolidParticleSystem.prototype.digest = function (mesh, options) {
  63126. var size = (options && options.facetNb) || 1;
  63127. var number = (options && options.number) || 0;
  63128. var delta = (options && options.delta) || 0;
  63129. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63130. var meshInd = mesh.getIndices();
  63131. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63132. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63133. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63134. var f = 0; // facet counter
  63135. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  63136. // compute size from number
  63137. if (number) {
  63138. number = (number > totalFacets) ? totalFacets : number;
  63139. size = Math.round(totalFacets / number);
  63140. delta = 0;
  63141. }
  63142. else {
  63143. size = (size > totalFacets) ? totalFacets : size;
  63144. }
  63145. var facetPos = []; // submesh positions
  63146. var facetInd = []; // submesh indices
  63147. var facetUV = []; // submesh UV
  63148. var facetCol = []; // submesh colors
  63149. var barycenter = BABYLON.Vector3.Zero();
  63150. var sizeO = size;
  63151. while (f < totalFacets) {
  63152. size = sizeO + Math.floor((1 + delta) * Math.random());
  63153. if (f > totalFacets - size) {
  63154. size = totalFacets - f;
  63155. }
  63156. // reset temp arrays
  63157. facetPos.length = 0;
  63158. facetInd.length = 0;
  63159. facetUV.length = 0;
  63160. facetCol.length = 0;
  63161. // iterate over "size" facets
  63162. var fi = 0;
  63163. for (var j = f * 3; j < (f + size) * 3; j++) {
  63164. facetInd.push(fi);
  63165. var i = meshInd[j];
  63166. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  63167. if (meshUV) {
  63168. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  63169. }
  63170. if (meshCol) {
  63171. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  63172. }
  63173. fi++;
  63174. }
  63175. // create a model shape for each single particle
  63176. var idx = this.nbParticles;
  63177. var shape = this._posToShape(facetPos);
  63178. var shapeUV = this._uvsToShapeUV(facetUV);
  63179. // compute the barycenter of the shape
  63180. var v;
  63181. for (v = 0; v < shape.length; v++) {
  63182. barycenter.addInPlace(shape[v]);
  63183. }
  63184. barycenter.scaleInPlace(1 / shape.length);
  63185. // shift the shape from its barycenter to the origin
  63186. for (v = 0; v < shape.length; v++) {
  63187. shape[v].subtractInPlace(barycenter);
  63188. }
  63189. var bInfo;
  63190. if (this._particlesIntersect) {
  63191. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  63192. }
  63193. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  63194. // add the particle in the SPS
  63195. var currentPos = this._positions.length;
  63196. var currentInd = this._indices.length;
  63197. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  63198. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  63199. // initialize the particle position
  63200. this.particles[this.nbParticles].position.addInPlace(barycenter);
  63201. this._index += shape.length;
  63202. idx++;
  63203. this.nbParticles++;
  63204. this._shapeCounter++;
  63205. f += size;
  63206. }
  63207. return this;
  63208. };
  63209. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  63210. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  63211. var index = 0;
  63212. var idx = 0;
  63213. for (var p = 0; p < this.particles.length; p++) {
  63214. this._particle = this.particles[p];
  63215. this._shape = this._particle._model._shape;
  63216. if (this._particle.rotationQuaternion) {
  63217. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63218. }
  63219. else {
  63220. this._yaw = this._particle.rotation.y;
  63221. this._pitch = this._particle.rotation.x;
  63222. this._roll = this._particle.rotation.z;
  63223. this._quaternionRotationYPR();
  63224. }
  63225. this._quaternionToRotationMatrix();
  63226. this._rotMatrix.invertToRef(this._invertMatrix);
  63227. for (var pt = 0; pt < this._shape.length; pt++) {
  63228. idx = index + pt * 3;
  63229. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  63230. this._fixedNormal32[idx] = this._normal.x;
  63231. this._fixedNormal32[idx + 1] = this._normal.y;
  63232. this._fixedNormal32[idx + 2] = this._normal.z;
  63233. }
  63234. index = idx + 3;
  63235. }
  63236. };
  63237. //reset copy
  63238. SolidParticleSystem.prototype._resetCopy = function () {
  63239. this._copy.position.x = 0;
  63240. this._copy.position.y = 0;
  63241. this._copy.position.z = 0;
  63242. this._copy.rotation.x = 0;
  63243. this._copy.rotation.y = 0;
  63244. this._copy.rotation.z = 0;
  63245. this._copy.rotationQuaternion = null;
  63246. this._copy.scaling.x = 1.0;
  63247. this._copy.scaling.y = 1.0;
  63248. this._copy.scaling.z = 1.0;
  63249. this._copy.uvs.x = 0;
  63250. this._copy.uvs.y = 0;
  63251. this._copy.uvs.z = 1.0;
  63252. this._copy.uvs.w = 1.0;
  63253. this._copy.color = null;
  63254. this._copy.translateFromPivot = false;
  63255. };
  63256. // _meshBuilder : inserts the shape model in the global SPS mesh
  63257. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  63258. var i;
  63259. var u = 0;
  63260. var c = 0;
  63261. var n = 0;
  63262. this._resetCopy();
  63263. if (options && options.positionFunction) { // call to custom positionFunction
  63264. options.positionFunction(this._copy, idx, idxInShape);
  63265. this._mustUnrotateFixedNormals = true;
  63266. }
  63267. if (this._copy.rotationQuaternion) {
  63268. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63269. }
  63270. else {
  63271. this._yaw = this._copy.rotation.y;
  63272. this._pitch = this._copy.rotation.x;
  63273. this._roll = this._copy.rotation.z;
  63274. this._quaternionRotationYPR();
  63275. }
  63276. this._quaternionToRotationMatrix();
  63277. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  63278. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  63279. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  63280. if (this._copy.translateFromPivot) {
  63281. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63282. }
  63283. else {
  63284. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63285. }
  63286. for (i = 0; i < shape.length; i++) {
  63287. this._vertex.x = shape[i].x;
  63288. this._vertex.y = shape[i].y;
  63289. this._vertex.z = shape[i].z;
  63290. if (options && options.vertexFunction) {
  63291. options.vertexFunction(this._copy, this._vertex, i);
  63292. }
  63293. this._vertex.x *= this._copy.scaling.x;
  63294. this._vertex.y *= this._copy.scaling.y;
  63295. this._vertex.z *= this._copy.scaling.z;
  63296. this._vertex.x -= this._scaledPivot.x;
  63297. this._vertex.y -= this._scaledPivot.y;
  63298. this._vertex.z -= this._scaledPivot.z;
  63299. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63300. this._rotated.addInPlace(this._pivotBackTranslation);
  63301. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  63302. if (meshUV) {
  63303. 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);
  63304. u += 2;
  63305. }
  63306. if (this._copy.color) {
  63307. this._color = this._copy.color;
  63308. }
  63309. else if (meshCol && meshCol[c] !== undefined) {
  63310. this._color.r = meshCol[c];
  63311. this._color.g = meshCol[c + 1];
  63312. this._color.b = meshCol[c + 2];
  63313. this._color.a = meshCol[c + 3];
  63314. }
  63315. else {
  63316. this._color.r = 1.0;
  63317. this._color.g = 1.0;
  63318. this._color.b = 1.0;
  63319. this._color.a = 1.0;
  63320. }
  63321. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  63322. c += 4;
  63323. if (!this.recomputeNormals && meshNor) {
  63324. this._normal.x = meshNor[n];
  63325. this._normal.y = meshNor[n + 1];
  63326. this._normal.z = meshNor[n + 2];
  63327. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  63328. normals.push(this._normal.x, this._normal.y, this._normal.z);
  63329. n += 3;
  63330. }
  63331. }
  63332. for (i = 0; i < meshInd.length; i++) {
  63333. var current_ind = p + meshInd[i];
  63334. indices.push(current_ind);
  63335. if (current_ind > 65535) {
  63336. this._needs32Bits = true;
  63337. }
  63338. }
  63339. if (this._pickable) {
  63340. var nbfaces = meshInd.length / 3;
  63341. for (i = 0; i < nbfaces; i++) {
  63342. this.pickedParticles.push({ idx: idx, faceId: i });
  63343. }
  63344. }
  63345. if (this._depthSort) {
  63346. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  63347. }
  63348. return this._copy;
  63349. };
  63350. // returns a shape array from positions array
  63351. SolidParticleSystem.prototype._posToShape = function (positions) {
  63352. var shape = [];
  63353. for (var i = 0; i < positions.length; i += 3) {
  63354. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  63355. }
  63356. return shape;
  63357. };
  63358. // returns a shapeUV array from a Vector4 uvs
  63359. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  63360. var shapeUV = [];
  63361. if (uvs) {
  63362. for (var i = 0; i < uvs.length; i++)
  63363. shapeUV.push(uvs[i]);
  63364. }
  63365. return shapeUV;
  63366. };
  63367. // adds a new particle object in the particles array
  63368. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  63369. if (bInfo === void 0) { bInfo = null; }
  63370. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  63371. this.particles.push(sp);
  63372. return sp;
  63373. };
  63374. /**
  63375. * Adds some particles to the SPS from the model shape. Returns the shape id.
  63376. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  63377. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  63378. * @param nb (positive integer) the number of particles to be created from this model
  63379. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  63380. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  63381. * @returns the number of shapes in the system
  63382. */
  63383. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  63384. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63385. var meshInd = mesh.getIndices();
  63386. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63387. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63388. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63389. var bbInfo;
  63390. if (this._particlesIntersect) {
  63391. bbInfo = mesh.getBoundingInfo();
  63392. }
  63393. var shape = this._posToShape(meshPos);
  63394. var shapeUV = this._uvsToShapeUV(meshUV);
  63395. var posfunc = options ? options.positionFunction : null;
  63396. var vtxfunc = options ? options.vertexFunction : null;
  63397. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  63398. // particles
  63399. var sp;
  63400. var currentCopy;
  63401. var idx = this.nbParticles;
  63402. for (var i = 0; i < nb; i++) {
  63403. var currentPos = this._positions.length;
  63404. var currentInd = this._indices.length;
  63405. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  63406. if (this._updatable) {
  63407. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  63408. sp.position.copyFrom(currentCopy.position);
  63409. sp.rotation.copyFrom(currentCopy.rotation);
  63410. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  63411. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  63412. }
  63413. if (currentCopy.color && sp.color) {
  63414. sp.color.copyFrom(currentCopy.color);
  63415. }
  63416. sp.scaling.copyFrom(currentCopy.scaling);
  63417. sp.uvs.copyFrom(currentCopy.uvs);
  63418. }
  63419. this._index += shape.length;
  63420. idx++;
  63421. }
  63422. this.nbParticles += nb;
  63423. this._shapeCounter++;
  63424. return this._shapeCounter - 1;
  63425. };
  63426. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  63427. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  63428. this._resetCopy();
  63429. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  63430. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  63431. }
  63432. if (this._copy.rotationQuaternion) {
  63433. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63434. }
  63435. else {
  63436. this._yaw = this._copy.rotation.y;
  63437. this._pitch = this._copy.rotation.x;
  63438. this._roll = this._copy.rotation.z;
  63439. this._quaternionRotationYPR();
  63440. }
  63441. this._quaternionToRotationMatrix();
  63442. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63443. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63444. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63445. if (this._copy.translateFromPivot) {
  63446. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63447. }
  63448. else {
  63449. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63450. }
  63451. this._shape = particle._model._shape;
  63452. for (var pt = 0; pt < this._shape.length; pt++) {
  63453. this._vertex.x = this._shape[pt].x;
  63454. this._vertex.y = this._shape[pt].y;
  63455. this._vertex.z = this._shape[pt].z;
  63456. if (particle._model._vertexFunction) {
  63457. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  63458. }
  63459. this._vertex.x *= this._copy.scaling.x;
  63460. this._vertex.y *= this._copy.scaling.y;
  63461. this._vertex.z *= this._copy.scaling.z;
  63462. this._vertex.x -= this._scaledPivot.x;
  63463. this._vertex.y -= this._scaledPivot.y;
  63464. this._vertex.z -= this._scaledPivot.z;
  63465. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63466. this._rotated.addInPlace(this._pivotBackTranslation);
  63467. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  63468. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  63469. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  63470. }
  63471. particle.position.x = 0.0;
  63472. particle.position.y = 0.0;
  63473. particle.position.z = 0.0;
  63474. particle.rotation.x = 0.0;
  63475. particle.rotation.y = 0.0;
  63476. particle.rotation.z = 0.0;
  63477. particle.rotationQuaternion = null;
  63478. particle.scaling.x = 1.0;
  63479. particle.scaling.y = 1.0;
  63480. particle.scaling.z = 1.0;
  63481. particle.uvs.x = 0.0;
  63482. particle.uvs.y = 0.0;
  63483. particle.uvs.z = 1.0;
  63484. particle.uvs.w = 1.0;
  63485. particle.pivot.x = 0.0;
  63486. particle.pivot.y = 0.0;
  63487. particle.pivot.z = 0.0;
  63488. particle.translateFromPivot = false;
  63489. particle.parentId = null;
  63490. };
  63491. /**
  63492. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  63493. * @returns the SPS.
  63494. */
  63495. SolidParticleSystem.prototype.rebuildMesh = function () {
  63496. for (var p = 0; p < this.particles.length; p++) {
  63497. this._rebuildParticle(this.particles[p]);
  63498. }
  63499. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63500. return this;
  63501. };
  63502. /**
  63503. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  63504. * This method calls `updateParticle()` for each particle of the SPS.
  63505. * For an animated SPS, it is usually called within the render loop.
  63506. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  63507. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  63508. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  63509. * @returns the SPS.
  63510. */
  63511. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  63512. if (start === void 0) { start = 0; }
  63513. if (end === void 0) { end = this.nbParticles - 1; }
  63514. if (update === void 0) { update = true; }
  63515. if (!this._updatable) {
  63516. return this;
  63517. }
  63518. // custom beforeUpdate
  63519. this.beforeUpdateParticles(start, end, update);
  63520. this._cam_axisX.x = 1.0;
  63521. this._cam_axisX.y = 0.0;
  63522. this._cam_axisX.z = 0.0;
  63523. this._cam_axisY.x = 0.0;
  63524. this._cam_axisY.y = 1.0;
  63525. this._cam_axisY.z = 0.0;
  63526. this._cam_axisZ.x = 0.0;
  63527. this._cam_axisZ.y = 0.0;
  63528. this._cam_axisZ.z = 1.0;
  63529. // cases when the World Matrix is to be computed first
  63530. if (this.billboard || this._depthSort) {
  63531. this.mesh.computeWorldMatrix(true);
  63532. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  63533. }
  63534. // if the particles will always face the camera
  63535. if (this.billboard) {
  63536. // compute the camera position and un-rotate it by the current mesh rotation
  63537. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  63538. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  63539. this._cam_axisZ.normalize();
  63540. // same for camera up vector extracted from the cam view matrix
  63541. var view = this._camera.getViewMatrix(true);
  63542. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  63543. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  63544. this._cam_axisY.normalize();
  63545. this._cam_axisX.normalize();
  63546. }
  63547. // if depthSort, compute the camera global position in the mesh local system
  63548. if (this._depthSort) {
  63549. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  63550. }
  63551. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  63552. var idx = 0; // current position index in the global array positions32
  63553. var index = 0; // position start index in the global array positions32 of the current particle
  63554. var colidx = 0; // current color index in the global array colors32
  63555. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  63556. var uvidx = 0; // current uv index in the global array uvs32
  63557. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  63558. var pt = 0; // current index in the particle model shape
  63559. if (this.mesh.isFacetDataEnabled) {
  63560. this._computeBoundingBox = true;
  63561. }
  63562. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  63563. if (this._computeBoundingBox) {
  63564. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  63565. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  63566. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  63567. }
  63568. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  63569. if (this.mesh._boundingInfo) {
  63570. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  63571. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  63572. }
  63573. }
  63574. }
  63575. // particle loop
  63576. index = this.particles[start]._pos;
  63577. var vpos = (index / 3) | 0;
  63578. colorIndex = vpos * 4;
  63579. uvIndex = vpos * 2;
  63580. for (var p = start; p <= end; p++) {
  63581. this._particle = this.particles[p];
  63582. this._shape = this._particle._model._shape;
  63583. this._shapeUV = this._particle._model._shapeUV;
  63584. // call to custom user function to update the particle properties
  63585. this.updateParticle(this._particle);
  63586. // camera-particle distance for depth sorting
  63587. if (this._depthSort && this._depthSortParticles) {
  63588. var dsp = this.depthSortedParticles[p];
  63589. dsp.ind = this._particle._ind;
  63590. dsp.indicesLength = this._particle._model._indicesLength;
  63591. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  63592. }
  63593. // skip the computations for inactive or already invisible particles
  63594. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  63595. // increment indexes for the next particle
  63596. pt = this._shape.length;
  63597. index += pt * 3;
  63598. colorIndex += pt * 4;
  63599. uvIndex += pt * 2;
  63600. continue;
  63601. }
  63602. if (this._particle.isVisible) {
  63603. this._particle._stillInvisible = false; // un-mark permanent invisibility
  63604. this._particleHasParent = (this._particle.parentId !== null);
  63605. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63606. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63607. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63608. // particle rotation matrix
  63609. if (this.billboard) {
  63610. this._particle.rotation.x = 0.0;
  63611. this._particle.rotation.y = 0.0;
  63612. }
  63613. if (this._computeParticleRotation || this.billboard) {
  63614. if (this._particle.rotationQuaternion) {
  63615. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63616. }
  63617. else {
  63618. this._yaw = this._particle.rotation.y;
  63619. this._pitch = this._particle.rotation.x;
  63620. this._roll = this._particle.rotation.z;
  63621. this._quaternionRotationYPR();
  63622. }
  63623. this._quaternionToRotationMatrix();
  63624. }
  63625. if (this._particleHasParent) {
  63626. this._parent = this.particles[this._particle.parentId];
  63627. 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];
  63628. 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];
  63629. 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];
  63630. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  63631. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  63632. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  63633. if (this._computeParticleRotation || this.billboard) {
  63634. 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];
  63635. 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];
  63636. 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];
  63637. 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];
  63638. 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];
  63639. 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];
  63640. 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];
  63641. 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];
  63642. 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];
  63643. }
  63644. }
  63645. else {
  63646. this._particle._globalPosition.x = this._particle.position.x;
  63647. this._particle._globalPosition.y = this._particle.position.y;
  63648. this._particle._globalPosition.z = this._particle.position.z;
  63649. if (this._computeParticleRotation || this.billboard) {
  63650. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  63651. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  63652. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  63653. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  63654. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  63655. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  63656. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  63657. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  63658. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  63659. }
  63660. }
  63661. if (this._particle.translateFromPivot) {
  63662. this._pivotBackTranslation.x = 0.0;
  63663. this._pivotBackTranslation.y = 0.0;
  63664. this._pivotBackTranslation.z = 0.0;
  63665. }
  63666. else {
  63667. this._pivotBackTranslation.x = this._scaledPivot.x;
  63668. this._pivotBackTranslation.y = this._scaledPivot.y;
  63669. this._pivotBackTranslation.z = this._scaledPivot.z;
  63670. }
  63671. // particle vertex loop
  63672. for (pt = 0; pt < this._shape.length; pt++) {
  63673. idx = index + pt * 3;
  63674. colidx = colorIndex + pt * 4;
  63675. uvidx = uvIndex + pt * 2;
  63676. this._vertex.x = this._shape[pt].x;
  63677. this._vertex.y = this._shape[pt].y;
  63678. this._vertex.z = this._shape[pt].z;
  63679. if (this._computeParticleVertex) {
  63680. this.updateParticleVertex(this._particle, this._vertex, pt);
  63681. }
  63682. // positions
  63683. this._vertex.x *= this._particle.scaling.x;
  63684. this._vertex.y *= this._particle.scaling.y;
  63685. this._vertex.z *= this._particle.scaling.z;
  63686. this._vertex.x -= this._scaledPivot.x;
  63687. this._vertex.y -= this._scaledPivot.y;
  63688. this._vertex.z -= this._scaledPivot.z;
  63689. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63690. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63691. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63692. this._rotated.x += this._pivotBackTranslation.x;
  63693. this._rotated.y += this._pivotBackTranslation.y;
  63694. this._rotated.z += this._pivotBackTranslation.z;
  63695. 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;
  63696. 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;
  63697. 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;
  63698. if (this._computeBoundingBox) {
  63699. if (this._positions32[idx] < this._minimum.x) {
  63700. this._minimum.x = this._positions32[idx];
  63701. }
  63702. if (this._positions32[idx] > this._maximum.x) {
  63703. this._maximum.x = this._positions32[idx];
  63704. }
  63705. if (this._positions32[idx + 1] < this._minimum.y) {
  63706. this._minimum.y = this._positions32[idx + 1];
  63707. }
  63708. if (this._positions32[idx + 1] > this._maximum.y) {
  63709. this._maximum.y = this._positions32[idx + 1];
  63710. }
  63711. if (this._positions32[idx + 2] < this._minimum.z) {
  63712. this._minimum.z = this._positions32[idx + 2];
  63713. }
  63714. if (this._positions32[idx + 2] > this._maximum.z) {
  63715. this._maximum.z = this._positions32[idx + 2];
  63716. }
  63717. }
  63718. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  63719. if (!this._computeParticleVertex) {
  63720. this._normal.x = this._fixedNormal32[idx];
  63721. this._normal.y = this._fixedNormal32[idx + 1];
  63722. this._normal.z = this._fixedNormal32[idx + 2];
  63723. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  63724. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  63725. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  63726. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  63727. 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;
  63728. 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;
  63729. }
  63730. if (this._computeParticleColor && this._particle.color) {
  63731. this._colors32[colidx] = this._particle.color.r;
  63732. this._colors32[colidx + 1] = this._particle.color.g;
  63733. this._colors32[colidx + 2] = this._particle.color.b;
  63734. this._colors32[colidx + 3] = this._particle.color.a;
  63735. }
  63736. if (this._computeParticleTexture) {
  63737. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63738. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63739. }
  63740. }
  63741. }
  63742. // particle just set invisible : scaled to zero and positioned at the origin
  63743. else {
  63744. this._particle._stillInvisible = true; // mark the particle as invisible
  63745. for (pt = 0; pt < this._shape.length; pt++) {
  63746. idx = index + pt * 3;
  63747. colidx = colorIndex + pt * 4;
  63748. uvidx = uvIndex + pt * 2;
  63749. this._positions32[idx] = 0.0;
  63750. this._positions32[idx + 1] = 0.0;
  63751. this._positions32[idx + 2] = 0.0;
  63752. this._normals32[idx] = 0.0;
  63753. this._normals32[idx + 1] = 0.0;
  63754. this._normals32[idx + 2] = 0.0;
  63755. if (this._computeParticleColor && this._particle.color) {
  63756. this._colors32[colidx] = this._particle.color.r;
  63757. this._colors32[colidx + 1] = this._particle.color.g;
  63758. this._colors32[colidx + 2] = this._particle.color.b;
  63759. this._colors32[colidx + 3] = this._particle.color.a;
  63760. }
  63761. if (this._computeParticleTexture) {
  63762. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63763. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63764. }
  63765. }
  63766. }
  63767. // if the particle intersections must be computed : update the bbInfo
  63768. if (this._particlesIntersect) {
  63769. var bInfo = this._particle._boundingInfo;
  63770. var bBox = bInfo.boundingBox;
  63771. var bSphere = bInfo.boundingSphere;
  63772. if (!this._bSphereOnly) {
  63773. // place, scale and rotate the particle bbox within the SPS local system, then update it
  63774. for (var b = 0; b < bBox.vectors.length; b++) {
  63775. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  63776. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  63777. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  63778. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63779. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63780. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63781. 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;
  63782. 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;
  63783. 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;
  63784. }
  63785. bBox._update(this.mesh._worldMatrix);
  63786. }
  63787. // place and scale the particle bouding sphere in the SPS local system, then update it
  63788. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  63789. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  63790. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  63791. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  63792. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  63793. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  63794. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  63795. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  63796. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  63797. 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));
  63798. bSphere._update(this.mesh._worldMatrix);
  63799. }
  63800. // increment indexes for the next particle
  63801. index = idx + 3;
  63802. colorIndex = colidx + 4;
  63803. uvIndex = uvidx + 2;
  63804. }
  63805. // if the VBO must be updated
  63806. if (update) {
  63807. if (this._computeParticleColor) {
  63808. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  63809. }
  63810. if (this._computeParticleTexture) {
  63811. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  63812. }
  63813. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63814. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  63815. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  63816. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  63817. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  63818. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  63819. for (var i = 0; i < this._normals32.length; i++) {
  63820. this._fixedNormal32[i] = this._normals32[i];
  63821. }
  63822. }
  63823. if (!this.mesh.areNormalsFrozen) {
  63824. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  63825. }
  63826. }
  63827. if (this._depthSort && this._depthSortParticles) {
  63828. this.depthSortedParticles.sort(this._depthSortFunction);
  63829. var dspl = this.depthSortedParticles.length;
  63830. var sorted = 0;
  63831. var lind = 0;
  63832. var sind = 0;
  63833. var sid = 0;
  63834. for (sorted = 0; sorted < dspl; sorted++) {
  63835. lind = this.depthSortedParticles[sorted].indicesLength;
  63836. sind = this.depthSortedParticles[sorted].ind;
  63837. for (var i = 0; i < lind; i++) {
  63838. this._indices32[sid] = this._indices[sind + i];
  63839. sid++;
  63840. }
  63841. }
  63842. this.mesh.updateIndices(this._indices32);
  63843. }
  63844. }
  63845. if (this._computeBoundingBox) {
  63846. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  63847. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  63848. }
  63849. this.afterUpdateParticles(start, end, update);
  63850. return this;
  63851. };
  63852. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  63853. this._halfroll = this._roll * 0.5;
  63854. this._halfpitch = this._pitch * 0.5;
  63855. this._halfyaw = this._yaw * 0.5;
  63856. this._sinRoll = Math.sin(this._halfroll);
  63857. this._cosRoll = Math.cos(this._halfroll);
  63858. this._sinPitch = Math.sin(this._halfpitch);
  63859. this._cosPitch = Math.cos(this._halfpitch);
  63860. this._sinYaw = Math.sin(this._halfyaw);
  63861. this._cosYaw = Math.cos(this._halfyaw);
  63862. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  63863. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  63864. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  63865. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  63866. };
  63867. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  63868. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  63869. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  63870. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  63871. this._rotMatrix.m[3] = 0;
  63872. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  63873. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  63874. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  63875. this._rotMatrix.m[7] = 0;
  63876. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  63877. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  63878. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  63879. this._rotMatrix.m[11] = 0;
  63880. this._rotMatrix.m[12] = 0;
  63881. this._rotMatrix.m[13] = 0;
  63882. this._rotMatrix.m[14] = 0;
  63883. this._rotMatrix.m[15] = 1.0;
  63884. };
  63885. /**
  63886. * Disposes the SPS.
  63887. */
  63888. SolidParticleSystem.prototype.dispose = function () {
  63889. this.mesh.dispose();
  63890. this.vars = null;
  63891. // drop references to internal big arrays for the GC
  63892. this._positions = null;
  63893. this._indices = null;
  63894. this._normals = null;
  63895. this._uvs = null;
  63896. this._colors = null;
  63897. this._indices32 = null;
  63898. this._positions32 = null;
  63899. this._normals32 = null;
  63900. this._fixedNormal32 = null;
  63901. this._uvs32 = null;
  63902. this._colors32 = null;
  63903. this.pickedParticles = null;
  63904. };
  63905. /**
  63906. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  63907. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63908. * @returns the SPS.
  63909. */
  63910. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  63911. if (!this._isVisibilityBoxLocked) {
  63912. this.mesh.refreshBoundingInfo();
  63913. }
  63914. return this;
  63915. };
  63916. /**
  63917. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  63918. * @param size the size (float) of the visibility box
  63919. * note : this doesn't lock the SPS mesh bounding box.
  63920. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63921. */
  63922. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  63923. var vis = size / 2;
  63924. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  63925. };
  63926. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  63927. /**
  63928. * Gets whether the SPS as always visible or not
  63929. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63930. */
  63931. get: function () {
  63932. return this._alwaysVisible;
  63933. },
  63934. /**
  63935. * Sets the SPS as always visible or not
  63936. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63937. */
  63938. set: function (val) {
  63939. this._alwaysVisible = val;
  63940. this.mesh.alwaysSelectAsActiveMesh = val;
  63941. },
  63942. enumerable: true,
  63943. configurable: true
  63944. });
  63945. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  63946. /**
  63947. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63948. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63949. */
  63950. get: function () {
  63951. return this._isVisibilityBoxLocked;
  63952. },
  63953. /**
  63954. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63955. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63956. */
  63957. set: function (val) {
  63958. this._isVisibilityBoxLocked = val;
  63959. var boundingInfo = this.mesh.getBoundingInfo();
  63960. boundingInfo.isLocked = val;
  63961. },
  63962. enumerable: true,
  63963. configurable: true
  63964. });
  63965. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  63966. /**
  63967. * Gets if `setParticles()` computes the particle rotations or not.
  63968. * Default value : true. The SPS is faster when it's set to false.
  63969. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63970. */
  63971. get: function () {
  63972. return this._computeParticleRotation;
  63973. },
  63974. /**
  63975. * Tells to `setParticles()` to compute the particle rotations or not.
  63976. * Default value : true. The SPS is faster when it's set to false.
  63977. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63978. */
  63979. set: function (val) {
  63980. this._computeParticleRotation = val;
  63981. },
  63982. enumerable: true,
  63983. configurable: true
  63984. });
  63985. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  63986. /**
  63987. * Gets if `setParticles()` computes the particle colors or not.
  63988. * Default value : true. The SPS is faster when it's set to false.
  63989. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63990. */
  63991. get: function () {
  63992. return this._computeParticleColor;
  63993. },
  63994. /**
  63995. * Tells to `setParticles()` to compute the particle colors or not.
  63996. * Default value : true. The SPS is faster when it's set to false.
  63997. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63998. */
  63999. set: function (val) {
  64000. this._computeParticleColor = val;
  64001. },
  64002. enumerable: true,
  64003. configurable: true
  64004. });
  64005. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  64006. /**
  64007. * Gets if `setParticles()` computes the particle textures or not.
  64008. * Default value : true. The SPS is faster when it's set to false.
  64009. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  64010. */
  64011. get: function () {
  64012. return this._computeParticleTexture;
  64013. },
  64014. set: function (val) {
  64015. this._computeParticleTexture = val;
  64016. },
  64017. enumerable: true,
  64018. configurable: true
  64019. });
  64020. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  64021. /**
  64022. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  64023. * Default value : false. The SPS is faster when it's set to false.
  64024. * Note : the particle custom vertex positions aren't stored values.
  64025. */
  64026. get: function () {
  64027. return this._computeParticleVertex;
  64028. },
  64029. /**
  64030. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  64031. * Default value : false. The SPS is faster when it's set to false.
  64032. * Note : the particle custom vertex positions aren't stored values.
  64033. */
  64034. set: function (val) {
  64035. this._computeParticleVertex = val;
  64036. },
  64037. enumerable: true,
  64038. configurable: true
  64039. });
  64040. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  64041. /**
  64042. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  64043. */
  64044. get: function () {
  64045. return this._computeBoundingBox;
  64046. },
  64047. /**
  64048. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  64049. */
  64050. set: function (val) {
  64051. this._computeBoundingBox = val;
  64052. },
  64053. enumerable: true,
  64054. configurable: true
  64055. });
  64056. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  64057. /**
  64058. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  64059. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  64060. * Default : `true`
  64061. */
  64062. get: function () {
  64063. return this._depthSortParticles;
  64064. },
  64065. /**
  64066. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  64067. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  64068. * Default : `true`
  64069. */
  64070. set: function (val) {
  64071. this._depthSortParticles = val;
  64072. },
  64073. enumerable: true,
  64074. configurable: true
  64075. });
  64076. // =======================================================================
  64077. // Particle behavior logic
  64078. // these following methods may be overwritten by the user to fit his needs
  64079. /**
  64080. * This function does nothing. It may be overwritten to set all the particle first values.
  64081. * The SPS doesn't call this function, you may have to call it by your own.
  64082. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64083. */
  64084. SolidParticleSystem.prototype.initParticles = function () {
  64085. };
  64086. /**
  64087. * This function does nothing. It may be overwritten to recycle a particle.
  64088. * The SPS doesn't call this function, you may have to call it by your own.
  64089. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64090. * @param particle The particle to recycle
  64091. * @returns the recycled particle
  64092. */
  64093. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  64094. return particle;
  64095. };
  64096. /**
  64097. * Updates a particle : this function should be overwritten by the user.
  64098. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  64099. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64100. * @example : just set a particle position or velocity and recycle conditions
  64101. * @param particle The particle to update
  64102. * @returns the updated particle
  64103. */
  64104. SolidParticleSystem.prototype.updateParticle = function (particle) {
  64105. return particle;
  64106. };
  64107. /**
  64108. * Updates a vertex of a particle : it can be overwritten by the user.
  64109. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  64110. * @param particle the current particle
  64111. * @param vertex the current index of the current particle
  64112. * @param pt the index of the current vertex in the particle shape
  64113. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  64114. * @example : just set a vertex particle position
  64115. * @returns the updated vertex
  64116. */
  64117. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  64118. return vertex;
  64119. };
  64120. /**
  64121. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  64122. * This does nothing and may be overwritten by the user.
  64123. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64124. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64125. * @param update the boolean update value actually passed to setParticles()
  64126. */
  64127. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  64128. };
  64129. /**
  64130. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  64131. * This will be passed three parameters.
  64132. * This does nothing and may be overwritten by the user.
  64133. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64134. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64135. * @param update the boolean update value actually passed to setParticles()
  64136. */
  64137. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  64138. };
  64139. return SolidParticleSystem;
  64140. }());
  64141. BABYLON.SolidParticleSystem = SolidParticleSystem;
  64142. })(BABYLON || (BABYLON = {}));
  64143. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  64144. var BABYLON;
  64145. (function (BABYLON) {
  64146. /**
  64147. * Class containing static functions to help procedurally build meshes
  64148. */
  64149. var MeshBuilder = /** @class */ (function () {
  64150. function MeshBuilder() {
  64151. }
  64152. MeshBuilder.updateSideOrientation = function (orientation) {
  64153. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  64154. return BABYLON.Mesh.DOUBLESIDE;
  64155. }
  64156. if (orientation === undefined || orientation === null) {
  64157. return BABYLON.Mesh.FRONTSIDE;
  64158. }
  64159. return orientation;
  64160. };
  64161. /**
  64162. * Creates a box mesh
  64163. * * The parameter `size` sets the size (float) of each box side (default 1)
  64164. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  64165. * * 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)
  64166. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64167. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64168. * * 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
  64169. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64170. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  64171. * @param name defines the name of the mesh
  64172. * @param options defines the options used to create the mesh
  64173. * @param scene defines the hosting scene
  64174. * @returns the box mesh
  64175. */
  64176. MeshBuilder.CreateBox = function (name, options, scene) {
  64177. if (scene === void 0) { scene = null; }
  64178. var box = new BABYLON.Mesh(name, scene);
  64179. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64180. box._originalBuilderSideOrientation = options.sideOrientation;
  64181. var vertexData = BABYLON.VertexData.CreateBox(options);
  64182. vertexData.applyToMesh(box, options.updatable);
  64183. return box;
  64184. };
  64185. /**
  64186. * Creates a sphere mesh
  64187. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  64188. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)
  64189. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  64190. * * 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
  64191. * * 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)
  64192. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64193. * * 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
  64194. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64195. * @param name defines the name of the mesh
  64196. * @param options defines the options used to create the mesh
  64197. * @param scene defines the hosting scene
  64198. * @returns the sphere mesh
  64199. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  64200. */
  64201. MeshBuilder.CreateSphere = function (name, options, scene) {
  64202. var sphere = new BABYLON.Mesh(name, scene);
  64203. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64204. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64205. var vertexData = BABYLON.VertexData.CreateSphere(options);
  64206. vertexData.applyToMesh(sphere, options.updatable);
  64207. return sphere;
  64208. };
  64209. /**
  64210. * Creates a plane polygonal mesh. By default, this is a disc
  64211. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  64212. * * 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
  64213. * * 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
  64214. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64215. * * 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
  64216. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64217. * @param name defines the name of the mesh
  64218. * @param options defines the options used to create the mesh
  64219. * @param scene defines the hosting scene
  64220. * @returns the plane polygonal mesh
  64221. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  64222. */
  64223. MeshBuilder.CreateDisc = function (name, options, scene) {
  64224. if (scene === void 0) { scene = null; }
  64225. var disc = new BABYLON.Mesh(name, scene);
  64226. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64227. disc._originalBuilderSideOrientation = options.sideOrientation;
  64228. var vertexData = BABYLON.VertexData.CreateDisc(options);
  64229. vertexData.applyToMesh(disc, options.updatable);
  64230. return disc;
  64231. };
  64232. /**
  64233. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  64234. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  64235. * * 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`)
  64236. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  64237. * * 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
  64238. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64239. * * 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
  64240. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64241. * @param name defines the name of the mesh
  64242. * @param options defines the options used to create the mesh
  64243. * @param scene defines the hosting scene
  64244. * @returns the icosahedron mesh
  64245. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  64246. */
  64247. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  64248. var sphere = new BABYLON.Mesh(name, scene);
  64249. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64250. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64251. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  64252. vertexData.applyToMesh(sphere, options.updatable);
  64253. return sphere;
  64254. };
  64255. ;
  64256. /**
  64257. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64258. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  64259. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  64260. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  64261. * * 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
  64262. * * 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
  64263. * * 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
  64264. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64265. * * 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
  64266. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64267. * * 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
  64268. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  64269. * * 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
  64270. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  64271. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64272. * @param name defines the name of the mesh
  64273. * @param options defines the options used to create the mesh
  64274. * @param scene defines the hosting scene
  64275. * @returns the ribbon mesh
  64276. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  64277. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64278. */
  64279. MeshBuilder.CreateRibbon = function (name, options, scene) {
  64280. if (scene === void 0) { scene = null; }
  64281. var pathArray = options.pathArray;
  64282. var closeArray = options.closeArray;
  64283. var closePath = options.closePath;
  64284. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64285. var instance = options.instance;
  64286. var updatable = options.updatable;
  64287. if (instance) { // existing ribbon instance update
  64288. // positionFunction : ribbon case
  64289. // only pathArray and sideOrientation parameters are taken into account for positions update
  64290. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  64291. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  64292. var positionFunction = function (positions) {
  64293. var minlg = pathArray[0].length;
  64294. var i = 0;
  64295. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  64296. for (var si = 1; si <= ns; si++) {
  64297. for (var p = 0; p < pathArray.length; p++) {
  64298. var path = pathArray[p];
  64299. var l = path.length;
  64300. minlg = (minlg < l) ? minlg : l;
  64301. var j = 0;
  64302. while (j < minlg) {
  64303. positions[i] = path[j].x;
  64304. positions[i + 1] = path[j].y;
  64305. positions[i + 2] = path[j].z;
  64306. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  64307. BABYLON.Tmp.Vector3[0].x = path[j].x;
  64308. }
  64309. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  64310. BABYLON.Tmp.Vector3[1].x = path[j].x;
  64311. }
  64312. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  64313. BABYLON.Tmp.Vector3[0].y = path[j].y;
  64314. }
  64315. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  64316. BABYLON.Tmp.Vector3[1].y = path[j].y;
  64317. }
  64318. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  64319. BABYLON.Tmp.Vector3[0].z = path[j].z;
  64320. }
  64321. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  64322. BABYLON.Tmp.Vector3[1].z = path[j].z;
  64323. }
  64324. j++;
  64325. i += 3;
  64326. }
  64327. if (instance._closePath) {
  64328. positions[i] = path[0].x;
  64329. positions[i + 1] = path[0].y;
  64330. positions[i + 2] = path[0].z;
  64331. i += 3;
  64332. }
  64333. }
  64334. }
  64335. };
  64336. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64337. positionFunction(positions);
  64338. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  64339. instance._boundingInfo.update(instance._worldMatrix);
  64340. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64341. if (options.colors) {
  64342. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64343. for (var c = 0; c < options.colors.length; c++) {
  64344. colors[c * 4] = options.colors[c].r;
  64345. colors[c * 4 + 1] = options.colors[c].g;
  64346. colors[c * 4 + 2] = options.colors[c].b;
  64347. colors[c * 4 + 3] = options.colors[c].a;
  64348. }
  64349. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  64350. }
  64351. if (options.uvs) {
  64352. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64353. for (var i = 0; i < options.uvs.length; i++) {
  64354. uvs[i * 2] = options.uvs[i].x;
  64355. uvs[i * 2 + 1] = options.uvs[i].y;
  64356. }
  64357. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  64358. }
  64359. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  64360. var indices = instance.getIndices();
  64361. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64362. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  64363. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  64364. if (instance._closePath) {
  64365. var indexFirst = 0;
  64366. var indexLast = 0;
  64367. for (var p = 0; p < pathArray.length; p++) {
  64368. indexFirst = instance._idx[p] * 3;
  64369. if (p + 1 < pathArray.length) {
  64370. indexLast = (instance._idx[p + 1] - 1) * 3;
  64371. }
  64372. else {
  64373. indexLast = normals.length - 3;
  64374. }
  64375. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  64376. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  64377. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  64378. normals[indexLast] = normals[indexFirst];
  64379. normals[indexLast + 1] = normals[indexFirst + 1];
  64380. normals[indexLast + 2] = normals[indexFirst + 2];
  64381. }
  64382. }
  64383. if (!(instance.areNormalsFrozen)) {
  64384. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  64385. }
  64386. }
  64387. return instance;
  64388. }
  64389. else { // new ribbon creation
  64390. var ribbon = new BABYLON.Mesh(name, scene);
  64391. ribbon._originalBuilderSideOrientation = sideOrientation;
  64392. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  64393. if (closePath) {
  64394. ribbon._idx = vertexData._idx;
  64395. }
  64396. ribbon._closePath = closePath;
  64397. ribbon._closeArray = closeArray;
  64398. vertexData.applyToMesh(ribbon, updatable);
  64399. return ribbon;
  64400. }
  64401. };
  64402. /**
  64403. * Creates a cylinder or a cone mesh
  64404. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  64405. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  64406. * * 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.
  64407. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  64408. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  64409. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  64410. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  64411. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  64412. * * 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).
  64413. * * 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
  64414. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  64415. * * 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
  64416. * * 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.
  64417. * * If `enclose` is false, a ring surface is one element.
  64418. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  64419. * * 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
  64420. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64421. * * 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
  64422. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64423. * @param name defines the name of the mesh
  64424. * @param options defines the options used to create the mesh
  64425. * @param scene defines the hosting scene
  64426. * @returns the cylinder mesh
  64427. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  64428. */
  64429. MeshBuilder.CreateCylinder = function (name, options, scene) {
  64430. var cylinder = new BABYLON.Mesh(name, scene);
  64431. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64432. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  64433. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  64434. vertexData.applyToMesh(cylinder, options.updatable);
  64435. return cylinder;
  64436. };
  64437. /**
  64438. * Creates a torus mesh
  64439. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  64440. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  64441. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  64442. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64443. * * 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
  64444. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64445. * @param name defines the name of the mesh
  64446. * @param options defines the options used to create the mesh
  64447. * @param scene defines the hosting scene
  64448. * @returns the torus mesh
  64449. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  64450. */
  64451. MeshBuilder.CreateTorus = function (name, options, scene) {
  64452. var torus = new BABYLON.Mesh(name, scene);
  64453. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64454. torus._originalBuilderSideOrientation = options.sideOrientation;
  64455. var vertexData = BABYLON.VertexData.CreateTorus(options);
  64456. vertexData.applyToMesh(torus, options.updatable);
  64457. return torus;
  64458. };
  64459. /**
  64460. * Creates a torus knot mesh
  64461. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  64462. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  64463. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  64464. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  64465. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64466. * * 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
  64467. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64468. * @param name defines the name of the mesh
  64469. * @param options defines the options used to create the mesh
  64470. * @param scene defines the hosting scene
  64471. * @returns the torus knot mesh
  64472. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  64473. */
  64474. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  64475. var torusKnot = new BABYLON.Mesh(name, scene);
  64476. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64477. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  64478. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  64479. vertexData.applyToMesh(torusKnot, options.updatable);
  64480. return torusKnot;
  64481. };
  64482. /**
  64483. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  64484. * * 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
  64485. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  64486. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  64487. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  64488. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  64489. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  64490. * * 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
  64491. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  64492. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64493. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  64494. * @param name defines the name of the new line system
  64495. * @param options defines the options used to create the line system
  64496. * @param scene defines the hosting scene
  64497. * @returns a new line system mesh
  64498. */
  64499. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  64500. var instance = options.instance;
  64501. var lines = options.lines;
  64502. var colors = options.colors;
  64503. if (instance) { // lines update
  64504. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64505. var vertexColor;
  64506. var lineColors;
  64507. if (colors) {
  64508. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64509. }
  64510. var i = 0;
  64511. var c = 0;
  64512. for (var l = 0; l < lines.length; l++) {
  64513. var points = lines[l];
  64514. for (var p = 0; p < points.length; p++) {
  64515. positions[i] = points[p].x;
  64516. positions[i + 1] = points[p].y;
  64517. positions[i + 2] = points[p].z;
  64518. if (colors && vertexColor) {
  64519. lineColors = colors[l];
  64520. vertexColor[c] = lineColors[p].r;
  64521. vertexColor[c + 1] = lineColors[p].g;
  64522. vertexColor[c + 2] = lineColors[p].b;
  64523. vertexColor[c + 3] = lineColors[p].a;
  64524. c += 4;
  64525. }
  64526. i += 3;
  64527. }
  64528. }
  64529. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64530. if (colors && vertexColor) {
  64531. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  64532. }
  64533. return instance;
  64534. }
  64535. // line system creation
  64536. var useVertexColor = (colors) ? true : false;
  64537. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  64538. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  64539. vertexData.applyToMesh(lineSystem, options.updatable);
  64540. return lineSystem;
  64541. };
  64542. /**
  64543. * Creates a line mesh
  64544. * 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
  64545. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64546. * * The parameter `points` is an array successive Vector3
  64547. * * 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
  64548. * * The optional parameter `colors` is an array of successive Color4, one per line point
  64549. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  64550. * * When updating an instance, remember that only point positions can change, not the number of points
  64551. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64552. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  64553. * @param name defines the name of the new line system
  64554. * @param options defines the options used to create the line system
  64555. * @param scene defines the hosting scene
  64556. * @returns a new line mesh
  64557. */
  64558. MeshBuilder.CreateLines = function (name, options, scene) {
  64559. if (scene === void 0) { scene = null; }
  64560. var colors = (options.colors) ? [options.colors] : null;
  64561. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  64562. return lines;
  64563. };
  64564. /**
  64565. * Creates a dashed line mesh
  64566. * * 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
  64567. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64568. * * The parameter `points` is an array successive Vector3
  64569. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  64570. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  64571. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  64572. * * 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
  64573. * * When updating an instance, remember that only point positions can change, not the number of points
  64574. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64575. * @param name defines the name of the mesh
  64576. * @param options defines the options used to create the mesh
  64577. * @param scene defines the hosting scene
  64578. * @returns the dashed line mesh
  64579. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  64580. */
  64581. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  64582. if (scene === void 0) { scene = null; }
  64583. var points = options.points;
  64584. var instance = options.instance;
  64585. var gapSize = options.gapSize || 1;
  64586. var dashSize = options.dashSize || 3;
  64587. if (instance) { // dashed lines update
  64588. var positionFunction = function (positions) {
  64589. var curvect = BABYLON.Vector3.Zero();
  64590. var nbSeg = positions.length / 6;
  64591. var lg = 0;
  64592. var nb = 0;
  64593. var shft = 0;
  64594. var dashshft = 0;
  64595. var curshft = 0;
  64596. var p = 0;
  64597. var i = 0;
  64598. var j = 0;
  64599. for (i = 0; i < points.length - 1; i++) {
  64600. points[i + 1].subtractToRef(points[i], curvect);
  64601. lg += curvect.length();
  64602. }
  64603. shft = lg / nbSeg;
  64604. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  64605. for (i = 0; i < points.length - 1; i++) {
  64606. points[i + 1].subtractToRef(points[i], curvect);
  64607. nb = Math.floor(curvect.length() / shft);
  64608. curvect.normalize();
  64609. j = 0;
  64610. while (j < nb && p < positions.length) {
  64611. curshft = shft * j;
  64612. positions[p] = points[i].x + curshft * curvect.x;
  64613. positions[p + 1] = points[i].y + curshft * curvect.y;
  64614. positions[p + 2] = points[i].z + curshft * curvect.z;
  64615. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  64616. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  64617. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  64618. p += 6;
  64619. j++;
  64620. }
  64621. }
  64622. while (p < positions.length) {
  64623. positions[p] = points[i].x;
  64624. positions[p + 1] = points[i].y;
  64625. positions[p + 2] = points[i].z;
  64626. p += 3;
  64627. }
  64628. };
  64629. instance.updateMeshPositions(positionFunction, false);
  64630. return instance;
  64631. }
  64632. // dashed lines creation
  64633. var dashedLines = new BABYLON.LinesMesh(name, scene);
  64634. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  64635. vertexData.applyToMesh(dashedLines, options.updatable);
  64636. dashedLines.dashSize = dashSize;
  64637. dashedLines.gapSize = gapSize;
  64638. return dashedLines;
  64639. };
  64640. /**
  64641. * 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.
  64642. * * 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.
  64643. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64644. * * 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.
  64645. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  64646. * * 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
  64647. * * 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
  64648. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  64649. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64650. * * 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
  64651. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  64652. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64653. * @param name defines the name of the mesh
  64654. * @param options defines the options used to create the mesh
  64655. * @param scene defines the hosting scene
  64656. * @returns the extruded shape mesh
  64657. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64658. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64659. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64660. */
  64661. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  64662. if (scene === void 0) { scene = null; }
  64663. var path = options.path;
  64664. var shape = options.shape;
  64665. var scale = options.scale || 1;
  64666. var rotation = options.rotation || 0;
  64667. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64668. var updatable = options.updatable;
  64669. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64670. var instance = options.instance || null;
  64671. var invertUV = options.invertUV || false;
  64672. 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);
  64673. };
  64674. /**
  64675. * Creates an custom extruded shape mesh.
  64676. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  64677. * * 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.
  64678. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64679. * * 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
  64680. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  64681. * * 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
  64682. * * It must returns a float value that will be the scale value applied to the shape on each path point
  64683. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  64684. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  64685. * * 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
  64686. * * 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
  64687. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  64688. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64689. * * 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
  64690. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64691. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64692. * @param name defines the name of the mesh
  64693. * @param options defines the options used to create the mesh
  64694. * @param scene defines the hosting scene
  64695. * @returns the custom extruded shape mesh
  64696. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  64697. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64698. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64699. */
  64700. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  64701. var path = options.path;
  64702. var shape = options.shape;
  64703. var scaleFunction = options.scaleFunction || (function () { return 1; });
  64704. var rotationFunction = options.rotationFunction || (function () { return 0; });
  64705. var ribbonCloseArray = options.ribbonCloseArray || false;
  64706. var ribbonClosePath = options.ribbonClosePath || false;
  64707. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64708. var updatable = options.updatable;
  64709. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64710. var instance = options.instance;
  64711. var invertUV = options.invertUV || false;
  64712. 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);
  64713. };
  64714. /**
  64715. * Creates lathe mesh.
  64716. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  64717. * * 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
  64718. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  64719. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  64720. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  64721. * * 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
  64722. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  64723. * * 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
  64724. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64725. * * 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
  64726. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64727. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64728. * @param name defines the name of the mesh
  64729. * @param options defines the options used to create the mesh
  64730. * @param scene defines the hosting scene
  64731. * @returns the lathe mesh
  64732. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  64733. */
  64734. MeshBuilder.CreateLathe = function (name, options, scene) {
  64735. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  64736. var closed = (options.closed === undefined) ? true : options.closed;
  64737. var shape = options.shape;
  64738. var radius = options.radius || 1;
  64739. var tessellation = options.tessellation || 64;
  64740. var clip = options.clip || 0;
  64741. var updatable = options.updatable;
  64742. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64743. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64744. var pi2 = Math.PI * 2;
  64745. var paths = new Array();
  64746. var invertUV = options.invertUV || false;
  64747. var i = 0;
  64748. var p = 0;
  64749. var step = pi2 / tessellation * arc;
  64750. var rotated;
  64751. var path = new Array();
  64752. for (i = 0; i <= tessellation - clip; i++) {
  64753. var path = [];
  64754. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  64755. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  64756. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  64757. }
  64758. for (p = 0; p < shape.length; p++) {
  64759. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  64760. path.push(rotated);
  64761. }
  64762. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  64763. 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));
  64764. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  64765. }
  64766. paths.push(path);
  64767. }
  64768. // lathe ribbon
  64769. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64770. return lathe;
  64771. };
  64772. /**
  64773. * Creates a plane mesh
  64774. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  64775. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  64776. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  64777. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64778. * * 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
  64779. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64780. * @param name defines the name of the mesh
  64781. * @param options defines the options used to create the mesh
  64782. * @param scene defines the hosting scene
  64783. * @returns the plane mesh
  64784. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64785. */
  64786. MeshBuilder.CreatePlane = function (name, options, scene) {
  64787. var plane = new BABYLON.Mesh(name, scene);
  64788. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64789. plane._originalBuilderSideOrientation = options.sideOrientation;
  64790. var vertexData = BABYLON.VertexData.CreatePlane(options);
  64791. vertexData.applyToMesh(plane, options.updatable);
  64792. if (options.sourcePlane) {
  64793. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  64794. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  64795. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  64796. plane.rotate(vectorProduct, product);
  64797. }
  64798. return plane;
  64799. };
  64800. /**
  64801. * Creates a ground mesh
  64802. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  64803. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  64804. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64805. * @param name defines the name of the mesh
  64806. * @param options defines the options used to create the mesh
  64807. * @param scene defines the hosting scene
  64808. * @returns the ground mesh
  64809. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64810. */
  64811. MeshBuilder.CreateGround = function (name, options, scene) {
  64812. var ground = new BABYLON.GroundMesh(name, scene);
  64813. ground._setReady(false);
  64814. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  64815. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  64816. ground._width = options.width || 1;
  64817. ground._height = options.height || 1;
  64818. ground._maxX = ground._width / 2;
  64819. ground._maxZ = ground._height / 2;
  64820. ground._minX = -ground._maxX;
  64821. ground._minZ = -ground._maxZ;
  64822. var vertexData = BABYLON.VertexData.CreateGround(options);
  64823. vertexData.applyToMesh(ground, options.updatable);
  64824. ground._setReady(true);
  64825. return ground;
  64826. };
  64827. /**
  64828. * Creates a tiled ground mesh
  64829. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  64830. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  64831. * * 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
  64832. * * 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
  64833. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64834. * @param name defines the name of the mesh
  64835. * @param options defines the options used to create the mesh
  64836. * @param scene defines the hosting scene
  64837. * @returns the tiled ground mesh
  64838. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  64839. */
  64840. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  64841. var tiledGround = new BABYLON.Mesh(name, scene);
  64842. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  64843. vertexData.applyToMesh(tiledGround, options.updatable);
  64844. return tiledGround;
  64845. };
  64846. /**
  64847. * Creates a ground mesh from a height map
  64848. * * The parameter `url` sets the URL of the height map image resource.
  64849. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  64850. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  64851. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  64852. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  64853. * * 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.
  64854. * * 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).
  64855. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64856. * @param name defines the name of the mesh
  64857. * @param url defines the url to the height map
  64858. * @param options defines the options used to create the mesh
  64859. * @param scene defines the hosting scene
  64860. * @returns the ground mesh
  64861. * @see http://doc.babylonjs.com/babylon101/height_map
  64862. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  64863. */
  64864. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  64865. var width = options.width || 10.0;
  64866. var height = options.height || 10.0;
  64867. var subdivisions = options.subdivisions || 1 | 0;
  64868. var minHeight = options.minHeight || 0.0;
  64869. var maxHeight = options.maxHeight || 1.0;
  64870. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  64871. var updatable = options.updatable;
  64872. var onReady = options.onReady;
  64873. var ground = new BABYLON.GroundMesh(name, scene);
  64874. ground._subdivisionsX = subdivisions;
  64875. ground._subdivisionsY = subdivisions;
  64876. ground._width = width;
  64877. ground._height = height;
  64878. ground._maxX = ground._width / 2.0;
  64879. ground._maxZ = ground._height / 2.0;
  64880. ground._minX = -ground._maxX;
  64881. ground._minZ = -ground._maxZ;
  64882. ground._setReady(false);
  64883. var onload = function (img) {
  64884. // Getting height map data
  64885. var canvas = document.createElement("canvas");
  64886. var context = canvas.getContext("2d");
  64887. if (!context) {
  64888. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  64889. }
  64890. if (scene.isDisposed) {
  64891. return;
  64892. }
  64893. var bufferWidth = img.width;
  64894. var bufferHeight = img.height;
  64895. canvas.width = bufferWidth;
  64896. canvas.height = bufferHeight;
  64897. context.drawImage(img, 0, 0);
  64898. // Create VertexData from map data
  64899. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  64900. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  64901. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  64902. width: width, height: height,
  64903. subdivisions: subdivisions,
  64904. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  64905. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  64906. });
  64907. vertexData.applyToMesh(ground, updatable);
  64908. //execute ready callback, if set
  64909. if (onReady) {
  64910. onReady(ground);
  64911. }
  64912. ground._setReady(true);
  64913. };
  64914. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  64915. return ground;
  64916. };
  64917. /**
  64918. * Creates a polygon mesh
  64919. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  64920. * * 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
  64921. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64922. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64923. * * 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)
  64924. * * Remember you can only change the shape positions, not their number when updating a polygon
  64925. * @param name defines the name of the mesh
  64926. * @param options defines the options used to create the mesh
  64927. * @param scene defines the hosting scene
  64928. * @returns the polygon mesh
  64929. */
  64930. MeshBuilder.CreatePolygon = function (name, options, scene) {
  64931. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64932. var shape = options.shape;
  64933. var holes = options.holes || [];
  64934. var depth = options.depth || 0;
  64935. var contours = [];
  64936. var hole = [];
  64937. for (var i = 0; i < shape.length; i++) {
  64938. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  64939. }
  64940. var epsilon = 0.00000001;
  64941. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  64942. contours.pop();
  64943. }
  64944. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  64945. for (var hNb = 0; hNb < holes.length; hNb++) {
  64946. hole = [];
  64947. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  64948. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  64949. }
  64950. polygonTriangulation.addHole(hole);
  64951. }
  64952. var polygon = polygonTriangulation.build(options.updatable, depth);
  64953. polygon._originalBuilderSideOrientation = options.sideOrientation;
  64954. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  64955. vertexData.applyToMesh(polygon, options.updatable);
  64956. return polygon;
  64957. };
  64958. ;
  64959. /**
  64960. * Creates an extruded polygon mesh, with depth in the Y direction.
  64961. * * 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)
  64962. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64963. * @param name defines the name of the mesh
  64964. * @param options defines the options used to create the mesh
  64965. * @param scene defines the hosting scene
  64966. * @returns the polygon mesh
  64967. */
  64968. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  64969. return MeshBuilder.CreatePolygon(name, options, scene);
  64970. };
  64971. ;
  64972. /**
  64973. * Creates a tube mesh.
  64974. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64975. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  64976. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  64977. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  64978. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  64979. * * 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)
  64980. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  64981. * * 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
  64982. * * 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
  64983. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64984. * * 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
  64985. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64986. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64987. * @param name defines the name of the mesh
  64988. * @param options defines the options used to create the mesh
  64989. * @param scene defines the hosting scene
  64990. * @returns the tube mesh
  64991. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64992. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  64993. */
  64994. MeshBuilder.CreateTube = function (name, options, scene) {
  64995. var path = options.path;
  64996. var instance = options.instance;
  64997. var radius = 1.0;
  64998. if (instance) {
  64999. radius = instance.radius;
  65000. }
  65001. if (options.radius !== undefined) {
  65002. radius = options.radius;
  65003. }
  65004. ;
  65005. var tessellation = options.tessellation || 64 | 0;
  65006. var radiusFunction = options.radiusFunction || null;
  65007. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  65008. var invertUV = options.invertUV || false;
  65009. var updatable = options.updatable;
  65010. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65011. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  65012. // tube geometry
  65013. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  65014. var tangents = path3D.getTangents();
  65015. var normals = path3D.getNormals();
  65016. var distances = path3D.getDistances();
  65017. var pi2 = Math.PI * 2;
  65018. var step = pi2 / tessellation * arc;
  65019. var returnRadius = function () { return radius; };
  65020. var radiusFunctionFinal = radiusFunction || returnRadius;
  65021. var circlePath;
  65022. var rad;
  65023. var normal;
  65024. var rotated;
  65025. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  65026. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  65027. for (var i = 0; i < path.length; i++) {
  65028. rad = radiusFunctionFinal(i, distances[i]); // current radius
  65029. circlePath = Array(); // current circle array
  65030. normal = normals[i]; // current normal
  65031. for (var t = 0; t < tessellation; t++) {
  65032. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  65033. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  65034. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  65035. rotated.scaleInPlace(rad).addInPlace(path[i]);
  65036. circlePath[t] = rotated;
  65037. }
  65038. circlePaths[index] = circlePath;
  65039. index++;
  65040. }
  65041. // cap
  65042. var capPath = function (nbPoints, pathIndex) {
  65043. var pointCap = Array();
  65044. for (var i = 0; i < nbPoints; i++) {
  65045. pointCap.push(path[pathIndex]);
  65046. }
  65047. return pointCap;
  65048. };
  65049. switch (cap) {
  65050. case BABYLON.Mesh.NO_CAP:
  65051. break;
  65052. case BABYLON.Mesh.CAP_START:
  65053. circlePaths[0] = capPath(tessellation, 0);
  65054. circlePaths[1] = circlePaths[2].slice(0);
  65055. break;
  65056. case BABYLON.Mesh.CAP_END:
  65057. circlePaths[index] = circlePaths[index - 1].slice(0);
  65058. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  65059. break;
  65060. case BABYLON.Mesh.CAP_ALL:
  65061. circlePaths[0] = capPath(tessellation, 0);
  65062. circlePaths[1] = circlePaths[2].slice(0);
  65063. circlePaths[index] = circlePaths[index - 1].slice(0);
  65064. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  65065. break;
  65066. default:
  65067. break;
  65068. }
  65069. return circlePaths;
  65070. };
  65071. var path3D;
  65072. var pathArray;
  65073. if (instance) { // tube update
  65074. var arc = options.arc || instance.arc;
  65075. path3D = (instance.path3D).update(path);
  65076. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  65077. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  65078. instance.path3D = path3D;
  65079. instance.pathArray = pathArray;
  65080. instance.arc = arc;
  65081. instance.radius = radius;
  65082. return instance;
  65083. }
  65084. // tube creation
  65085. path3D = new BABYLON.Path3D(path);
  65086. var newPathArray = new Array();
  65087. cap = (cap < 0 || cap > 3) ? 0 : cap;
  65088. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  65089. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  65090. tube.pathArray = pathArray;
  65091. tube.path3D = path3D;
  65092. tube.tessellation = tessellation;
  65093. tube.cap = cap;
  65094. tube.arc = options.arc;
  65095. tube.radius = radius;
  65096. return tube;
  65097. };
  65098. /**
  65099. * Creates a polyhedron mesh
  65100. * * 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
  65101. * * The parameter `size` (positive float, default 1) sets the polygon size
  65102. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  65103. * * 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`
  65104. * * 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
  65105. * * 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)`)
  65106. * * 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
  65107. * * 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
  65108. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65109. * * 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
  65110. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65111. * @param name defines the name of the mesh
  65112. * @param options defines the options used to create the mesh
  65113. * @param scene defines the hosting scene
  65114. * @returns the polyhedron mesh
  65115. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  65116. */
  65117. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  65118. var polyhedron = new BABYLON.Mesh(name, scene);
  65119. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65120. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  65121. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  65122. vertexData.applyToMesh(polyhedron, options.updatable);
  65123. return polyhedron;
  65124. };
  65125. /**
  65126. * Creates a decal mesh.
  65127. * 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
  65128. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  65129. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  65130. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  65131. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  65132. * @param name defines the name of the mesh
  65133. * @param sourceMesh defines the mesh where the decal must be applied
  65134. * @param options defines the options used to create the mesh
  65135. * @param scene defines the hosting scene
  65136. * @returns the decal mesh
  65137. * @see http://doc.babylonjs.com/how_to/decals
  65138. */
  65139. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  65140. var indices = sourceMesh.getIndices();
  65141. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65142. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65143. var position = options.position || BABYLON.Vector3.Zero();
  65144. var normal = options.normal || BABYLON.Vector3.Up();
  65145. var size = options.size || BABYLON.Vector3.One();
  65146. var angle = options.angle || 0;
  65147. // Getting correct rotation
  65148. if (!normal) {
  65149. var target = new BABYLON.Vector3(0, 0, 1);
  65150. var camera = sourceMesh.getScene().activeCamera;
  65151. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  65152. normal = camera.globalPosition.subtract(cameraWorldTarget);
  65153. }
  65154. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  65155. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  65156. var pitch = Math.atan2(normal.y, len);
  65157. // Matrix
  65158. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  65159. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  65160. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  65161. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  65162. var vertexData = new BABYLON.VertexData();
  65163. vertexData.indices = [];
  65164. vertexData.positions = [];
  65165. vertexData.normals = [];
  65166. vertexData.uvs = [];
  65167. var currentVertexDataIndex = 0;
  65168. var extractDecalVector3 = function (indexId) {
  65169. var result = new BABYLON.PositionNormalVertex();
  65170. if (!indices || !positions || !normals) {
  65171. return result;
  65172. }
  65173. var vertexId = indices[indexId];
  65174. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  65175. // Send vector to decal local world
  65176. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  65177. // Get normal
  65178. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  65179. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  65180. return result;
  65181. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  65182. var clip = function (vertices, axis) {
  65183. if (vertices.length === 0) {
  65184. return vertices;
  65185. }
  65186. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  65187. var clipVertices = function (v0, v1) {
  65188. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  65189. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  65190. };
  65191. var result = new Array();
  65192. for (var index = 0; index < vertices.length; index += 3) {
  65193. var v1Out;
  65194. var v2Out;
  65195. var v3Out;
  65196. var total = 0;
  65197. var nV1 = null;
  65198. var nV2 = null;
  65199. var nV3 = null;
  65200. var nV4 = null;
  65201. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  65202. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  65203. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  65204. v1Out = d1 > 0;
  65205. v2Out = d2 > 0;
  65206. v3Out = d3 > 0;
  65207. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  65208. switch (total) {
  65209. case 0:
  65210. result.push(vertices[index]);
  65211. result.push(vertices[index + 1]);
  65212. result.push(vertices[index + 2]);
  65213. break;
  65214. case 1:
  65215. if (v1Out) {
  65216. nV1 = vertices[index + 1];
  65217. nV2 = vertices[index + 2];
  65218. nV3 = clipVertices(vertices[index], nV1);
  65219. nV4 = clipVertices(vertices[index], nV2);
  65220. }
  65221. if (v2Out) {
  65222. nV1 = vertices[index];
  65223. nV2 = vertices[index + 2];
  65224. nV3 = clipVertices(vertices[index + 1], nV1);
  65225. nV4 = clipVertices(vertices[index + 1], nV2);
  65226. result.push(nV3);
  65227. result.push(nV2.clone());
  65228. result.push(nV1.clone());
  65229. result.push(nV2.clone());
  65230. result.push(nV3.clone());
  65231. result.push(nV4);
  65232. break;
  65233. }
  65234. if (v3Out) {
  65235. nV1 = vertices[index];
  65236. nV2 = vertices[index + 1];
  65237. nV3 = clipVertices(vertices[index + 2], nV1);
  65238. nV4 = clipVertices(vertices[index + 2], nV2);
  65239. }
  65240. if (nV1 && nV2 && nV3 && nV4) {
  65241. result.push(nV1.clone());
  65242. result.push(nV2.clone());
  65243. result.push(nV3);
  65244. result.push(nV4);
  65245. result.push(nV3.clone());
  65246. result.push(nV2.clone());
  65247. }
  65248. break;
  65249. case 2:
  65250. if (!v1Out) {
  65251. nV1 = vertices[index].clone();
  65252. nV2 = clipVertices(nV1, vertices[index + 1]);
  65253. nV3 = clipVertices(nV1, vertices[index + 2]);
  65254. result.push(nV1);
  65255. result.push(nV2);
  65256. result.push(nV3);
  65257. }
  65258. if (!v2Out) {
  65259. nV1 = vertices[index + 1].clone();
  65260. nV2 = clipVertices(nV1, vertices[index + 2]);
  65261. nV3 = clipVertices(nV1, vertices[index]);
  65262. result.push(nV1);
  65263. result.push(nV2);
  65264. result.push(nV3);
  65265. }
  65266. if (!v3Out) {
  65267. nV1 = vertices[index + 2].clone();
  65268. nV2 = clipVertices(nV1, vertices[index]);
  65269. nV3 = clipVertices(nV1, vertices[index + 1]);
  65270. result.push(nV1);
  65271. result.push(nV2);
  65272. result.push(nV3);
  65273. }
  65274. break;
  65275. case 3:
  65276. break;
  65277. }
  65278. }
  65279. return result;
  65280. };
  65281. for (var index = 0; index < indices.length; index += 3) {
  65282. var faceVertices = new Array();
  65283. faceVertices.push(extractDecalVector3(index));
  65284. faceVertices.push(extractDecalVector3(index + 1));
  65285. faceVertices.push(extractDecalVector3(index + 2));
  65286. // Clip
  65287. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  65288. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  65289. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  65290. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  65291. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  65292. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  65293. if (faceVertices.length === 0) {
  65294. continue;
  65295. }
  65296. // Add UVs and get back to world
  65297. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  65298. var vertex = faceVertices[vIndex];
  65299. //TODO check for Int32Array | Uint32Array | Uint16Array
  65300. vertexData.indices.push(currentVertexDataIndex);
  65301. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  65302. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  65303. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  65304. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  65305. currentVertexDataIndex++;
  65306. }
  65307. }
  65308. // Return mesh
  65309. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  65310. vertexData.applyToMesh(decal);
  65311. decal.position = position.clone();
  65312. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  65313. return decal;
  65314. };
  65315. // Privates
  65316. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  65317. // extrusion geometry
  65318. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  65319. var tangents = path3D.getTangents();
  65320. var normals = path3D.getNormals();
  65321. var binormals = path3D.getBinormals();
  65322. var distances = path3D.getDistances();
  65323. var angle = 0;
  65324. var returnScale = function () { return scale !== null ? scale : 1; };
  65325. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  65326. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  65327. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  65328. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  65329. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  65330. for (var i = 0; i < curve.length; i++) {
  65331. var shapePath = new Array();
  65332. var angleStep = rotate(i, distances[i]);
  65333. var scaleRatio = scl(i, distances[i]);
  65334. for (var p = 0; p < shape.length; p++) {
  65335. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  65336. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  65337. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  65338. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  65339. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  65340. shapePath[p] = rotated;
  65341. }
  65342. shapePaths[index] = shapePath;
  65343. angle += angleStep;
  65344. index++;
  65345. }
  65346. // cap
  65347. var capPath = function (shapePath) {
  65348. var pointCap = Array();
  65349. var barycenter = BABYLON.Vector3.Zero();
  65350. var i;
  65351. for (i = 0; i < shapePath.length; i++) {
  65352. barycenter.addInPlace(shapePath[i]);
  65353. }
  65354. barycenter.scaleInPlace(1.0 / shapePath.length);
  65355. for (i = 0; i < shapePath.length; i++) {
  65356. pointCap.push(barycenter);
  65357. }
  65358. return pointCap;
  65359. };
  65360. switch (cap) {
  65361. case BABYLON.Mesh.NO_CAP:
  65362. break;
  65363. case BABYLON.Mesh.CAP_START:
  65364. shapePaths[0] = capPath(shapePaths[2]);
  65365. shapePaths[1] = shapePaths[2];
  65366. break;
  65367. case BABYLON.Mesh.CAP_END:
  65368. shapePaths[index] = shapePaths[index - 1];
  65369. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65370. break;
  65371. case BABYLON.Mesh.CAP_ALL:
  65372. shapePaths[0] = capPath(shapePaths[2]);
  65373. shapePaths[1] = shapePaths[2];
  65374. shapePaths[index] = shapePaths[index - 1];
  65375. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65376. break;
  65377. default:
  65378. break;
  65379. }
  65380. return shapePaths;
  65381. };
  65382. var path3D;
  65383. var pathArray;
  65384. if (instance) { // instance update
  65385. path3D = (instance.path3D).update(curve);
  65386. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  65387. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  65388. return instance;
  65389. }
  65390. // extruded shape creation
  65391. path3D = new BABYLON.Path3D(curve);
  65392. var newShapePaths = new Array();
  65393. cap = (cap < 0 || cap > 3) ? 0 : cap;
  65394. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  65395. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  65396. extrudedGeneric.pathArray = pathArray;
  65397. extrudedGeneric.path3D = path3D;
  65398. extrudedGeneric.cap = cap;
  65399. return extrudedGeneric;
  65400. };
  65401. return MeshBuilder;
  65402. }());
  65403. BABYLON.MeshBuilder = MeshBuilder;
  65404. })(BABYLON || (BABYLON = {}));
  65405. //# sourceMappingURL=babylon.meshBuilder.js.map
  65406. var BABYLON;
  65407. (function (BABYLON) {
  65408. /**
  65409. * Draco compression (https://google.github.io/draco/)
  65410. *
  65411. * This class wraps the Draco module.
  65412. *
  65413. * **Encoder**
  65414. *
  65415. * The encoder is not currently implemented.
  65416. *
  65417. * **Decoder**
  65418. *
  65419. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  65420. *
  65421. * To update the configuration, use the following code:
  65422. * ```javascript
  65423. * BABYLON.DracoCompression.Configuration = {
  65424. * decoder: {
  65425. * wasmUrl: "<url to the WebAssembly library>",
  65426. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  65427. * fallbackUrl: "<url to the fallback JavaScript library>",
  65428. * }
  65429. * };
  65430. * ```
  65431. *
  65432. * 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.
  65433. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  65434. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  65435. *
  65436. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  65437. * ```javascript
  65438. * var dracoCompression = new BABYLON.DracoCompression();
  65439. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  65440. * [BABYLON.VertexBuffer.PositionKind]: 0
  65441. * });
  65442. * ```
  65443. *
  65444. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  65445. */
  65446. var DracoCompression = /** @class */ (function () {
  65447. /**
  65448. * Constructor
  65449. */
  65450. function DracoCompression() {
  65451. }
  65452. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  65453. /**
  65454. * Returns true if the decoder is available.
  65455. */
  65456. get: function () {
  65457. if (typeof DracoDecoderModule !== "undefined") {
  65458. return true;
  65459. }
  65460. var decoder = DracoCompression.Configuration.decoder;
  65461. if (decoder) {
  65462. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65463. return true;
  65464. }
  65465. if (decoder.fallbackUrl) {
  65466. return true;
  65467. }
  65468. }
  65469. return false;
  65470. },
  65471. enumerable: true,
  65472. configurable: true
  65473. });
  65474. /**
  65475. * Stop all async operations and release resources.
  65476. */
  65477. DracoCompression.prototype.dispose = function () {
  65478. };
  65479. /**
  65480. * Decode Draco compressed mesh data to vertex data.
  65481. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  65482. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  65483. * @returns A promise that resolves with the decoded vertex data
  65484. */
  65485. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  65486. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  65487. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  65488. var module = wrappedModule.module;
  65489. var vertexData = new BABYLON.VertexData();
  65490. var buffer = new module.DecoderBuffer();
  65491. buffer.Init(dataView, dataView.byteLength);
  65492. var decoder = new module.Decoder();
  65493. var geometry;
  65494. var status;
  65495. try {
  65496. var type = decoder.GetEncodedGeometryType(buffer);
  65497. switch (type) {
  65498. case module.TRIANGULAR_MESH:
  65499. geometry = new module.Mesh();
  65500. status = decoder.DecodeBufferToMesh(buffer, geometry);
  65501. break;
  65502. case module.POINT_CLOUD:
  65503. geometry = new module.PointCloud();
  65504. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  65505. break;
  65506. default:
  65507. throw new Error("Invalid geometry type " + type);
  65508. }
  65509. if (!status.ok() || !geometry.ptr) {
  65510. throw new Error(status.error_msg());
  65511. }
  65512. var numPoints = geometry.num_points();
  65513. if (type === module.TRIANGULAR_MESH) {
  65514. var numFaces = geometry.num_faces();
  65515. var faceIndices = new module.DracoInt32Array();
  65516. try {
  65517. var indices = new Uint32Array(numFaces * 3);
  65518. for (var i = 0; i < numFaces; i++) {
  65519. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  65520. var offset = i * 3;
  65521. indices[offset + 0] = faceIndices.GetValue(0);
  65522. indices[offset + 1] = faceIndices.GetValue(1);
  65523. indices[offset + 2] = faceIndices.GetValue(2);
  65524. }
  65525. vertexData.indices = indices;
  65526. }
  65527. finally {
  65528. module.destroy(faceIndices);
  65529. }
  65530. }
  65531. for (var kind in attributes) {
  65532. var uniqueId = attributes[kind];
  65533. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  65534. var dracoData = new module.DracoFloat32Array();
  65535. try {
  65536. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  65537. var babylonData = new Float32Array(numPoints * attribute.num_components());
  65538. for (var i = 0; i < babylonData.length; i++) {
  65539. babylonData[i] = dracoData.GetValue(i);
  65540. }
  65541. vertexData.set(babylonData, kind);
  65542. }
  65543. finally {
  65544. module.destroy(dracoData);
  65545. }
  65546. }
  65547. }
  65548. finally {
  65549. if (geometry) {
  65550. module.destroy(geometry);
  65551. }
  65552. module.destroy(decoder);
  65553. module.destroy(buffer);
  65554. }
  65555. return vertexData;
  65556. });
  65557. };
  65558. DracoCompression._GetDecoderModule = function () {
  65559. if (!DracoCompression._DecoderModulePromise) {
  65560. var promise = null;
  65561. var config_1 = {};
  65562. if (typeof DracoDecoderModule !== "undefined") {
  65563. promise = Promise.resolve();
  65564. }
  65565. else {
  65566. var decoder = DracoCompression.Configuration.decoder;
  65567. if (decoder) {
  65568. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65569. promise = Promise.all([
  65570. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  65571. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  65572. config_1.wasmBinary = data;
  65573. })
  65574. ]);
  65575. }
  65576. else if (decoder.fallbackUrl) {
  65577. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  65578. }
  65579. }
  65580. }
  65581. if (!promise) {
  65582. throw new Error("Draco decoder module is not available");
  65583. }
  65584. DracoCompression._DecoderModulePromise = promise.then(function () {
  65585. return new Promise(function (resolve) {
  65586. config_1.onModuleLoaded = function (decoderModule) {
  65587. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  65588. resolve({ module: decoderModule });
  65589. };
  65590. DracoDecoderModule(config_1);
  65591. });
  65592. });
  65593. }
  65594. return DracoCompression._DecoderModulePromise;
  65595. };
  65596. DracoCompression._LoadScriptAsync = function (url) {
  65597. return new Promise(function (resolve, reject) {
  65598. BABYLON.Tools.LoadScript(url, function () {
  65599. resolve();
  65600. }, function (message) {
  65601. reject(new Error(message));
  65602. });
  65603. });
  65604. };
  65605. DracoCompression._LoadFileAsync = function (url) {
  65606. return new Promise(function (resolve, reject) {
  65607. BABYLON.Tools.LoadFile(url, function (data) {
  65608. resolve(data);
  65609. }, undefined, undefined, true, function (request, exception) {
  65610. reject(exception);
  65611. });
  65612. });
  65613. };
  65614. /**
  65615. * The configuration. Defaults to the following urls:
  65616. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  65617. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  65618. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65619. */
  65620. DracoCompression.Configuration = {
  65621. decoder: {
  65622. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  65623. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  65624. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65625. }
  65626. };
  65627. return DracoCompression;
  65628. }());
  65629. BABYLON.DracoCompression = DracoCompression;
  65630. })(BABYLON || (BABYLON = {}));
  65631. //# sourceMappingURL=babylon.dracoCompression.js.map
  65632. var BABYLON;
  65633. (function (BABYLON) {
  65634. var AudioEngine = /** @class */ (function () {
  65635. function AudioEngine() {
  65636. this._audioContext = null;
  65637. this._audioContextInitialized = false;
  65638. this.canUseWebAudio = false;
  65639. this.WarnedWebAudioUnsupported = false;
  65640. this.unlocked = false;
  65641. this.isMP3supported = false;
  65642. this.isOGGsupported = false;
  65643. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  65644. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  65645. this.canUseWebAudio = true;
  65646. }
  65647. var audioElem = document.createElement('audio');
  65648. try {
  65649. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  65650. this.isMP3supported = true;
  65651. }
  65652. }
  65653. catch (e) {
  65654. // protect error during capability check.
  65655. }
  65656. try {
  65657. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  65658. this.isOGGsupported = true;
  65659. }
  65660. }
  65661. catch (e) {
  65662. // protect error during capability check.
  65663. }
  65664. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  65665. this._unlockiOSaudio();
  65666. }
  65667. else {
  65668. this.unlocked = true;
  65669. }
  65670. }
  65671. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  65672. get: function () {
  65673. if (!this._audioContextInitialized) {
  65674. this._initializeAudioContext();
  65675. }
  65676. return this._audioContext;
  65677. },
  65678. enumerable: true,
  65679. configurable: true
  65680. });
  65681. AudioEngine.prototype._unlockiOSaudio = function () {
  65682. var _this = this;
  65683. var unlockaudio = function () {
  65684. if (!_this.audioContext) {
  65685. return;
  65686. }
  65687. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  65688. var source = _this.audioContext.createBufferSource();
  65689. source.buffer = buffer;
  65690. source.connect(_this.audioContext.destination);
  65691. source.start(0);
  65692. setTimeout(function () {
  65693. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  65694. _this.unlocked = true;
  65695. window.removeEventListener('touchend', unlockaudio, false);
  65696. if (_this.onAudioUnlocked) {
  65697. _this.onAudioUnlocked();
  65698. }
  65699. }
  65700. }, 0);
  65701. };
  65702. window.addEventListener('touchend', unlockaudio, false);
  65703. };
  65704. AudioEngine.prototype._initializeAudioContext = function () {
  65705. try {
  65706. if (this.canUseWebAudio) {
  65707. this._audioContext = new AudioContext();
  65708. // create a global volume gain node
  65709. this.masterGain = this._audioContext.createGain();
  65710. this.masterGain.gain.value = 1;
  65711. this.masterGain.connect(this._audioContext.destination);
  65712. this._audioContextInitialized = true;
  65713. }
  65714. }
  65715. catch (e) {
  65716. this.canUseWebAudio = false;
  65717. BABYLON.Tools.Error("Web Audio: " + e.message);
  65718. }
  65719. };
  65720. AudioEngine.prototype.dispose = function () {
  65721. if (this.canUseWebAudio && this._audioContextInitialized) {
  65722. if (this._connectedAnalyser && this._audioContext) {
  65723. this._connectedAnalyser.stopDebugCanvas();
  65724. this._connectedAnalyser.dispose();
  65725. this.masterGain.disconnect();
  65726. this.masterGain.connect(this._audioContext.destination);
  65727. this._connectedAnalyser = null;
  65728. }
  65729. this.masterGain.gain.value = 1;
  65730. }
  65731. this.WarnedWebAudioUnsupported = false;
  65732. };
  65733. AudioEngine.prototype.getGlobalVolume = function () {
  65734. if (this.canUseWebAudio && this._audioContextInitialized) {
  65735. return this.masterGain.gain.value;
  65736. }
  65737. else {
  65738. return -1;
  65739. }
  65740. };
  65741. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  65742. if (this.canUseWebAudio && this._audioContextInitialized) {
  65743. this.masterGain.gain.value = newVolume;
  65744. }
  65745. };
  65746. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  65747. if (this._connectedAnalyser) {
  65748. this._connectedAnalyser.stopDebugCanvas();
  65749. }
  65750. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  65751. this._connectedAnalyser = analyser;
  65752. this.masterGain.disconnect();
  65753. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  65754. }
  65755. };
  65756. return AudioEngine;
  65757. }());
  65758. BABYLON.AudioEngine = AudioEngine;
  65759. })(BABYLON || (BABYLON = {}));
  65760. //# sourceMappingURL=babylon.audioEngine.js.map
  65761. var BABYLON;
  65762. (function (BABYLON) {
  65763. var Sound = /** @class */ (function () {
  65764. /**
  65765. * Create a sound and attach it to a scene
  65766. * @param name Name of your sound
  65767. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  65768. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  65769. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  65770. */
  65771. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  65772. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  65773. var _this = this;
  65774. this.autoplay = false;
  65775. this.loop = false;
  65776. this.useCustomAttenuation = false;
  65777. this.spatialSound = false;
  65778. this.refDistance = 1;
  65779. this.rolloffFactor = 1;
  65780. this.maxDistance = 100;
  65781. this.distanceModel = "linear";
  65782. this._panningModel = "equalpower";
  65783. /**
  65784. * Observable event when the current playing sound finishes.
  65785. */
  65786. this.onEndedObservable = new BABYLON.Observable();
  65787. this._playbackRate = 1;
  65788. this._streaming = false;
  65789. this._startTime = 0;
  65790. this._startOffset = 0;
  65791. this._position = BABYLON.Vector3.Zero();
  65792. /** @hidden */
  65793. this._positionInEmitterSpace = false;
  65794. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  65795. this._volume = 1;
  65796. this._isReadyToPlay = false;
  65797. this.isPlaying = false;
  65798. this.isPaused = false;
  65799. this._isDirectional = false;
  65800. // Used if you'd like to create a directional sound.
  65801. // If not set, the sound will be omnidirectional
  65802. this._coneInnerAngle = 360;
  65803. this._coneOuterAngle = 360;
  65804. this._coneOuterGain = 0;
  65805. this._isOutputConnected = false;
  65806. this._urlType = "Unknown";
  65807. this.name = name;
  65808. this._scene = scene;
  65809. this._readyToPlayCallback = readyToPlayCallback;
  65810. // Default custom attenuation function is a linear attenuation
  65811. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  65812. if (currentDistance < maxDistance) {
  65813. return currentVolume * (1 - currentDistance / maxDistance);
  65814. }
  65815. else {
  65816. return 0;
  65817. }
  65818. };
  65819. if (options) {
  65820. this.autoplay = options.autoplay || false;
  65821. this.loop = options.loop || false;
  65822. // if volume === 0, we need another way to check this option
  65823. if (options.volume !== undefined) {
  65824. this._volume = options.volume;
  65825. }
  65826. this.spatialSound = options.spatialSound || false;
  65827. this.maxDistance = options.maxDistance || 100;
  65828. this.useCustomAttenuation = options.useCustomAttenuation || false;
  65829. this.rolloffFactor = options.rolloffFactor || 1;
  65830. this.refDistance = options.refDistance || 1;
  65831. this.distanceModel = options.distanceModel || "linear";
  65832. this._playbackRate = options.playbackRate || 1;
  65833. this._streaming = options.streaming || false;
  65834. }
  65835. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65836. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  65837. this._soundGain.gain.value = this._volume;
  65838. this._inputAudioNode = this._soundGain;
  65839. this._outputAudioNode = this._soundGain;
  65840. if (this.spatialSound) {
  65841. this._createSpatialParameters();
  65842. }
  65843. this._scene.mainSoundTrack.AddSound(this);
  65844. var validParameter = true;
  65845. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  65846. if (urlOrArrayBuffer) {
  65847. try {
  65848. if (typeof (urlOrArrayBuffer) === "string") {
  65849. this._urlType = "String";
  65850. }
  65851. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  65852. this._urlType = "ArrayBuffer";
  65853. }
  65854. else if (urlOrArrayBuffer instanceof MediaStream) {
  65855. this._urlType = "MediaStream";
  65856. }
  65857. else if (Array.isArray(urlOrArrayBuffer)) {
  65858. this._urlType = "Array";
  65859. }
  65860. var urls = [];
  65861. var codecSupportedFound = false;
  65862. switch (this._urlType) {
  65863. case "MediaStream":
  65864. this._streaming = true;
  65865. this._isReadyToPlay = true;
  65866. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  65867. if (this.autoplay) {
  65868. this.play();
  65869. }
  65870. if (this._readyToPlayCallback) {
  65871. this._readyToPlayCallback();
  65872. }
  65873. break;
  65874. case "ArrayBuffer":
  65875. if (urlOrArrayBuffer.byteLength > 0) {
  65876. codecSupportedFound = true;
  65877. this._soundLoaded(urlOrArrayBuffer);
  65878. }
  65879. break;
  65880. case "String":
  65881. urls.push(urlOrArrayBuffer);
  65882. case "Array":
  65883. if (urls.length === 0)
  65884. urls = urlOrArrayBuffer;
  65885. // If we found a supported format, we load it immediately and stop the loop
  65886. for (var i = 0; i < urls.length; i++) {
  65887. var url = urls[i];
  65888. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  65889. codecSupportedFound = true;
  65890. }
  65891. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  65892. codecSupportedFound = true;
  65893. }
  65894. if (url.indexOf(".wav", url.length - 4) !== -1) {
  65895. codecSupportedFound = true;
  65896. }
  65897. if (url.indexOf("blob:") !== -1) {
  65898. codecSupportedFound = true;
  65899. }
  65900. if (codecSupportedFound) {
  65901. // Loading sound using XHR2
  65902. if (!this._streaming) {
  65903. this._scene._loadFile(url, function (data) {
  65904. _this._soundLoaded(data);
  65905. }, undefined, true, true, function (exception) {
  65906. if (exception) {
  65907. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  65908. }
  65909. BABYLON.Tools.Error("Sound creation aborted.");
  65910. _this._scene.mainSoundTrack.RemoveSound(_this);
  65911. });
  65912. }
  65913. // Streaming sound using HTML5 Audio tag
  65914. else {
  65915. this._htmlAudioElement = new Audio(url);
  65916. this._htmlAudioElement.controls = false;
  65917. this._htmlAudioElement.loop = this.loop;
  65918. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  65919. this._htmlAudioElement.preload = "auto";
  65920. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  65921. _this._isReadyToPlay = true;
  65922. if (_this.autoplay) {
  65923. _this.play();
  65924. }
  65925. if (_this._readyToPlayCallback) {
  65926. _this._readyToPlayCallback();
  65927. }
  65928. });
  65929. document.body.appendChild(this._htmlAudioElement);
  65930. }
  65931. break;
  65932. }
  65933. }
  65934. break;
  65935. default:
  65936. validParameter = false;
  65937. break;
  65938. }
  65939. if (!validParameter) {
  65940. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  65941. }
  65942. else {
  65943. if (!codecSupportedFound) {
  65944. this._isReadyToPlay = true;
  65945. // Simulating a ready to play event to avoid breaking code path
  65946. if (this._readyToPlayCallback) {
  65947. window.setTimeout(function () {
  65948. if (_this._readyToPlayCallback) {
  65949. _this._readyToPlayCallback();
  65950. }
  65951. }, 1000);
  65952. }
  65953. }
  65954. }
  65955. }
  65956. catch (ex) {
  65957. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  65958. this._scene.mainSoundTrack.RemoveSound(this);
  65959. }
  65960. }
  65961. }
  65962. else {
  65963. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  65964. this._scene.mainSoundTrack.AddSound(this);
  65965. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  65966. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  65967. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  65968. }
  65969. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  65970. if (this._readyToPlayCallback) {
  65971. window.setTimeout(function () {
  65972. if (_this._readyToPlayCallback) {
  65973. _this._readyToPlayCallback();
  65974. }
  65975. }, 1000);
  65976. }
  65977. }
  65978. }
  65979. Sound.prototype.dispose = function () {
  65980. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65981. if (this.isPlaying) {
  65982. this.stop();
  65983. }
  65984. this._isReadyToPlay = false;
  65985. if (this.soundTrackId === -1) {
  65986. this._scene.mainSoundTrack.RemoveSound(this);
  65987. }
  65988. else {
  65989. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  65990. }
  65991. if (this._soundGain) {
  65992. this._soundGain.disconnect();
  65993. this._soundGain = null;
  65994. }
  65995. if (this._soundPanner) {
  65996. this._soundPanner.disconnect();
  65997. this._soundPanner = null;
  65998. }
  65999. if (this._soundSource) {
  66000. this._soundSource.disconnect();
  66001. this._soundSource = null;
  66002. }
  66003. this._audioBuffer = null;
  66004. if (this._htmlAudioElement) {
  66005. this._htmlAudioElement.pause();
  66006. this._htmlAudioElement.src = "";
  66007. document.body.removeChild(this._htmlAudioElement);
  66008. }
  66009. if (this._streamingSource) {
  66010. this._streamingSource.disconnect();
  66011. }
  66012. if (this._connectedMesh && this._registerFunc) {
  66013. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66014. this._connectedMesh = null;
  66015. }
  66016. }
  66017. };
  66018. Sound.prototype.isReady = function () {
  66019. return this._isReadyToPlay;
  66020. };
  66021. Sound.prototype._soundLoaded = function (audioData) {
  66022. var _this = this;
  66023. if (!BABYLON.Engine.audioEngine.audioContext) {
  66024. return;
  66025. }
  66026. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  66027. _this._audioBuffer = buffer;
  66028. _this._isReadyToPlay = true;
  66029. if (_this.autoplay) {
  66030. _this.play();
  66031. }
  66032. if (_this._readyToPlayCallback) {
  66033. _this._readyToPlayCallback();
  66034. }
  66035. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  66036. };
  66037. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  66038. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66039. this._audioBuffer = audioBuffer;
  66040. this._isReadyToPlay = true;
  66041. }
  66042. };
  66043. Sound.prototype.updateOptions = function (options) {
  66044. if (options) {
  66045. this.loop = options.loop || this.loop;
  66046. this.maxDistance = options.maxDistance || this.maxDistance;
  66047. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  66048. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  66049. this.refDistance = options.refDistance || this.refDistance;
  66050. this.distanceModel = options.distanceModel || this.distanceModel;
  66051. this._playbackRate = options.playbackRate || this._playbackRate;
  66052. this._updateSpatialParameters();
  66053. if (this.isPlaying) {
  66054. if (this._streaming && this._htmlAudioElement) {
  66055. this._htmlAudioElement.playbackRate = this._playbackRate;
  66056. }
  66057. else {
  66058. if (this._soundSource) {
  66059. this._soundSource.playbackRate.value = this._playbackRate;
  66060. }
  66061. }
  66062. }
  66063. }
  66064. };
  66065. Sound.prototype._createSpatialParameters = function () {
  66066. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66067. if (this._scene.headphone) {
  66068. this._panningModel = "HRTF";
  66069. }
  66070. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  66071. this._updateSpatialParameters();
  66072. this._soundPanner.connect(this._outputAudioNode);
  66073. this._inputAudioNode = this._soundPanner;
  66074. }
  66075. };
  66076. Sound.prototype._updateSpatialParameters = function () {
  66077. if (this.spatialSound && this._soundPanner) {
  66078. if (this.useCustomAttenuation) {
  66079. // Tricks to disable in a way embedded Web Audio attenuation
  66080. this._soundPanner.distanceModel = "linear";
  66081. this._soundPanner.maxDistance = Number.MAX_VALUE;
  66082. this._soundPanner.refDistance = 1;
  66083. this._soundPanner.rolloffFactor = 1;
  66084. this._soundPanner.panningModel = this._panningModel;
  66085. }
  66086. else {
  66087. this._soundPanner.distanceModel = this.distanceModel;
  66088. this._soundPanner.maxDistance = this.maxDistance;
  66089. this._soundPanner.refDistance = this.refDistance;
  66090. this._soundPanner.rolloffFactor = this.rolloffFactor;
  66091. this._soundPanner.panningModel = this._panningModel;
  66092. }
  66093. }
  66094. };
  66095. Sound.prototype.switchPanningModelToHRTF = function () {
  66096. this._panningModel = "HRTF";
  66097. this._switchPanningModel();
  66098. };
  66099. Sound.prototype.switchPanningModelToEqualPower = function () {
  66100. this._panningModel = "equalpower";
  66101. this._switchPanningModel();
  66102. };
  66103. Sound.prototype._switchPanningModel = function () {
  66104. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66105. this._soundPanner.panningModel = this._panningModel;
  66106. }
  66107. };
  66108. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  66109. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66110. if (this._isOutputConnected) {
  66111. this._outputAudioNode.disconnect();
  66112. }
  66113. this._outputAudioNode.connect(soundTrackAudioNode);
  66114. this._isOutputConnected = true;
  66115. }
  66116. };
  66117. /**
  66118. * Transform this sound into a directional source
  66119. * @param coneInnerAngle Size of the inner cone in degree
  66120. * @param coneOuterAngle Size of the outer cone in degree
  66121. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  66122. */
  66123. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  66124. if (coneOuterAngle < coneInnerAngle) {
  66125. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  66126. return;
  66127. }
  66128. this._coneInnerAngle = coneInnerAngle;
  66129. this._coneOuterAngle = coneOuterAngle;
  66130. this._coneOuterGain = coneOuterGain;
  66131. this._isDirectional = true;
  66132. if (this.isPlaying && this.loop) {
  66133. this.stop();
  66134. this.play();
  66135. }
  66136. };
  66137. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  66138. /**
  66139. * Gets or sets the inner angle for the directional cone.
  66140. */
  66141. get: function () {
  66142. return this._coneInnerAngle;
  66143. },
  66144. /**
  66145. * Gets or sets the inner angle for the directional cone.
  66146. */
  66147. set: function (value) {
  66148. if (value != this._coneInnerAngle) {
  66149. if (this._coneOuterAngle < value) {
  66150. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66151. return;
  66152. }
  66153. this._coneInnerAngle = value;
  66154. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66155. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66156. }
  66157. }
  66158. },
  66159. enumerable: true,
  66160. configurable: true
  66161. });
  66162. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  66163. /**
  66164. * Gets or sets the outer angle for the directional cone.
  66165. */
  66166. get: function () {
  66167. return this._coneOuterAngle;
  66168. },
  66169. /**
  66170. * Gets or sets the outer angle for the directional cone.
  66171. */
  66172. set: function (value) {
  66173. if (value != this._coneOuterAngle) {
  66174. if (value < this._coneInnerAngle) {
  66175. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66176. return;
  66177. }
  66178. this._coneOuterAngle = value;
  66179. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66180. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66181. }
  66182. }
  66183. },
  66184. enumerable: true,
  66185. configurable: true
  66186. });
  66187. Sound.prototype.setPosition = function (newPosition) {
  66188. this._position = newPosition;
  66189. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66190. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66191. }
  66192. };
  66193. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  66194. this._localDirection = newLocalDirection;
  66195. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  66196. this._updateDirection();
  66197. }
  66198. };
  66199. Sound.prototype._updateDirection = function () {
  66200. if (!this._connectedMesh || !this._soundPanner) {
  66201. return;
  66202. }
  66203. var mat = this._connectedMesh.getWorldMatrix();
  66204. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  66205. direction.normalize();
  66206. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  66207. };
  66208. Sound.prototype.updateDistanceFromListener = function () {
  66209. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  66210. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  66211. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  66212. }
  66213. };
  66214. Sound.prototype.setAttenuationFunction = function (callback) {
  66215. this._customAttenuationFunction = callback;
  66216. };
  66217. /**
  66218. * Play the sound
  66219. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  66220. * @param offset (optional) Start the sound setting it at a specific time
  66221. */
  66222. Sound.prototype.play = function (time, offset) {
  66223. var _this = this;
  66224. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  66225. try {
  66226. if (this._startOffset < 0) {
  66227. time = -this._startOffset;
  66228. this._startOffset = 0;
  66229. }
  66230. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66231. if (!this._soundSource || !this._streamingSource) {
  66232. if (this.spatialSound && this._soundPanner) {
  66233. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66234. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66235. }
  66236. if (this._isDirectional) {
  66237. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66238. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66239. this._soundPanner.coneOuterGain = this._coneOuterGain;
  66240. if (this._connectedMesh) {
  66241. this._updateDirection();
  66242. }
  66243. else {
  66244. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  66245. }
  66246. }
  66247. }
  66248. }
  66249. if (this._streaming) {
  66250. if (!this._streamingSource) {
  66251. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  66252. this._htmlAudioElement.onended = function () { _this._onended(); };
  66253. this._htmlAudioElement.playbackRate = this._playbackRate;
  66254. }
  66255. this._streamingSource.disconnect();
  66256. this._streamingSource.connect(this._inputAudioNode);
  66257. if (this._htmlAudioElement) {
  66258. this._htmlAudioElement.play();
  66259. }
  66260. }
  66261. else {
  66262. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  66263. this._soundSource.buffer = this._audioBuffer;
  66264. this._soundSource.connect(this._inputAudioNode);
  66265. this._soundSource.loop = this.loop;
  66266. this._soundSource.playbackRate.value = this._playbackRate;
  66267. this._soundSource.onended = function () { _this._onended(); };
  66268. if (this._soundSource.buffer) {
  66269. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  66270. }
  66271. }
  66272. this._startTime = startTime;
  66273. this.isPlaying = true;
  66274. this.isPaused = false;
  66275. }
  66276. catch (ex) {
  66277. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  66278. }
  66279. }
  66280. };
  66281. Sound.prototype._onended = function () {
  66282. this.isPlaying = false;
  66283. if (this.onended) {
  66284. this.onended();
  66285. }
  66286. this.onEndedObservable.notifyObservers(this);
  66287. };
  66288. /**
  66289. * Stop the sound
  66290. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  66291. */
  66292. Sound.prototype.stop = function (time) {
  66293. if (this.isPlaying) {
  66294. if (this._streaming) {
  66295. if (this._htmlAudioElement) {
  66296. this._htmlAudioElement.pause();
  66297. // Test needed for Firefox or it will generate an Invalid State Error
  66298. if (this._htmlAudioElement.currentTime > 0) {
  66299. this._htmlAudioElement.currentTime = 0;
  66300. }
  66301. }
  66302. else {
  66303. this._streamingSource.disconnect();
  66304. }
  66305. }
  66306. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  66307. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66308. this._soundSource.stop(stopTime);
  66309. this._soundSource.onended = function () { };
  66310. if (!this.isPaused) {
  66311. this._startOffset = 0;
  66312. }
  66313. }
  66314. this.isPlaying = false;
  66315. }
  66316. };
  66317. Sound.prototype.pause = function () {
  66318. if (this.isPlaying) {
  66319. this.isPaused = true;
  66320. if (this._streaming) {
  66321. if (this._htmlAudioElement) {
  66322. this._htmlAudioElement.pause();
  66323. }
  66324. else {
  66325. this._streamingSource.disconnect();
  66326. }
  66327. }
  66328. else if (BABYLON.Engine.audioEngine.audioContext) {
  66329. this.stop(0);
  66330. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  66331. }
  66332. }
  66333. };
  66334. Sound.prototype.setVolume = function (newVolume, time) {
  66335. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  66336. if (time && BABYLON.Engine.audioEngine.audioContext) {
  66337. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  66338. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  66339. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  66340. }
  66341. else {
  66342. this._soundGain.gain.value = newVolume;
  66343. }
  66344. }
  66345. this._volume = newVolume;
  66346. };
  66347. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  66348. this._playbackRate = newPlaybackRate;
  66349. if (this.isPlaying) {
  66350. if (this._streaming && this._htmlAudioElement) {
  66351. this._htmlAudioElement.playbackRate = this._playbackRate;
  66352. }
  66353. else if (this._soundSource) {
  66354. this._soundSource.playbackRate.value = this._playbackRate;
  66355. }
  66356. }
  66357. };
  66358. Sound.prototype.getVolume = function () {
  66359. return this._volume;
  66360. };
  66361. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  66362. var _this = this;
  66363. if (this._connectedMesh && this._registerFunc) {
  66364. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66365. this._registerFunc = null;
  66366. }
  66367. this._connectedMesh = meshToConnectTo;
  66368. if (!this.spatialSound) {
  66369. this.spatialSound = true;
  66370. this._createSpatialParameters();
  66371. if (this.isPlaying && this.loop) {
  66372. this.stop();
  66373. this.play();
  66374. }
  66375. }
  66376. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  66377. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  66378. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  66379. };
  66380. Sound.prototype.detachFromMesh = function () {
  66381. if (this._connectedMesh && this._registerFunc) {
  66382. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66383. this._registerFunc = null;
  66384. this._connectedMesh = null;
  66385. }
  66386. };
  66387. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  66388. if (!node.getBoundingInfo) {
  66389. return;
  66390. }
  66391. var mesh = node;
  66392. if (this._positionInEmitterSpace) {
  66393. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  66394. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  66395. }
  66396. else {
  66397. var boundingInfo = mesh.getBoundingInfo();
  66398. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  66399. }
  66400. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  66401. this._updateDirection();
  66402. }
  66403. };
  66404. Sound.prototype.clone = function () {
  66405. var _this = this;
  66406. if (!this._streaming) {
  66407. var setBufferAndRun = function () {
  66408. if (_this._isReadyToPlay) {
  66409. clonedSound._audioBuffer = _this.getAudioBuffer();
  66410. clonedSound._isReadyToPlay = true;
  66411. if (clonedSound.autoplay) {
  66412. clonedSound.play();
  66413. }
  66414. }
  66415. else {
  66416. window.setTimeout(setBufferAndRun, 300);
  66417. }
  66418. };
  66419. var currentOptions = {
  66420. autoplay: this.autoplay, loop: this.loop,
  66421. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  66422. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  66423. refDistance: this.refDistance, distanceModel: this.distanceModel
  66424. };
  66425. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  66426. if (this.useCustomAttenuation) {
  66427. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  66428. }
  66429. clonedSound.setPosition(this._position);
  66430. clonedSound.setPlaybackRate(this._playbackRate);
  66431. setBufferAndRun();
  66432. return clonedSound;
  66433. }
  66434. // Can't clone a streaming sound
  66435. else {
  66436. return null;
  66437. }
  66438. };
  66439. Sound.prototype.getAudioBuffer = function () {
  66440. return this._audioBuffer;
  66441. };
  66442. Sound.prototype.serialize = function () {
  66443. var serializationObject = {
  66444. name: this.name,
  66445. url: this.name,
  66446. autoplay: this.autoplay,
  66447. loop: this.loop,
  66448. volume: this._volume,
  66449. spatialSound: this.spatialSound,
  66450. maxDistance: this.maxDistance,
  66451. rolloffFactor: this.rolloffFactor,
  66452. refDistance: this.refDistance,
  66453. distanceModel: this.distanceModel,
  66454. playbackRate: this._playbackRate,
  66455. panningModel: this._panningModel,
  66456. soundTrackId: this.soundTrackId
  66457. };
  66458. if (this.spatialSound) {
  66459. if (this._connectedMesh)
  66460. serializationObject.connectedMeshId = this._connectedMesh.id;
  66461. serializationObject.position = this._position.asArray();
  66462. serializationObject.refDistance = this.refDistance;
  66463. serializationObject.distanceModel = this.distanceModel;
  66464. serializationObject.isDirectional = this._isDirectional;
  66465. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  66466. serializationObject.coneInnerAngle = this._coneInnerAngle;
  66467. serializationObject.coneOuterAngle = this._coneOuterAngle;
  66468. serializationObject.coneOuterGain = this._coneOuterGain;
  66469. }
  66470. return serializationObject;
  66471. };
  66472. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  66473. var soundName = parsedSound.name;
  66474. var soundUrl;
  66475. if (parsedSound.url) {
  66476. soundUrl = rootUrl + parsedSound.url;
  66477. }
  66478. else {
  66479. soundUrl = rootUrl + soundName;
  66480. }
  66481. var options = {
  66482. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  66483. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  66484. rolloffFactor: parsedSound.rolloffFactor,
  66485. refDistance: parsedSound.refDistance,
  66486. distanceModel: parsedSound.distanceModel,
  66487. playbackRate: parsedSound.playbackRate
  66488. };
  66489. var newSound;
  66490. if (!sourceSound) {
  66491. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  66492. scene._addPendingData(newSound);
  66493. }
  66494. else {
  66495. var setBufferAndRun = function () {
  66496. if (sourceSound._isReadyToPlay) {
  66497. newSound._audioBuffer = sourceSound.getAudioBuffer();
  66498. newSound._isReadyToPlay = true;
  66499. if (newSound.autoplay) {
  66500. newSound.play();
  66501. }
  66502. }
  66503. else {
  66504. window.setTimeout(setBufferAndRun, 300);
  66505. }
  66506. };
  66507. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  66508. setBufferAndRun();
  66509. }
  66510. if (parsedSound.position) {
  66511. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  66512. newSound.setPosition(soundPosition);
  66513. }
  66514. if (parsedSound.isDirectional) {
  66515. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  66516. if (parsedSound.localDirectionToMesh) {
  66517. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  66518. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  66519. }
  66520. }
  66521. if (parsedSound.connectedMeshId) {
  66522. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  66523. if (connectedMesh) {
  66524. newSound.attachToMesh(connectedMesh);
  66525. }
  66526. }
  66527. return newSound;
  66528. };
  66529. return Sound;
  66530. }());
  66531. BABYLON.Sound = Sound;
  66532. })(BABYLON || (BABYLON = {}));
  66533. //# sourceMappingURL=babylon.sound.js.map
  66534. var BABYLON;
  66535. (function (BABYLON) {
  66536. var SoundTrack = /** @class */ (function () {
  66537. function SoundTrack(scene, options) {
  66538. this.id = -1;
  66539. this._isMainTrack = false;
  66540. this._isInitialized = false;
  66541. this._scene = scene;
  66542. this.soundCollection = new Array();
  66543. this._options = options;
  66544. if (!this._isMainTrack) {
  66545. this._scene.soundTracks.push(this);
  66546. this.id = this._scene.soundTracks.length - 1;
  66547. }
  66548. }
  66549. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  66550. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66551. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  66552. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  66553. if (this._options) {
  66554. if (this._options.volume) {
  66555. this._outputAudioNode.gain.value = this._options.volume;
  66556. }
  66557. if (this._options.mainTrack) {
  66558. this._isMainTrack = this._options.mainTrack;
  66559. }
  66560. }
  66561. this._isInitialized = true;
  66562. }
  66563. };
  66564. SoundTrack.prototype.dispose = function () {
  66565. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  66566. if (this._connectedAnalyser) {
  66567. this._connectedAnalyser.stopDebugCanvas();
  66568. }
  66569. while (this.soundCollection.length) {
  66570. this.soundCollection[0].dispose();
  66571. }
  66572. if (this._outputAudioNode) {
  66573. this._outputAudioNode.disconnect();
  66574. }
  66575. this._outputAudioNode = null;
  66576. }
  66577. };
  66578. SoundTrack.prototype.AddSound = function (sound) {
  66579. if (!this._isInitialized) {
  66580. this._initializeSoundTrackAudioGraph();
  66581. }
  66582. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66583. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  66584. }
  66585. if (sound.soundTrackId) {
  66586. if (sound.soundTrackId === -1) {
  66587. this._scene.mainSoundTrack.RemoveSound(sound);
  66588. }
  66589. else {
  66590. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  66591. }
  66592. }
  66593. this.soundCollection.push(sound);
  66594. sound.soundTrackId = this.id;
  66595. };
  66596. SoundTrack.prototype.RemoveSound = function (sound) {
  66597. var index = this.soundCollection.indexOf(sound);
  66598. if (index !== -1) {
  66599. this.soundCollection.splice(index, 1);
  66600. }
  66601. };
  66602. SoundTrack.prototype.setVolume = function (newVolume) {
  66603. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66604. this._outputAudioNode.gain.value = newVolume;
  66605. }
  66606. };
  66607. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  66608. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66609. for (var i = 0; i < this.soundCollection.length; i++) {
  66610. this.soundCollection[i].switchPanningModelToHRTF();
  66611. }
  66612. }
  66613. };
  66614. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  66615. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66616. for (var i = 0; i < this.soundCollection.length; i++) {
  66617. this.soundCollection[i].switchPanningModelToEqualPower();
  66618. }
  66619. }
  66620. };
  66621. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  66622. if (this._connectedAnalyser) {
  66623. this._connectedAnalyser.stopDebugCanvas();
  66624. }
  66625. this._connectedAnalyser = analyser;
  66626. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66627. this._outputAudioNode.disconnect();
  66628. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  66629. }
  66630. };
  66631. return SoundTrack;
  66632. }());
  66633. BABYLON.SoundTrack = SoundTrack;
  66634. })(BABYLON || (BABYLON = {}));
  66635. //# sourceMappingURL=babylon.soundtrack.js.map
  66636. var BABYLON;
  66637. (function (BABYLON) {
  66638. /**
  66639. * Class used to work with sound analyzer using fast fourier transform (FFT)
  66640. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  66641. */
  66642. var Analyser = /** @class */ (function () {
  66643. /**
  66644. * Creates a new analyser
  66645. * @param scene defines hosting scene
  66646. */
  66647. function Analyser(scene) {
  66648. /**
  66649. * Gets or sets the smoothing
  66650. * @ignorenaming
  66651. */
  66652. this.SMOOTHING = 0.75;
  66653. /**
  66654. * Gets or sets the FFT table size
  66655. * @ignorenaming
  66656. */
  66657. this.FFT_SIZE = 512;
  66658. /**
  66659. * Gets or sets the bar graph amplitude
  66660. * @ignorenaming
  66661. */
  66662. this.BARGRAPHAMPLITUDE = 256;
  66663. /**
  66664. * Gets or sets the position of the debug canvas
  66665. * @ignorenaming
  66666. */
  66667. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  66668. /**
  66669. * Gets or sets the debug canvas size
  66670. * @ignorenaming
  66671. */
  66672. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  66673. this._scene = scene;
  66674. this._audioEngine = BABYLON.Engine.audioEngine;
  66675. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  66676. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  66677. this._webAudioAnalyser.minDecibels = -140;
  66678. this._webAudioAnalyser.maxDecibels = 0;
  66679. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66680. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66681. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  66682. }
  66683. }
  66684. /**
  66685. * Get the number of data values you will have to play with for the visualization
  66686. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  66687. * @returns a number
  66688. */
  66689. Analyser.prototype.getFrequencyBinCount = function () {
  66690. if (this._audioEngine.canUseWebAudio) {
  66691. return this._webAudioAnalyser.frequencyBinCount;
  66692. }
  66693. else {
  66694. return 0;
  66695. }
  66696. };
  66697. /**
  66698. * Gets the current frequency data as a byte array
  66699. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66700. * @returns a Uint8Array
  66701. */
  66702. Analyser.prototype.getByteFrequencyData = function () {
  66703. if (this._audioEngine.canUseWebAudio) {
  66704. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66705. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66706. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  66707. }
  66708. return this._byteFreqs;
  66709. };
  66710. /**
  66711. * Gets the current waveform as a byte array
  66712. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  66713. * @returns a Uint8Array
  66714. */
  66715. Analyser.prototype.getByteTimeDomainData = function () {
  66716. if (this._audioEngine.canUseWebAudio) {
  66717. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66718. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66719. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  66720. }
  66721. return this._byteTime;
  66722. };
  66723. /**
  66724. * Gets the current frequency data as a float array
  66725. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66726. * @returns a Float32Array
  66727. */
  66728. Analyser.prototype.getFloatFrequencyData = function () {
  66729. if (this._audioEngine.canUseWebAudio) {
  66730. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66731. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66732. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  66733. }
  66734. return this._floatFreqs;
  66735. };
  66736. /**
  66737. * Renders the debug canvas
  66738. */
  66739. Analyser.prototype.drawDebugCanvas = function () {
  66740. var _this = this;
  66741. if (this._audioEngine.canUseWebAudio) {
  66742. if (!this._debugCanvas) {
  66743. this._debugCanvas = document.createElement("canvas");
  66744. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  66745. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  66746. this._debugCanvas.style.position = "absolute";
  66747. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  66748. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  66749. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  66750. document.body.appendChild(this._debugCanvas);
  66751. this._registerFunc = function () {
  66752. _this.drawDebugCanvas();
  66753. };
  66754. this._scene.registerBeforeRender(this._registerFunc);
  66755. }
  66756. if (this._registerFunc && this._debugCanvasContext) {
  66757. var workingArray = this.getByteFrequencyData();
  66758. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  66759. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  66760. // Draw the frequency domain chart.
  66761. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  66762. var value = workingArray[i];
  66763. var percent = value / this.BARGRAPHAMPLITUDE;
  66764. var height = this.DEBUGCANVASSIZE.height * percent;
  66765. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  66766. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  66767. var hue = i / this.getFrequencyBinCount() * 360;
  66768. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  66769. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  66770. }
  66771. }
  66772. }
  66773. };
  66774. /**
  66775. * Stops rendering the debug canvas and removes it
  66776. */
  66777. Analyser.prototype.stopDebugCanvas = function () {
  66778. if (this._debugCanvas) {
  66779. if (this._registerFunc) {
  66780. this._scene.unregisterBeforeRender(this._registerFunc);
  66781. this._registerFunc = null;
  66782. }
  66783. document.body.removeChild(this._debugCanvas);
  66784. this._debugCanvas = null;
  66785. this._debugCanvasContext = null;
  66786. }
  66787. };
  66788. /**
  66789. * Connects two audio nodes
  66790. * @param inputAudioNode defines first node to connect
  66791. * @param outputAudioNode defines second node to connect
  66792. */
  66793. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  66794. if (this._audioEngine.canUseWebAudio) {
  66795. inputAudioNode.connect(this._webAudioAnalyser);
  66796. this._webAudioAnalyser.connect(outputAudioNode);
  66797. }
  66798. };
  66799. /**
  66800. * Releases all associated resources
  66801. */
  66802. Analyser.prototype.dispose = function () {
  66803. if (this._audioEngine.canUseWebAudio) {
  66804. this._webAudioAnalyser.disconnect();
  66805. }
  66806. };
  66807. return Analyser;
  66808. }());
  66809. BABYLON.Analyser = Analyser;
  66810. })(BABYLON || (BABYLON = {}));
  66811. //# sourceMappingURL=babylon.analyser.js.map
  66812. var BABYLON;
  66813. (function (BABYLON) {
  66814. /**
  66815. * Wraps one or more Sound objects and selects one with random weight for playback.
  66816. */
  66817. var WeightedSound = /** @class */ (function () {
  66818. /**
  66819. * Creates a new WeightedSound from the list of sounds given.
  66820. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  66821. * @param sounds Array of Sounds that will be selected from.
  66822. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  66823. */
  66824. function WeightedSound(loop, sounds, weights) {
  66825. var _this = this;
  66826. /** When true a Sound will be selected and played when the current playing Sound completes. */
  66827. this.loop = false;
  66828. this._coneInnerAngle = 360;
  66829. this._coneOuterAngle = 360;
  66830. this._volume = 1;
  66831. /** A Sound is currently playing. */
  66832. this.isPlaying = false;
  66833. /** A Sound is currently paused. */
  66834. this.isPaused = false;
  66835. this._sounds = [];
  66836. this._weights = [];
  66837. if (sounds.length !== weights.length) {
  66838. throw new Error('Sounds length does not equal weights length');
  66839. }
  66840. this.loop = loop;
  66841. this._weights = weights;
  66842. // Normalize the weights
  66843. var weightSum = 0;
  66844. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  66845. var weight = weights_1[_i];
  66846. weightSum += weight;
  66847. }
  66848. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  66849. for (var i = 0; i < this._weights.length; i++) {
  66850. this._weights[i] *= invWeightSum;
  66851. }
  66852. this._sounds = sounds;
  66853. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  66854. var sound = _b[_a];
  66855. sound.onEndedObservable.add(function () { _this._onended(); });
  66856. }
  66857. }
  66858. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  66859. /**
  66860. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  66861. */
  66862. get: function () {
  66863. return this._coneInnerAngle;
  66864. },
  66865. /**
  66866. * The size of cone in degress for a directional sound in which there will be no attenuation.
  66867. */
  66868. set: function (value) {
  66869. if (value !== this._coneInnerAngle) {
  66870. if (this._coneOuterAngle < value) {
  66871. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66872. return;
  66873. }
  66874. this._coneInnerAngle = value;
  66875. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66876. var sound = _a[_i];
  66877. sound.directionalConeInnerAngle = value;
  66878. }
  66879. }
  66880. },
  66881. enumerable: true,
  66882. configurable: true
  66883. });
  66884. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  66885. /**
  66886. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66887. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66888. */
  66889. get: function () {
  66890. return this._coneOuterAngle;
  66891. },
  66892. /**
  66893. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66894. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66895. */
  66896. set: function (value) {
  66897. if (value !== this._coneOuterAngle) {
  66898. if (value < this._coneInnerAngle) {
  66899. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66900. return;
  66901. }
  66902. this._coneOuterAngle = value;
  66903. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66904. var sound = _a[_i];
  66905. sound.directionalConeOuterAngle = value;
  66906. }
  66907. }
  66908. },
  66909. enumerable: true,
  66910. configurable: true
  66911. });
  66912. Object.defineProperty(WeightedSound.prototype, "volume", {
  66913. /**
  66914. * Playback volume.
  66915. */
  66916. get: function () {
  66917. return this._volume;
  66918. },
  66919. /**
  66920. * Playback volume.
  66921. */
  66922. set: function (value) {
  66923. if (value !== this._volume) {
  66924. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66925. var sound = _a[_i];
  66926. sound.setVolume(value);
  66927. }
  66928. }
  66929. },
  66930. enumerable: true,
  66931. configurable: true
  66932. });
  66933. WeightedSound.prototype._onended = function () {
  66934. if (this._currentIndex !== undefined) {
  66935. this._sounds[this._currentIndex].autoplay = false;
  66936. }
  66937. if (this.loop && this.isPlaying) {
  66938. this.play();
  66939. }
  66940. else {
  66941. this.isPlaying = false;
  66942. }
  66943. };
  66944. /**
  66945. * Suspend playback
  66946. */
  66947. WeightedSound.prototype.pause = function () {
  66948. this.isPaused = true;
  66949. if (this._currentIndex !== undefined) {
  66950. this._sounds[this._currentIndex].pause();
  66951. }
  66952. };
  66953. /**
  66954. * Stop playback
  66955. */
  66956. WeightedSound.prototype.stop = function () {
  66957. this.isPlaying = false;
  66958. if (this._currentIndex !== undefined) {
  66959. this._sounds[this._currentIndex].stop();
  66960. }
  66961. };
  66962. /**
  66963. * Start playback.
  66964. * @param startOffset Position the clip head at a specific time in seconds.
  66965. */
  66966. WeightedSound.prototype.play = function (startOffset) {
  66967. if (!this.isPaused) {
  66968. this.stop();
  66969. var randomValue = Math.random();
  66970. var total = 0;
  66971. for (var i = 0; i < this._weights.length; i++) {
  66972. total += this._weights[i];
  66973. if (randomValue <= total) {
  66974. this._currentIndex = i;
  66975. break;
  66976. }
  66977. }
  66978. }
  66979. var sound = this._sounds[this._currentIndex];
  66980. if (sound.isReady()) {
  66981. sound.play(0, this.isPaused ? undefined : startOffset);
  66982. }
  66983. else {
  66984. sound.autoplay = true;
  66985. }
  66986. this.isPlaying = true;
  66987. this.isPaused = false;
  66988. };
  66989. return WeightedSound;
  66990. }());
  66991. BABYLON.WeightedSound = WeightedSound;
  66992. })(BABYLON || (BABYLON = {}));
  66993. //# sourceMappingURL=babylon.weightedsound.js.map
  66994. var BABYLON;
  66995. (function (BABYLON) {
  66996. var CubeTexture = /** @class */ (function (_super) {
  66997. __extends(CubeTexture, _super);
  66998. /**
  66999. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  67000. * as prefiltered data.
  67001. * @param rootUrl defines the url of the texture or the root name of the six images
  67002. * @param scene defines the scene the texture is attached to
  67003. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  67004. * @param noMipmap defines if mipmaps should be created or not
  67005. * @param files defines the six files to load for the different faces
  67006. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  67007. * @param onError defines a callback triggered in case of error during load
  67008. * @param format defines the internal format to use for the texture once loaded
  67009. * @param prefiltered defines whether or not the texture is created from prefiltered data
  67010. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  67011. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  67012. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  67013. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  67014. * @return the cube texture
  67015. */
  67016. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  67017. if (extensions === void 0) { extensions = null; }
  67018. if (noMipmap === void 0) { noMipmap = false; }
  67019. if (files === void 0) { files = null; }
  67020. if (onLoad === void 0) { onLoad = null; }
  67021. if (onError === void 0) { onError = null; }
  67022. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67023. if (prefiltered === void 0) { prefiltered = false; }
  67024. if (forcedExtension === void 0) { forcedExtension = null; }
  67025. if (createPolynomials === void 0) { createPolynomials = false; }
  67026. if (lodScale === void 0) { lodScale = 0.8; }
  67027. if (lodOffset === void 0) { lodOffset = 0; }
  67028. var _this = _super.call(this, scene) || this;
  67029. /**
  67030. * Gets or sets the center of the bounding box associated with the cube texture
  67031. * It must define where the camera used to render the texture was set
  67032. */
  67033. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67034. _this._rotationY = 0;
  67035. /** @hidden */
  67036. _this._prefiltered = false;
  67037. _this.name = rootUrl;
  67038. _this.url = rootUrl;
  67039. _this._noMipmap = noMipmap;
  67040. _this.hasAlpha = false;
  67041. _this._format = format;
  67042. _this.isCube = true;
  67043. _this._textureMatrix = BABYLON.Matrix.Identity();
  67044. _this._createPolynomials = createPolynomials;
  67045. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  67046. if (!rootUrl && !files) {
  67047. return _this;
  67048. }
  67049. var lastDot = rootUrl.lastIndexOf(".");
  67050. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  67051. var isDDS = (extension === ".dds");
  67052. var isEnv = (extension === ".env");
  67053. if (isEnv) {
  67054. _this.gammaSpace = false;
  67055. _this._prefiltered = false;
  67056. }
  67057. else {
  67058. _this._prefiltered = prefiltered;
  67059. if (prefiltered) {
  67060. _this.gammaSpace = false;
  67061. }
  67062. }
  67063. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  67064. if (!files) {
  67065. if (!isEnv && !isDDS && !extensions) {
  67066. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  67067. }
  67068. files = [];
  67069. if (extensions) {
  67070. for (var index = 0; index < extensions.length; index++) {
  67071. files.push(rootUrl + extensions[index]);
  67072. }
  67073. }
  67074. }
  67075. _this._files = files;
  67076. if (!_this._texture) {
  67077. if (!scene.useDelayedTextureLoading) {
  67078. if (prefiltered) {
  67079. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  67080. }
  67081. else {
  67082. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  67083. }
  67084. }
  67085. else {
  67086. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  67087. }
  67088. }
  67089. else if (onLoad) {
  67090. if (_this._texture.isReady) {
  67091. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  67092. }
  67093. else {
  67094. _this._texture.onLoadedObservable.add(onLoad);
  67095. }
  67096. }
  67097. return _this;
  67098. }
  67099. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  67100. get: function () {
  67101. return this._boundingBoxSize;
  67102. },
  67103. /**
  67104. * Gets or sets the size of the bounding box associated with the cube texture
  67105. * When defined, the cubemap will switch to local mode
  67106. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67107. * @example https://www.babylonjs-playground.com/#RNASML
  67108. */
  67109. set: function (value) {
  67110. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67111. return;
  67112. }
  67113. this._boundingBoxSize = value;
  67114. var scene = this.getScene();
  67115. if (scene) {
  67116. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67117. }
  67118. },
  67119. enumerable: true,
  67120. configurable: true
  67121. });
  67122. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  67123. /**
  67124. * Gets texture matrix rotation angle around Y axis radians.
  67125. */
  67126. get: function () {
  67127. return this._rotationY;
  67128. },
  67129. /**
  67130. * Sets texture matrix rotation angle around Y axis in radians.
  67131. */
  67132. set: function (value) {
  67133. this._rotationY = value;
  67134. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  67135. },
  67136. enumerable: true,
  67137. configurable: true
  67138. });
  67139. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  67140. var rootUrlKey = "";
  67141. files.forEach(function (url) { return rootUrlKey += url; });
  67142. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  67143. };
  67144. /**
  67145. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  67146. * @param url defines the url of the prefiltered texture
  67147. * @param scene defines the scene the texture is attached to
  67148. * @param forcedExtension defines the extension of the file if different from the url
  67149. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  67150. * @return the prefiltered texture
  67151. */
  67152. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  67153. if (forcedExtension === void 0) { forcedExtension = null; }
  67154. if (createPolynomials === void 0) { createPolynomials = true; }
  67155. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  67156. };
  67157. // Methods
  67158. CubeTexture.prototype.delayLoad = function () {
  67159. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  67160. return;
  67161. }
  67162. var scene = this.getScene();
  67163. if (!scene) {
  67164. return;
  67165. }
  67166. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  67167. this._texture = this._getFromCache(this.url, this._noMipmap);
  67168. if (!this._texture) {
  67169. if (this._prefiltered) {
  67170. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  67171. }
  67172. else {
  67173. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  67174. }
  67175. }
  67176. };
  67177. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  67178. return this._textureMatrix;
  67179. };
  67180. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  67181. this._textureMatrix = value;
  67182. };
  67183. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  67184. var texture = BABYLON.SerializationHelper.Parse(function () {
  67185. var prefiltered = false;
  67186. if (parsedTexture.prefiltered) {
  67187. prefiltered = parsedTexture.prefiltered;
  67188. }
  67189. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  67190. }, parsedTexture, scene);
  67191. // Local Cubemaps
  67192. if (parsedTexture.boundingBoxPosition) {
  67193. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  67194. }
  67195. if (parsedTexture.boundingBoxSize) {
  67196. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  67197. }
  67198. // Animations
  67199. if (parsedTexture.animations) {
  67200. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  67201. var parsedAnimation = parsedTexture.animations[animationIndex];
  67202. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  67203. }
  67204. }
  67205. return texture;
  67206. };
  67207. CubeTexture.prototype.clone = function () {
  67208. var _this = this;
  67209. return BABYLON.SerializationHelper.Clone(function () {
  67210. var scene = _this.getScene();
  67211. if (!scene) {
  67212. return _this;
  67213. }
  67214. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  67215. }, this);
  67216. };
  67217. __decorate([
  67218. BABYLON.serialize("rotationY")
  67219. ], CubeTexture.prototype, "rotationY", null);
  67220. return CubeTexture;
  67221. }(BABYLON.BaseTexture));
  67222. BABYLON.CubeTexture = CubeTexture;
  67223. })(BABYLON || (BABYLON = {}));
  67224. //# sourceMappingURL=babylon.cubeTexture.js.map
  67225. var BABYLON;
  67226. (function (BABYLON) {
  67227. /**
  67228. * Raw cube texture where the raw buffers are passed in
  67229. */
  67230. var RawCubeTexture = /** @class */ (function (_super) {
  67231. __extends(RawCubeTexture, _super);
  67232. /**
  67233. * Creates a cube texture where the raw buffers are passed in.
  67234. * @param scene defines the scene the texture is attached to
  67235. * @param data defines the array of data to use to create each face
  67236. * @param size defines the size of the textures
  67237. * @param format defines the format of the data
  67238. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  67239. * @param generateMipMaps defines if the engine should generate the mip levels
  67240. * @param invertY defines if data must be stored with Y axis inverted
  67241. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  67242. * @param compression defines the compression used (null by default)
  67243. */
  67244. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  67245. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67246. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67247. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67248. if (invertY === void 0) { invertY = false; }
  67249. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67250. if (compression === void 0) { compression = null; }
  67251. var _this = _super.call(this, "", scene) || this;
  67252. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  67253. return _this;
  67254. }
  67255. /**
  67256. * Updates the raw cube texture.
  67257. * @param data defines the data to store
  67258. * @param format defines the data format
  67259. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  67260. * @param invertY defines if data must be stored with Y axis inverted
  67261. * @param compression defines the compression used (null by default)
  67262. * @param level defines which level of the texture to update
  67263. */
  67264. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  67265. if (compression === void 0) { compression = null; }
  67266. if (level === void 0) { level = 0; }
  67267. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  67268. };
  67269. /**
  67270. * Updates a raw cube texture with RGBD encoded data.
  67271. * @param data defines the array of data [mipmap][face] to use to create each face
  67272. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  67273. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  67274. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  67275. * @returns a promsie that resolves when the operation is complete
  67276. */
  67277. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  67278. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  67279. if (lodScale === void 0) { lodScale = 0.8; }
  67280. if (lodOffset === void 0) { lodOffset = 0; }
  67281. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  67282. };
  67283. /**
  67284. * Clones the raw cube texture.
  67285. * @return a new cube texture
  67286. */
  67287. RawCubeTexture.prototype.clone = function () {
  67288. var _this = this;
  67289. return BABYLON.SerializationHelper.Clone(function () {
  67290. var scene = _this.getScene();
  67291. var internalTexture = _this._texture;
  67292. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  67293. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  67294. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  67295. }
  67296. return texture;
  67297. }, this);
  67298. };
  67299. /** @hidden */
  67300. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  67301. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  67302. internalTexture._bufferViewArrayArray = data;
  67303. internalTexture._lodGenerationScale = lodScale;
  67304. internalTexture._lodGenerationOffset = lodOffset;
  67305. internalTexture._sphericalPolynomial = sphericalPolynomial;
  67306. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  67307. internalTexture.isReady = true;
  67308. });
  67309. };
  67310. return RawCubeTexture;
  67311. }(BABYLON.CubeTexture));
  67312. BABYLON.RawCubeTexture = RawCubeTexture;
  67313. })(BABYLON || (BABYLON = {}));
  67314. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  67315. var BABYLON;
  67316. (function (BABYLON) {
  67317. var RenderTargetTexture = /** @class */ (function (_super) {
  67318. __extends(RenderTargetTexture, _super);
  67319. /**
  67320. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  67321. * or used a shadow, depth texture...
  67322. * @param name The friendly name of the texture
  67323. * @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)
  67324. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  67325. * @param generateMipMaps True if mip maps need to be generated after render.
  67326. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  67327. * @param type The type of the buffer in the RTT (int, half float, float...)
  67328. * @param isCube True if a cube texture needs to be created
  67329. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  67330. * @param generateDepthBuffer True to generate a depth buffer
  67331. * @param generateStencilBuffer True to generate a stencil buffer
  67332. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  67333. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  67334. */
  67335. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  67336. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  67337. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67338. if (isCube === void 0) { isCube = false; }
  67339. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67340. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67341. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  67342. if (isMulti === void 0) { isMulti = false; }
  67343. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67344. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  67345. _this.isCube = isCube;
  67346. _this.renderParticles = true;
  67347. _this.renderSprites = false;
  67348. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  67349. _this.ignoreCameraViewport = false;
  67350. // Events
  67351. /**
  67352. * An event triggered when the texture is unbind.
  67353. */
  67354. _this.onBeforeBindObservable = new BABYLON.Observable();
  67355. /**
  67356. * An event triggered when the texture is unbind.
  67357. */
  67358. _this.onAfterUnbindObservable = new BABYLON.Observable();
  67359. /**
  67360. * An event triggered before rendering the texture
  67361. */
  67362. _this.onBeforeRenderObservable = new BABYLON.Observable();
  67363. /**
  67364. * An event triggered after rendering the texture
  67365. */
  67366. _this.onAfterRenderObservable = new BABYLON.Observable();
  67367. /**
  67368. * An event triggered after the texture clear
  67369. */
  67370. _this.onClearObservable = new BABYLON.Observable();
  67371. _this._currentRefreshId = -1;
  67372. _this._refreshRate = 1;
  67373. _this._samples = 1;
  67374. /**
  67375. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  67376. * It must define where the camera used to render the texture is set
  67377. */
  67378. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67379. scene = _this.getScene();
  67380. if (!scene) {
  67381. return _this;
  67382. }
  67383. _this.renderList = new Array();
  67384. _this._engine = scene.getEngine();
  67385. _this.name = name;
  67386. _this.isRenderTarget = true;
  67387. _this._initialSizeParameter = size;
  67388. _this._processSizeParameter(size);
  67389. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  67390. });
  67391. _this._generateMipMaps = generateMipMaps ? true : false;
  67392. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  67393. // Rendering groups
  67394. _this._renderingManager = new BABYLON.RenderingManager(scene);
  67395. _this._renderingManager._useSceneAutoClearSetup = true;
  67396. if (isMulti) {
  67397. return _this;
  67398. }
  67399. _this._renderTargetOptions = {
  67400. generateMipMaps: generateMipMaps,
  67401. type: type,
  67402. format: format,
  67403. samplingMode: samplingMode,
  67404. generateDepthBuffer: generateDepthBuffer,
  67405. generateStencilBuffer: generateStencilBuffer
  67406. };
  67407. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  67408. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67409. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67410. }
  67411. if (isCube) {
  67412. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  67413. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  67414. _this._textureMatrix = BABYLON.Matrix.Identity();
  67415. }
  67416. else {
  67417. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  67418. }
  67419. return _this;
  67420. }
  67421. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  67422. get: function () {
  67423. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  67424. },
  67425. enumerable: true,
  67426. configurable: true
  67427. });
  67428. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  67429. get: function () {
  67430. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  67431. },
  67432. enumerable: true,
  67433. configurable: true
  67434. });
  67435. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  67436. get: function () {
  67437. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  67438. },
  67439. enumerable: true,
  67440. configurable: true
  67441. });
  67442. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  67443. /**
  67444. * Use this list to define the list of mesh you want to render.
  67445. */
  67446. get: function () {
  67447. return this._renderList;
  67448. },
  67449. set: function (value) {
  67450. this._renderList = value;
  67451. if (this._renderList) {
  67452. this._hookArray(this._renderList);
  67453. }
  67454. },
  67455. enumerable: true,
  67456. configurable: true
  67457. });
  67458. RenderTargetTexture.prototype._hookArray = function (array) {
  67459. var _this = this;
  67460. var oldPush = array.push;
  67461. array.push = function () {
  67462. var items = [];
  67463. for (var _i = 0; _i < arguments.length; _i++) {
  67464. items[_i] = arguments[_i];
  67465. }
  67466. var result = oldPush.apply(array, items);
  67467. _this.getScene().meshes.forEach(function (mesh) {
  67468. mesh._markSubMeshesAsLightDirty();
  67469. });
  67470. return result;
  67471. };
  67472. var oldSplice = array.splice;
  67473. array.splice = function (index, deleteCount) {
  67474. var deleted = oldSplice.apply(array, [index, deleteCount]);
  67475. _this.getScene().meshes.forEach(function (mesh) {
  67476. mesh._markSubMeshesAsLightDirty();
  67477. });
  67478. return deleted;
  67479. };
  67480. };
  67481. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  67482. set: function (callback) {
  67483. if (this._onAfterUnbindObserver) {
  67484. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  67485. }
  67486. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  67487. },
  67488. enumerable: true,
  67489. configurable: true
  67490. });
  67491. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  67492. set: function (callback) {
  67493. if (this._onBeforeRenderObserver) {
  67494. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67495. }
  67496. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67497. },
  67498. enumerable: true,
  67499. configurable: true
  67500. });
  67501. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  67502. set: function (callback) {
  67503. if (this._onAfterRenderObserver) {
  67504. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67505. }
  67506. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67507. },
  67508. enumerable: true,
  67509. configurable: true
  67510. });
  67511. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  67512. set: function (callback) {
  67513. if (this._onClearObserver) {
  67514. this.onClearObservable.remove(this._onClearObserver);
  67515. }
  67516. this._onClearObserver = this.onClearObservable.add(callback);
  67517. },
  67518. enumerable: true,
  67519. configurable: true
  67520. });
  67521. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  67522. get: function () {
  67523. return this._renderTargetOptions;
  67524. },
  67525. enumerable: true,
  67526. configurable: true
  67527. });
  67528. RenderTargetTexture.prototype._onRatioRescale = function () {
  67529. if (this._sizeRatio) {
  67530. this.resize(this._initialSizeParameter);
  67531. }
  67532. };
  67533. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  67534. get: function () {
  67535. return this._boundingBoxSize;
  67536. },
  67537. /**
  67538. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  67539. * When defined, the cubemap will switch to local mode
  67540. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67541. * @example https://www.babylonjs-playground.com/#RNASML
  67542. */
  67543. set: function (value) {
  67544. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67545. return;
  67546. }
  67547. this._boundingBoxSize = value;
  67548. var scene = this.getScene();
  67549. if (scene) {
  67550. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67551. }
  67552. },
  67553. enumerable: true,
  67554. configurable: true
  67555. });
  67556. /**
  67557. * Creates a depth stencil texture.
  67558. * This is only available in WebGL 2 or with the depth texture extension available.
  67559. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  67560. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  67561. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  67562. */
  67563. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  67564. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  67565. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  67566. if (generateStencil === void 0) { generateStencil = false; }
  67567. if (!this.getScene()) {
  67568. return;
  67569. }
  67570. var engine = this.getScene().getEngine();
  67571. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  67572. bilinearFiltering: bilinearFiltering,
  67573. comparisonFunction: comparisonFunction,
  67574. generateStencil: generateStencil,
  67575. isCube: this.isCube
  67576. });
  67577. engine.setFrameBufferDepthStencilTexture(this);
  67578. };
  67579. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  67580. if (size.ratio) {
  67581. this._sizeRatio = size.ratio;
  67582. this._size = {
  67583. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  67584. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  67585. };
  67586. }
  67587. else {
  67588. this._size = size;
  67589. }
  67590. };
  67591. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  67592. get: function () {
  67593. return this._samples;
  67594. },
  67595. set: function (value) {
  67596. if (this._samples === value) {
  67597. return;
  67598. }
  67599. var scene = this.getScene();
  67600. if (!scene) {
  67601. return;
  67602. }
  67603. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  67604. },
  67605. enumerable: true,
  67606. configurable: true
  67607. });
  67608. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  67609. this._currentRefreshId = -1;
  67610. };
  67611. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  67612. get: function () {
  67613. return this._refreshRate;
  67614. },
  67615. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  67616. set: function (value) {
  67617. this._refreshRate = value;
  67618. this.resetRefreshCounter();
  67619. },
  67620. enumerable: true,
  67621. configurable: true
  67622. });
  67623. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  67624. if (!this._postProcessManager) {
  67625. var scene = this.getScene();
  67626. if (!scene) {
  67627. return;
  67628. }
  67629. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  67630. this._postProcesses = new Array();
  67631. }
  67632. this._postProcesses.push(postProcess);
  67633. this._postProcesses[0].autoClear = false;
  67634. };
  67635. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  67636. if (!this._postProcesses) {
  67637. return;
  67638. }
  67639. if (dispose) {
  67640. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  67641. var postProcess = _a[_i];
  67642. postProcess.dispose();
  67643. }
  67644. }
  67645. this._postProcesses = [];
  67646. };
  67647. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  67648. if (!this._postProcesses) {
  67649. return;
  67650. }
  67651. var index = this._postProcesses.indexOf(postProcess);
  67652. if (index === -1) {
  67653. return;
  67654. }
  67655. this._postProcesses.splice(index, 1);
  67656. if (this._postProcesses.length > 0) {
  67657. this._postProcesses[0].autoClear = false;
  67658. }
  67659. };
  67660. /** @hidden */
  67661. RenderTargetTexture.prototype._shouldRender = function () {
  67662. if (this._currentRefreshId === -1) { // At least render once
  67663. this._currentRefreshId = 1;
  67664. return true;
  67665. }
  67666. if (this.refreshRate === this._currentRefreshId) {
  67667. this._currentRefreshId = 1;
  67668. return true;
  67669. }
  67670. this._currentRefreshId++;
  67671. return false;
  67672. };
  67673. RenderTargetTexture.prototype.getRenderSize = function () {
  67674. if (this._size.width) {
  67675. return this._size.width;
  67676. }
  67677. return this._size;
  67678. };
  67679. RenderTargetTexture.prototype.getRenderWidth = function () {
  67680. if (this._size.width) {
  67681. return this._size.width;
  67682. }
  67683. return this._size;
  67684. };
  67685. RenderTargetTexture.prototype.getRenderHeight = function () {
  67686. if (this._size.width) {
  67687. return this._size.height;
  67688. }
  67689. return this._size;
  67690. };
  67691. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  67692. get: function () {
  67693. return true;
  67694. },
  67695. enumerable: true,
  67696. configurable: true
  67697. });
  67698. RenderTargetTexture.prototype.scale = function (ratio) {
  67699. var newSize = this.getRenderSize() * ratio;
  67700. this.resize(newSize);
  67701. };
  67702. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  67703. if (this.isCube) {
  67704. return this._textureMatrix;
  67705. }
  67706. return _super.prototype.getReflectionTextureMatrix.call(this);
  67707. };
  67708. RenderTargetTexture.prototype.resize = function (size) {
  67709. this.releaseInternalTexture();
  67710. var scene = this.getScene();
  67711. if (!scene) {
  67712. return;
  67713. }
  67714. this._processSizeParameter(size);
  67715. if (this.isCube) {
  67716. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  67717. }
  67718. else {
  67719. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  67720. }
  67721. };
  67722. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  67723. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  67724. if (dumpForDebug === void 0) { dumpForDebug = false; }
  67725. var scene = this.getScene();
  67726. if (!scene) {
  67727. return;
  67728. }
  67729. var engine = scene.getEngine();
  67730. if (this.useCameraPostProcesses !== undefined) {
  67731. useCameraPostProcess = this.useCameraPostProcesses;
  67732. }
  67733. if (this._waitingRenderList) {
  67734. this.renderList = [];
  67735. for (var index = 0; index < this._waitingRenderList.length; index++) {
  67736. var id = this._waitingRenderList[index];
  67737. var mesh_1 = scene.getMeshByID(id);
  67738. if (mesh_1) {
  67739. this.renderList.push(mesh_1);
  67740. }
  67741. }
  67742. delete this._waitingRenderList;
  67743. }
  67744. // Is predicate defined?
  67745. if (this.renderListPredicate) {
  67746. if (this.renderList) {
  67747. this.renderList.splice(0); // Clear previous renderList
  67748. }
  67749. else {
  67750. this.renderList = [];
  67751. }
  67752. var scene = this.getScene();
  67753. if (!scene) {
  67754. return;
  67755. }
  67756. var sceneMeshes = scene.meshes;
  67757. for (var index = 0; index < sceneMeshes.length; index++) {
  67758. var mesh = sceneMeshes[index];
  67759. if (this.renderListPredicate(mesh)) {
  67760. this.renderList.push(mesh);
  67761. }
  67762. }
  67763. }
  67764. this.onBeforeBindObservable.notifyObservers(this);
  67765. // Set custom projection.
  67766. // Needs to be before binding to prevent changing the aspect ratio.
  67767. var camera;
  67768. if (this.activeCamera) {
  67769. camera = this.activeCamera;
  67770. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  67771. if (this.activeCamera !== scene.activeCamera) {
  67772. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  67773. }
  67774. }
  67775. else {
  67776. camera = scene.activeCamera;
  67777. if (camera) {
  67778. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  67779. }
  67780. }
  67781. // Prepare renderingManager
  67782. this._renderingManager.reset();
  67783. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  67784. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  67785. var sceneRenderId = scene.getRenderId();
  67786. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  67787. var mesh = currentRenderList[meshIndex];
  67788. if (mesh) {
  67789. if (!mesh.isReady(this.refreshRate === 0)) {
  67790. this.resetRefreshCounter();
  67791. continue;
  67792. }
  67793. mesh._preActivateForIntermediateRendering(sceneRenderId);
  67794. var isMasked = void 0;
  67795. if (!this.renderList && camera) {
  67796. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  67797. }
  67798. else {
  67799. isMasked = false;
  67800. }
  67801. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  67802. mesh._activate(sceneRenderId);
  67803. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  67804. var subMesh = mesh.subMeshes[subIndex];
  67805. scene._activeIndices.addCount(subMesh.indexCount, false);
  67806. this._renderingManager.dispatch(subMesh, mesh);
  67807. }
  67808. }
  67809. }
  67810. }
  67811. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  67812. var particleSystem = scene.particleSystems[particleIndex];
  67813. var emitter = particleSystem.emitter;
  67814. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  67815. continue;
  67816. }
  67817. if (currentRenderList.indexOf(emitter) >= 0) {
  67818. this._renderingManager.dispatchParticles(particleSystem);
  67819. }
  67820. }
  67821. if (this.isCube) {
  67822. for (var face = 0; face < 6; face++) {
  67823. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  67824. scene.incrementRenderId();
  67825. scene.resetCachedMaterial();
  67826. }
  67827. }
  67828. else {
  67829. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  67830. }
  67831. this.onAfterUnbindObservable.notifyObservers(this);
  67832. if (scene.activeCamera) {
  67833. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  67834. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  67835. }
  67836. engine.setViewport(scene.activeCamera.viewport);
  67837. }
  67838. scene.resetCachedMaterial();
  67839. };
  67840. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  67841. var minimum = 128;
  67842. var x = renderDimension * scale;
  67843. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  67844. // Ensure we don't exceed the render dimension (while staying POT)
  67845. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  67846. };
  67847. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  67848. var _this = this;
  67849. if (!this._texture) {
  67850. return;
  67851. }
  67852. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  67853. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  67854. });
  67855. };
  67856. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  67857. var scene = this.getScene();
  67858. if (!scene) {
  67859. return;
  67860. }
  67861. var engine = scene.getEngine();
  67862. if (!this._texture) {
  67863. return;
  67864. }
  67865. // Bind
  67866. if (this._postProcessManager) {
  67867. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  67868. }
  67869. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  67870. if (this._texture) {
  67871. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  67872. }
  67873. }
  67874. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  67875. // Clear
  67876. if (this.onClearObservable.hasObservers()) {
  67877. this.onClearObservable.notifyObservers(engine);
  67878. }
  67879. else {
  67880. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  67881. }
  67882. if (!this._doNotChangeAspectRatio) {
  67883. scene.updateTransformMatrix(true);
  67884. }
  67885. // Render
  67886. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  67887. if (this._postProcessManager) {
  67888. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  67889. }
  67890. else if (useCameraPostProcess) {
  67891. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  67892. }
  67893. if (!this._doNotChangeAspectRatio) {
  67894. scene.updateTransformMatrix(true);
  67895. }
  67896. // Dump ?
  67897. if (dumpForDebug) {
  67898. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  67899. }
  67900. // Unbind
  67901. if (!this.isCube || faceIndex === 5) {
  67902. if (this.isCube) {
  67903. if (faceIndex === 5) {
  67904. engine.generateMipMapsForCubemap(this._texture);
  67905. }
  67906. }
  67907. this.unbindFrameBuffer(engine, faceIndex);
  67908. }
  67909. else {
  67910. this.onAfterRenderObservable.notifyObservers(faceIndex);
  67911. }
  67912. };
  67913. /**
  67914. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  67915. * This allowed control for front to back rendering or reversly depending of the special needs.
  67916. *
  67917. * @param renderingGroupId The rendering group id corresponding to its index
  67918. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  67919. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  67920. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  67921. */
  67922. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  67923. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  67924. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  67925. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  67926. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  67927. };
  67928. /**
  67929. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  67930. *
  67931. * @param renderingGroupId The rendering group id corresponding to its index
  67932. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  67933. */
  67934. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  67935. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  67936. this._renderingManager._useSceneAutoClearSetup = false;
  67937. };
  67938. RenderTargetTexture.prototype.clone = function () {
  67939. var textureSize = this.getSize();
  67940. 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);
  67941. // Base texture
  67942. newTexture.hasAlpha = this.hasAlpha;
  67943. newTexture.level = this.level;
  67944. // RenderTarget Texture
  67945. newTexture.coordinatesMode = this.coordinatesMode;
  67946. if (this.renderList) {
  67947. newTexture.renderList = this.renderList.slice(0);
  67948. }
  67949. return newTexture;
  67950. };
  67951. RenderTargetTexture.prototype.serialize = function () {
  67952. if (!this.name) {
  67953. return null;
  67954. }
  67955. var serializationObject = _super.prototype.serialize.call(this);
  67956. serializationObject.renderTargetSize = this.getRenderSize();
  67957. serializationObject.renderList = [];
  67958. if (this.renderList) {
  67959. for (var index = 0; index < this.renderList.length; index++) {
  67960. serializationObject.renderList.push(this.renderList[index].id);
  67961. }
  67962. }
  67963. return serializationObject;
  67964. };
  67965. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  67966. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  67967. var objBuffer = this.getInternalTexture();
  67968. var scene = this.getScene();
  67969. if (objBuffer && scene) {
  67970. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  67971. }
  67972. };
  67973. RenderTargetTexture.prototype.dispose = function () {
  67974. if (this._postProcessManager) {
  67975. this._postProcessManager.dispose();
  67976. this._postProcessManager = null;
  67977. }
  67978. this.clearPostProcesses(true);
  67979. if (this._resizeObserver) {
  67980. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  67981. this._resizeObserver = null;
  67982. }
  67983. this.renderList = null;
  67984. // Remove from custom render targets
  67985. var scene = this.getScene();
  67986. if (!scene) {
  67987. return;
  67988. }
  67989. var index = scene.customRenderTargets.indexOf(this);
  67990. if (index >= 0) {
  67991. scene.customRenderTargets.splice(index, 1);
  67992. }
  67993. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  67994. var camera = _a[_i];
  67995. index = camera.customRenderTargets.indexOf(this);
  67996. if (index >= 0) {
  67997. camera.customRenderTargets.splice(index, 1);
  67998. }
  67999. }
  68000. _super.prototype.dispose.call(this);
  68001. };
  68002. /** @hidden */
  68003. RenderTargetTexture.prototype._rebuild = function () {
  68004. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  68005. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  68006. }
  68007. if (this._postProcessManager) {
  68008. this._postProcessManager._rebuild();
  68009. }
  68010. };
  68011. /**
  68012. * Clear the info related to rendering groups preventing retention point in material dispose.
  68013. */
  68014. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  68015. if (this._renderingManager) {
  68016. this._renderingManager.freeRenderingGroups();
  68017. }
  68018. };
  68019. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  68020. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  68021. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  68022. return RenderTargetTexture;
  68023. }(BABYLON.Texture));
  68024. BABYLON.RenderTargetTexture = RenderTargetTexture;
  68025. })(BABYLON || (BABYLON = {}));
  68026. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  68027. var BABYLON;
  68028. (function (BABYLON) {
  68029. ;
  68030. var MultiRenderTarget = /** @class */ (function (_super) {
  68031. __extends(MultiRenderTarget, _super);
  68032. function MultiRenderTarget(name, size, count, scene, options) {
  68033. var _this = this;
  68034. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  68035. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  68036. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  68037. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  68038. _this._engine = scene.getEngine();
  68039. if (!_this.isSupported) {
  68040. _this.dispose();
  68041. return;
  68042. }
  68043. var types = [];
  68044. var samplingModes = [];
  68045. for (var i = 0; i < count; i++) {
  68046. if (options && options.types && options.types[i] !== undefined) {
  68047. types.push(options.types[i]);
  68048. }
  68049. else {
  68050. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68051. }
  68052. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  68053. samplingModes.push(options.samplingModes[i]);
  68054. }
  68055. else {
  68056. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68057. }
  68058. }
  68059. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  68060. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  68061. _this._size = size;
  68062. _this._multiRenderTargetOptions = {
  68063. samplingModes: samplingModes,
  68064. generateMipMaps: generateMipMaps,
  68065. generateDepthBuffer: generateDepthBuffer,
  68066. generateStencilBuffer: generateStencilBuffer,
  68067. generateDepthTexture: generateDepthTexture,
  68068. types: types,
  68069. textureCount: count
  68070. };
  68071. _this._createInternalTextures();
  68072. _this._createTextures();
  68073. return _this;
  68074. }
  68075. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  68076. get: function () {
  68077. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  68078. },
  68079. enumerable: true,
  68080. configurable: true
  68081. });
  68082. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  68083. get: function () {
  68084. return this._textures;
  68085. },
  68086. enumerable: true,
  68087. configurable: true
  68088. });
  68089. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  68090. get: function () {
  68091. return this._textures[this._textures.length - 1];
  68092. },
  68093. enumerable: true,
  68094. configurable: true
  68095. });
  68096. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  68097. set: function (wrap) {
  68098. if (this._textures) {
  68099. for (var i = 0; i < this._textures.length; i++) {
  68100. this._textures[i].wrapU = wrap;
  68101. }
  68102. }
  68103. },
  68104. enumerable: true,
  68105. configurable: true
  68106. });
  68107. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  68108. set: function (wrap) {
  68109. if (this._textures) {
  68110. for (var i = 0; i < this._textures.length; i++) {
  68111. this._textures[i].wrapV = wrap;
  68112. }
  68113. }
  68114. },
  68115. enumerable: true,
  68116. configurable: true
  68117. });
  68118. /** @hidden */
  68119. MultiRenderTarget.prototype._rebuild = function () {
  68120. this.releaseInternalTextures();
  68121. this._createInternalTextures();
  68122. for (var i = 0; i < this._internalTextures.length; i++) {
  68123. var texture = this._textures[i];
  68124. texture._texture = this._internalTextures[i];
  68125. }
  68126. // Keeps references to frame buffer and stencil/depth buffer
  68127. this._texture = this._internalTextures[0];
  68128. };
  68129. MultiRenderTarget.prototype._createInternalTextures = function () {
  68130. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  68131. };
  68132. MultiRenderTarget.prototype._createTextures = function () {
  68133. this._textures = [];
  68134. for (var i = 0; i < this._internalTextures.length; i++) {
  68135. var texture = new BABYLON.Texture(null, this.getScene());
  68136. texture._texture = this._internalTextures[i];
  68137. this._textures.push(texture);
  68138. }
  68139. // Keeps references to frame buffer and stencil/depth buffer
  68140. this._texture = this._internalTextures[0];
  68141. };
  68142. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  68143. get: function () {
  68144. return this._samples;
  68145. },
  68146. set: function (value) {
  68147. if (this._samples === value) {
  68148. return;
  68149. }
  68150. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  68151. },
  68152. enumerable: true,
  68153. configurable: true
  68154. });
  68155. MultiRenderTarget.prototype.resize = function (size) {
  68156. this.releaseInternalTextures();
  68157. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  68158. this._createInternalTextures();
  68159. };
  68160. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  68161. var _this = this;
  68162. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  68163. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  68164. });
  68165. };
  68166. MultiRenderTarget.prototype.dispose = function () {
  68167. this.releaseInternalTextures();
  68168. _super.prototype.dispose.call(this);
  68169. };
  68170. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  68171. if (!this._internalTextures) {
  68172. return;
  68173. }
  68174. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  68175. if (this._internalTextures[i] !== undefined) {
  68176. this._internalTextures[i].dispose();
  68177. this._internalTextures.splice(i, 1);
  68178. }
  68179. }
  68180. };
  68181. return MultiRenderTarget;
  68182. }(BABYLON.RenderTargetTexture));
  68183. BABYLON.MultiRenderTarget = MultiRenderTarget;
  68184. })(BABYLON || (BABYLON = {}));
  68185. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  68186. var BABYLON;
  68187. (function (BABYLON) {
  68188. var MirrorTexture = /** @class */ (function (_super) {
  68189. __extends(MirrorTexture, _super);
  68190. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  68191. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68192. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68193. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  68194. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  68195. _this.scene = scene;
  68196. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  68197. _this._transformMatrix = BABYLON.Matrix.Zero();
  68198. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  68199. _this._adaptiveBlurKernel = 0;
  68200. _this._blurKernelX = 0;
  68201. _this._blurKernelY = 0;
  68202. _this._blurRatio = 1.0;
  68203. _this.ignoreCameraViewport = true;
  68204. _this._updateGammaSpace();
  68205. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  68206. _this._updateGammaSpace;
  68207. });
  68208. _this.onBeforeRenderObservable.add(function () {
  68209. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  68210. _this._savedViewMatrix = scene.getViewMatrix();
  68211. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  68212. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  68213. scene.clipPlane = _this.mirrorPlane;
  68214. scene.getEngine().cullBackFaces = false;
  68215. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  68216. });
  68217. _this.onAfterRenderObservable.add(function () {
  68218. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  68219. scene.getEngine().cullBackFaces = true;
  68220. scene._mirroredCameraPosition = null;
  68221. delete scene.clipPlane;
  68222. });
  68223. return _this;
  68224. }
  68225. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  68226. get: function () {
  68227. return this._blurRatio;
  68228. },
  68229. set: function (value) {
  68230. if (this._blurRatio === value) {
  68231. return;
  68232. }
  68233. this._blurRatio = value;
  68234. this._preparePostProcesses();
  68235. },
  68236. enumerable: true,
  68237. configurable: true
  68238. });
  68239. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  68240. set: function (value) {
  68241. this._adaptiveBlurKernel = value;
  68242. this._autoComputeBlurKernel();
  68243. },
  68244. enumerable: true,
  68245. configurable: true
  68246. });
  68247. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  68248. set: function (value) {
  68249. this.blurKernelX = value;
  68250. this.blurKernelY = value;
  68251. },
  68252. enumerable: true,
  68253. configurable: true
  68254. });
  68255. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  68256. get: function () {
  68257. return this._blurKernelX;
  68258. },
  68259. set: function (value) {
  68260. if (this._blurKernelX === value) {
  68261. return;
  68262. }
  68263. this._blurKernelX = value;
  68264. this._preparePostProcesses();
  68265. },
  68266. enumerable: true,
  68267. configurable: true
  68268. });
  68269. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  68270. get: function () {
  68271. return this._blurKernelY;
  68272. },
  68273. set: function (value) {
  68274. if (this._blurKernelY === value) {
  68275. return;
  68276. }
  68277. this._blurKernelY = value;
  68278. this._preparePostProcesses();
  68279. },
  68280. enumerable: true,
  68281. configurable: true
  68282. });
  68283. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  68284. var engine = this.getScene().getEngine();
  68285. var dw = this.getRenderWidth() / engine.getRenderWidth();
  68286. var dh = this.getRenderHeight() / engine.getRenderHeight();
  68287. this.blurKernelX = this._adaptiveBlurKernel * dw;
  68288. this.blurKernelY = this._adaptiveBlurKernel * dh;
  68289. };
  68290. MirrorTexture.prototype._onRatioRescale = function () {
  68291. if (this._sizeRatio) {
  68292. this.resize(this._initialSizeParameter);
  68293. if (!this._adaptiveBlurKernel) {
  68294. this._preparePostProcesses();
  68295. }
  68296. }
  68297. if (this._adaptiveBlurKernel) {
  68298. this._autoComputeBlurKernel();
  68299. }
  68300. };
  68301. MirrorTexture.prototype._updateGammaSpace = function () {
  68302. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  68303. };
  68304. MirrorTexture.prototype._preparePostProcesses = function () {
  68305. this.clearPostProcesses(true);
  68306. if (this._blurKernelX && this._blurKernelY) {
  68307. var engine = this.getScene().getEngine();
  68308. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68309. 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);
  68310. this._blurX.autoClear = false;
  68311. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  68312. this._blurX.inputTexture = this._texture;
  68313. }
  68314. else {
  68315. this._blurX.alwaysForcePOT = true;
  68316. }
  68317. 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);
  68318. this._blurY.autoClear = false;
  68319. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  68320. this.addPostProcess(this._blurX);
  68321. this.addPostProcess(this._blurY);
  68322. }
  68323. else {
  68324. if (this._blurY) {
  68325. this.removePostProcess(this._blurY);
  68326. this._blurY.dispose();
  68327. this._blurY = null;
  68328. }
  68329. if (this._blurX) {
  68330. this.removePostProcess(this._blurX);
  68331. this._blurX.dispose();
  68332. this._blurX = null;
  68333. }
  68334. }
  68335. };
  68336. MirrorTexture.prototype.clone = function () {
  68337. var scene = this.getScene();
  68338. if (!scene) {
  68339. return this;
  68340. }
  68341. var textureSize = this.getSize();
  68342. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  68343. // Base texture
  68344. newTexture.hasAlpha = this.hasAlpha;
  68345. newTexture.level = this.level;
  68346. // Mirror Texture
  68347. newTexture.mirrorPlane = this.mirrorPlane.clone();
  68348. if (this.renderList) {
  68349. newTexture.renderList = this.renderList.slice(0);
  68350. }
  68351. return newTexture;
  68352. };
  68353. MirrorTexture.prototype.serialize = function () {
  68354. if (!this.name) {
  68355. return null;
  68356. }
  68357. var serializationObject = _super.prototype.serialize.call(this);
  68358. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  68359. return serializationObject;
  68360. };
  68361. MirrorTexture.prototype.dispose = function () {
  68362. _super.prototype.dispose.call(this);
  68363. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  68364. };
  68365. return MirrorTexture;
  68366. }(BABYLON.RenderTargetTexture));
  68367. BABYLON.MirrorTexture = MirrorTexture;
  68368. })(BABYLON || (BABYLON = {}));
  68369. //# sourceMappingURL=babylon.mirrorTexture.js.map
  68370. var BABYLON;
  68371. (function (BABYLON) {
  68372. /**
  68373. * Creates a refraction texture used by refraction channel of the standard material.
  68374. * @param name the texture name
  68375. * @param size size of the underlying texture
  68376. * @param scene root scene
  68377. */
  68378. var RefractionTexture = /** @class */ (function (_super) {
  68379. __extends(RefractionTexture, _super);
  68380. function RefractionTexture(name, size, scene, generateMipMaps) {
  68381. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  68382. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  68383. _this.depth = 2.0;
  68384. _this.onBeforeRenderObservable.add(function () {
  68385. scene.clipPlane = _this.refractionPlane;
  68386. });
  68387. _this.onAfterRenderObservable.add(function () {
  68388. delete scene.clipPlane;
  68389. });
  68390. return _this;
  68391. }
  68392. RefractionTexture.prototype.clone = function () {
  68393. var scene = this.getScene();
  68394. if (!scene) {
  68395. return this;
  68396. }
  68397. var textureSize = this.getSize();
  68398. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  68399. // Base texture
  68400. newTexture.hasAlpha = this.hasAlpha;
  68401. newTexture.level = this.level;
  68402. // Refraction Texture
  68403. newTexture.refractionPlane = this.refractionPlane.clone();
  68404. if (this.renderList) {
  68405. newTexture.renderList = this.renderList.slice(0);
  68406. }
  68407. newTexture.depth = this.depth;
  68408. return newTexture;
  68409. };
  68410. RefractionTexture.prototype.serialize = function () {
  68411. if (!this.name) {
  68412. return null;
  68413. }
  68414. var serializationObject = _super.prototype.serialize.call(this);
  68415. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  68416. serializationObject.depth = this.depth;
  68417. return serializationObject;
  68418. };
  68419. return RefractionTexture;
  68420. }(BABYLON.RenderTargetTexture));
  68421. BABYLON.RefractionTexture = RefractionTexture;
  68422. })(BABYLON || (BABYLON = {}));
  68423. //# sourceMappingURL=babylon.refractionTexture.js.map
  68424. var BABYLON;
  68425. (function (BABYLON) {
  68426. /**
  68427. * A class extending {BABYLON.Texture} allowing drawing on a texture
  68428. * @see http://doc.babylonjs.com/how_to/dynamictexture
  68429. */
  68430. var DynamicTexture = /** @class */ (function (_super) {
  68431. __extends(DynamicTexture, _super);
  68432. /**
  68433. * Creates a {BABYLON.DynamicTexture}
  68434. * @param name defines the name of the texture
  68435. * @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
  68436. * @param scene defines the scene where you want the texture
  68437. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  68438. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  68439. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  68440. */
  68441. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  68442. if (scene === void 0) { scene = null; }
  68443. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68444. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  68445. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  68446. _this.name = name;
  68447. _this._engine = _this.getScene().getEngine();
  68448. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68449. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68450. _this._generateMipMaps = generateMipMaps;
  68451. if (options.getContext) {
  68452. _this._canvas = options;
  68453. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  68454. }
  68455. else {
  68456. _this._canvas = document.createElement("canvas");
  68457. if (options.width || options.width === 0) {
  68458. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  68459. }
  68460. else {
  68461. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  68462. }
  68463. }
  68464. var textureSize = _this.getSize();
  68465. _this._canvas.width = textureSize.width;
  68466. _this._canvas.height = textureSize.height;
  68467. _this._context = _this._canvas.getContext("2d");
  68468. return _this;
  68469. }
  68470. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  68471. /**
  68472. * Gets the current state of canRescale
  68473. */
  68474. get: function () {
  68475. return true;
  68476. },
  68477. enumerable: true,
  68478. configurable: true
  68479. });
  68480. DynamicTexture.prototype._recreate = function (textureSize) {
  68481. this._canvas.width = textureSize.width;
  68482. this._canvas.height = textureSize.height;
  68483. this.releaseInternalTexture();
  68484. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  68485. };
  68486. /**
  68487. * Scales the texture
  68488. * @param ratio the scale factor to apply to both width and height
  68489. */
  68490. DynamicTexture.prototype.scale = function (ratio) {
  68491. var textureSize = this.getSize();
  68492. textureSize.width *= ratio;
  68493. textureSize.height *= ratio;
  68494. this._recreate(textureSize);
  68495. };
  68496. /**
  68497. * Resizes the texture
  68498. * @param width the new width
  68499. * @param height the new height
  68500. */
  68501. DynamicTexture.prototype.scaleTo = function (width, height) {
  68502. var textureSize = this.getSize();
  68503. textureSize.width = width;
  68504. textureSize.height = height;
  68505. this._recreate(textureSize);
  68506. };
  68507. /**
  68508. * Gets the context of the canvas used by the texture
  68509. * @returns the canvas context of the dynamic texture
  68510. */
  68511. DynamicTexture.prototype.getContext = function () {
  68512. return this._context;
  68513. };
  68514. /**
  68515. * Clears the texture
  68516. */
  68517. DynamicTexture.prototype.clear = function () {
  68518. var size = this.getSize();
  68519. this._context.fillRect(0, 0, size.width, size.height);
  68520. };
  68521. /**
  68522. * Updates the texture
  68523. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68524. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  68525. */
  68526. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  68527. if (premulAlpha === void 0) { premulAlpha = false; }
  68528. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  68529. };
  68530. /**
  68531. * Draws text onto the texture
  68532. * @param text defines the text to be drawn
  68533. * @param x defines the placement of the text from the left
  68534. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  68535. * @param font defines the font to be used with font-style, font-size, font-name
  68536. * @param color defines the color used for the text
  68537. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  68538. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68539. * @param update defines whether texture is immediately update (default is true)
  68540. */
  68541. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  68542. if (update === void 0) { update = true; }
  68543. var size = this.getSize();
  68544. if (clearColor) {
  68545. this._context.fillStyle = clearColor;
  68546. this._context.fillRect(0, 0, size.width, size.height);
  68547. }
  68548. this._context.font = font;
  68549. if (x === null || x === undefined) {
  68550. var textSize = this._context.measureText(text);
  68551. x = (size.width - textSize.width) / 2;
  68552. }
  68553. if (y === null || y === undefined) {
  68554. var fontSize = parseInt((font.replace(/\D/g, '')));
  68555. y = (size.height / 2) + (fontSize / 3.65);
  68556. }
  68557. this._context.fillStyle = color;
  68558. this._context.fillText(text, x, y);
  68559. if (update) {
  68560. this.update(invertY);
  68561. }
  68562. };
  68563. /**
  68564. * Clones the texture
  68565. * @returns the clone of the texture.
  68566. */
  68567. DynamicTexture.prototype.clone = function () {
  68568. var scene = this.getScene();
  68569. if (!scene) {
  68570. return this;
  68571. }
  68572. var textureSize = this.getSize();
  68573. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  68574. // Base texture
  68575. newTexture.hasAlpha = this.hasAlpha;
  68576. newTexture.level = this.level;
  68577. // Dynamic Texture
  68578. newTexture.wrapU = this.wrapU;
  68579. newTexture.wrapV = this.wrapV;
  68580. return newTexture;
  68581. };
  68582. /**
  68583. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  68584. * @returns a serialized dynamic texture object
  68585. */
  68586. DynamicTexture.prototype.serialize = function () {
  68587. var scene = this.getScene();
  68588. if (scene && !scene.isReady()) {
  68589. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  68590. }
  68591. var serializationObject = _super.prototype.serialize.call(this);
  68592. serializationObject.base64String = this._canvas.toDataURL();
  68593. serializationObject.invertY = this._invertY;
  68594. serializationObject.samplingMode = this.samplingMode;
  68595. return serializationObject;
  68596. };
  68597. /** @hidden */
  68598. DynamicTexture.prototype._rebuild = function () {
  68599. this.update();
  68600. };
  68601. return DynamicTexture;
  68602. }(BABYLON.Texture));
  68603. BABYLON.DynamicTexture = DynamicTexture;
  68604. })(BABYLON || (BABYLON = {}));
  68605. //# sourceMappingURL=babylon.dynamicTexture.js.map
  68606. var BABYLON;
  68607. (function (BABYLON) {
  68608. var VideoTexture = /** @class */ (function (_super) {
  68609. __extends(VideoTexture, _super);
  68610. /**
  68611. * Creates a video texture.
  68612. * Sample : https://doc.babylonjs.com/how_to/video_texture
  68613. * @param {string | null} name optional name, will detect from video source, if not defined
  68614. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  68615. * @param {BABYLON.Scene} scene is obviously the current scene.
  68616. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  68617. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  68618. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  68619. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  68620. */
  68621. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  68622. if (generateMipMaps === void 0) { generateMipMaps = false; }
  68623. if (invertY === void 0) { invertY = false; }
  68624. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68625. if (settings === void 0) { settings = {
  68626. autoPlay: true,
  68627. loop: true,
  68628. autoUpdateTexture: true,
  68629. }; }
  68630. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68631. _this._onUserActionRequestedObservable = null;
  68632. _this._stillImageCaptured = false;
  68633. _this._poster = false;
  68634. _this._createInternalTexture = function () {
  68635. if (_this._texture != null) {
  68636. if (_this._poster) {
  68637. _this._texture.dispose();
  68638. _this._poster = false;
  68639. }
  68640. else {
  68641. return;
  68642. }
  68643. }
  68644. if (!_this._engine.needPOTTextures ||
  68645. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  68646. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68647. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68648. }
  68649. else {
  68650. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68651. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68652. _this._generateMipMaps = false;
  68653. }
  68654. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  68655. if (!_this.video.autoplay) {
  68656. var oldHandler_1 = _this.video.onplaying;
  68657. var error_1 = false;
  68658. _this.video.onplaying = function () {
  68659. _this.video.onplaying = oldHandler_1;
  68660. _this._texture.isReady = true;
  68661. _this._updateInternalTexture();
  68662. if (!error_1) {
  68663. _this.video.pause();
  68664. }
  68665. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68666. _this.onLoadObservable.notifyObservers(_this);
  68667. }
  68668. };
  68669. var playing = _this.video.play();
  68670. if (playing) {
  68671. playing.then(function () {
  68672. // Everything is good.
  68673. })
  68674. .catch(function () {
  68675. error_1 = true;
  68676. // On Chrome for instance, new policies might prevent playing without user interaction.
  68677. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  68678. _this._onUserActionRequestedObservable.notifyObservers(_this);
  68679. }
  68680. });
  68681. }
  68682. else {
  68683. _this.video.onplaying = oldHandler_1;
  68684. _this._texture.isReady = true;
  68685. _this._updateInternalTexture();
  68686. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68687. _this.onLoadObservable.notifyObservers(_this);
  68688. }
  68689. }
  68690. }
  68691. else {
  68692. _this._texture.isReady = true;
  68693. _this._updateInternalTexture();
  68694. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68695. _this.onLoadObservable.notifyObservers(_this);
  68696. }
  68697. }
  68698. };
  68699. _this.reset = function () {
  68700. if (_this._texture == null) {
  68701. return;
  68702. }
  68703. if (!_this._poster) {
  68704. _this._texture.dispose();
  68705. _this._texture = null;
  68706. }
  68707. };
  68708. _this._updateInternalTexture = function (e) {
  68709. if (_this._texture == null || !_this._texture.isReady) {
  68710. return;
  68711. }
  68712. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  68713. return;
  68714. }
  68715. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  68716. };
  68717. _this._engine = _this.getScene().getEngine();
  68718. _this._generateMipMaps = generateMipMaps;
  68719. _this._samplingMode = samplingMode;
  68720. _this.autoUpdateTexture = settings.autoUpdateTexture;
  68721. _this.name = name || _this._getName(src);
  68722. _this.video = _this._getVideo(src);
  68723. if (settings.poster) {
  68724. _this.video.poster = settings.poster;
  68725. }
  68726. if (settings.autoPlay !== undefined) {
  68727. _this.video.autoplay = settings.autoPlay;
  68728. }
  68729. if (settings.loop !== undefined) {
  68730. _this.video.loop = settings.loop;
  68731. }
  68732. _this.video.setAttribute("playsinline", "");
  68733. _this.video.addEventListener("canplay", _this._createInternalTexture);
  68734. _this.video.addEventListener("paused", _this._updateInternalTexture);
  68735. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  68736. _this.video.addEventListener("emptied", _this.reset);
  68737. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  68738. _this._createInternalTexture();
  68739. }
  68740. if (settings.poster) {
  68741. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  68742. _this._poster = true;
  68743. }
  68744. return _this;
  68745. }
  68746. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  68747. get: function () {
  68748. if (!this._onUserActionRequestedObservable) {
  68749. this._onUserActionRequestedObservable = new BABYLON.Observable();
  68750. }
  68751. return this._onUserActionRequestedObservable;
  68752. },
  68753. enumerable: true,
  68754. configurable: true
  68755. });
  68756. VideoTexture.prototype._getName = function (src) {
  68757. if (src instanceof HTMLVideoElement) {
  68758. return src.currentSrc;
  68759. }
  68760. if (typeof src === "object") {
  68761. return src.toString();
  68762. }
  68763. return src;
  68764. };
  68765. ;
  68766. VideoTexture.prototype._getVideo = function (src) {
  68767. if (src instanceof HTMLVideoElement) {
  68768. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  68769. return src;
  68770. }
  68771. var video = document.createElement("video");
  68772. if (typeof src === "string") {
  68773. BABYLON.Tools.SetCorsBehavior(src, video);
  68774. video.src = src;
  68775. }
  68776. else {
  68777. BABYLON.Tools.SetCorsBehavior(src[0], video);
  68778. src.forEach(function (url) {
  68779. var source = document.createElement("source");
  68780. source.src = url;
  68781. video.appendChild(source);
  68782. });
  68783. }
  68784. return video;
  68785. };
  68786. ;
  68787. /**
  68788. * @hidden Internal method to initiate `update`.
  68789. */
  68790. VideoTexture.prototype._rebuild = function () {
  68791. this.update();
  68792. };
  68793. /**
  68794. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  68795. */
  68796. VideoTexture.prototype.update = function () {
  68797. if (!this.autoUpdateTexture) {
  68798. // Expecting user to call `updateTexture` manually
  68799. return;
  68800. }
  68801. this.updateTexture(true);
  68802. };
  68803. /**
  68804. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  68805. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  68806. */
  68807. VideoTexture.prototype.updateTexture = function (isVisible) {
  68808. if (!isVisible) {
  68809. return;
  68810. }
  68811. if (this.video.paused && this._stillImageCaptured) {
  68812. return;
  68813. }
  68814. this._stillImageCaptured = true;
  68815. this._updateInternalTexture();
  68816. };
  68817. /**
  68818. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  68819. * @param url New url.
  68820. */
  68821. VideoTexture.prototype.updateURL = function (url) {
  68822. this.video.src = url;
  68823. };
  68824. VideoTexture.prototype.dispose = function () {
  68825. _super.prototype.dispose.call(this);
  68826. if (this._onUserActionRequestedObservable) {
  68827. this._onUserActionRequestedObservable.clear();
  68828. this._onUserActionRequestedObservable = null;
  68829. }
  68830. this.video.removeEventListener("canplay", this._createInternalTexture);
  68831. this.video.removeEventListener("paused", this._updateInternalTexture);
  68832. this.video.removeEventListener("seeked", this._updateInternalTexture);
  68833. this.video.removeEventListener("emptied", this.reset);
  68834. this.video.pause();
  68835. };
  68836. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  68837. var video = document.createElement("video");
  68838. video.setAttribute('autoplay', '');
  68839. video.setAttribute('muted', '');
  68840. video.setAttribute('playsinline', '');
  68841. var constraintsDeviceId;
  68842. if (constraints && constraints.deviceId) {
  68843. constraintsDeviceId = {
  68844. exact: constraints.deviceId,
  68845. };
  68846. }
  68847. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  68848. if (navigator.mediaDevices) {
  68849. navigator.mediaDevices.getUserMedia({ video: constraints })
  68850. .then(function (stream) {
  68851. if (video.mozSrcObject !== undefined) {
  68852. // hack for Firefox < 19
  68853. video.mozSrcObject = stream;
  68854. }
  68855. else {
  68856. video.srcObject = stream;
  68857. }
  68858. var onPlaying = function () {
  68859. if (onReady) {
  68860. onReady(new VideoTexture("video", video, scene, true, true));
  68861. }
  68862. video.removeEventListener("playing", onPlaying);
  68863. };
  68864. video.addEventListener("playing", onPlaying);
  68865. video.play();
  68866. })
  68867. .catch(function (err) {
  68868. BABYLON.Tools.Error(err.name);
  68869. });
  68870. }
  68871. else {
  68872. navigator.getUserMedia =
  68873. navigator.getUserMedia ||
  68874. navigator.webkitGetUserMedia ||
  68875. navigator.mozGetUserMedia ||
  68876. navigator.msGetUserMedia;
  68877. if (navigator.getUserMedia) {
  68878. navigator.getUserMedia({
  68879. video: {
  68880. deviceId: constraintsDeviceId,
  68881. width: {
  68882. min: (constraints && constraints.minWidth) || 256,
  68883. max: (constraints && constraints.maxWidth) || 640,
  68884. },
  68885. height: {
  68886. min: (constraints && constraints.minHeight) || 256,
  68887. max: (constraints && constraints.maxHeight) || 480,
  68888. },
  68889. },
  68890. }, function (stream) {
  68891. if (video.mozSrcObject !== undefined) {
  68892. // hack for Firefox < 19
  68893. video.mozSrcObject = stream;
  68894. }
  68895. else {
  68896. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  68897. }
  68898. video.play();
  68899. if (onReady) {
  68900. onReady(new VideoTexture("video", video, scene, true, true));
  68901. }
  68902. }, function (e) {
  68903. BABYLON.Tools.Error(e.name);
  68904. });
  68905. }
  68906. }
  68907. };
  68908. return VideoTexture;
  68909. }(BABYLON.Texture));
  68910. BABYLON.VideoTexture = VideoTexture;
  68911. })(BABYLON || (BABYLON = {}));
  68912. //# sourceMappingURL=babylon.videoTexture.js.map
  68913. var BABYLON;
  68914. (function (BABYLON) {
  68915. var RawTexture = /** @class */ (function (_super) {
  68916. __extends(RawTexture, _super);
  68917. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  68918. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68919. if (invertY === void 0) { invertY = false; }
  68920. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68921. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68922. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68923. _this.format = format;
  68924. _this._engine = scene.getEngine();
  68925. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  68926. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68927. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68928. return _this;
  68929. }
  68930. RawTexture.prototype.update = function (data) {
  68931. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68932. };
  68933. // Statics
  68934. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68935. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68936. if (invertY === void 0) { invertY = false; }
  68937. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68938. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  68939. };
  68940. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68941. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68942. if (invertY === void 0) { invertY = false; }
  68943. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68944. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68945. };
  68946. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68947. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68948. if (invertY === void 0) { invertY = false; }
  68949. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68950. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68951. };
  68952. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68953. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68954. if (invertY === void 0) { invertY = false; }
  68955. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68956. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68957. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  68958. };
  68959. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68960. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68961. if (invertY === void 0) { invertY = false; }
  68962. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68963. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68964. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  68965. };
  68966. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68967. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68968. if (invertY === void 0) { invertY = false; }
  68969. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68970. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68971. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  68972. };
  68973. return RawTexture;
  68974. }(BABYLON.Texture));
  68975. BABYLON.RawTexture = RawTexture;
  68976. })(BABYLON || (BABYLON = {}));
  68977. //# sourceMappingURL=babylon.rawTexture.js.map
  68978. var BABYLON;
  68979. (function (BABYLON) {
  68980. /**
  68981. * Class used to store 3D textures containing user data
  68982. */
  68983. var RawTexture3D = /** @class */ (function (_super) {
  68984. __extends(RawTexture3D, _super);
  68985. /**
  68986. * Create a new RawTexture3D
  68987. * @param data defines the data of the texture
  68988. * @param width defines the width of the texture
  68989. * @param height defines the height of the texture
  68990. * @param depth defines the depth of the texture
  68991. * @param format defines the texture format to use
  68992. * @param scene defines the hosting scene
  68993. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  68994. * @param invertY defines if texture must be stored with Y axis inverted
  68995. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  68996. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  68997. */
  68998. function RawTexture3D(data, width, height, depth,
  68999. /** Gets or sets the texture format to use */
  69000. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  69001. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69002. if (invertY === void 0) { invertY = false; }
  69003. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69004. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69005. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  69006. _this.format = format;
  69007. _this._engine = scene.getEngine();
  69008. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  69009. _this.is3D = true;
  69010. return _this;
  69011. }
  69012. /**
  69013. * Update the texture with new data
  69014. * @param data defines the data to store in the texture
  69015. */
  69016. RawTexture3D.prototype.update = function (data) {
  69017. if (!this._texture) {
  69018. return;
  69019. }
  69020. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  69021. };
  69022. return RawTexture3D;
  69023. }(BABYLON.Texture));
  69024. BABYLON.RawTexture3D = RawTexture3D;
  69025. })(BABYLON || (BABYLON = {}));
  69026. //# sourceMappingURL=babylon.rawTexture3D.js.map
  69027. var BABYLON;
  69028. (function (BABYLON) {
  69029. /**
  69030. * PostProcessManager is used to manage one or more post processes or post process pipelines
  69031. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  69032. */
  69033. var PostProcessManager = /** @class */ (function () {
  69034. /**
  69035. * Creates a new instance PostProcess
  69036. * @param scene The scene that the post process is associated with.
  69037. */
  69038. function PostProcessManager(scene) {
  69039. this._vertexBuffers = {};
  69040. this._scene = scene;
  69041. }
  69042. PostProcessManager.prototype._prepareBuffers = function () {
  69043. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  69044. return;
  69045. }
  69046. // VBO
  69047. var vertices = [];
  69048. vertices.push(1, 1);
  69049. vertices.push(-1, 1);
  69050. vertices.push(-1, -1);
  69051. vertices.push(1, -1);
  69052. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69053. this._buildIndexBuffer();
  69054. };
  69055. PostProcessManager.prototype._buildIndexBuffer = function () {
  69056. // Indices
  69057. var indices = [];
  69058. indices.push(0);
  69059. indices.push(1);
  69060. indices.push(2);
  69061. indices.push(0);
  69062. indices.push(2);
  69063. indices.push(3);
  69064. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  69065. };
  69066. /**
  69067. * Rebuilds the vertex buffers of the manager.
  69068. * @hidden
  69069. */
  69070. PostProcessManager.prototype._rebuild = function () {
  69071. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69072. if (!vb) {
  69073. return;
  69074. }
  69075. vb._rebuild();
  69076. this._buildIndexBuffer();
  69077. };
  69078. // Methods
  69079. /**
  69080. * Prepares a frame to be run through a post process.
  69081. * @param sourceTexture The input texture to the post procesess. (default: null)
  69082. * @param postProcesses An array of post processes to be run. (default: null)
  69083. * @returns True if the post processes were able to be run.
  69084. * @hidden
  69085. */
  69086. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  69087. if (sourceTexture === void 0) { sourceTexture = null; }
  69088. if (postProcesses === void 0) { postProcesses = null; }
  69089. var camera = this._scene.activeCamera;
  69090. if (!camera) {
  69091. return false;
  69092. }
  69093. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69094. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69095. return false;
  69096. }
  69097. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  69098. return true;
  69099. };
  69100. /**
  69101. * Manually render a set of post processes to a texture.
  69102. * @param postProcesses An array of post processes to be run.
  69103. * @param targetTexture The target texture to render to.
  69104. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  69105. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  69106. * @param lodLevel defines which lod of the texture to render to
  69107. */
  69108. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  69109. if (targetTexture === void 0) { targetTexture = null; }
  69110. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69111. if (faceIndex === void 0) { faceIndex = 0; }
  69112. if (lodLevel === void 0) { lodLevel = 0; }
  69113. var engine = this._scene.getEngine();
  69114. for (var index = 0; index < postProcesses.length; index++) {
  69115. if (index < postProcesses.length - 1) {
  69116. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  69117. }
  69118. else {
  69119. if (targetTexture) {
  69120. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  69121. }
  69122. else {
  69123. engine.restoreDefaultFramebuffer();
  69124. }
  69125. }
  69126. var pp = postProcesses[index];
  69127. var effect = pp.apply();
  69128. if (effect) {
  69129. pp.onBeforeRenderObservable.notifyObservers(effect);
  69130. // VBOs
  69131. this._prepareBuffers();
  69132. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69133. // Draw order
  69134. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69135. pp.onAfterRenderObservable.notifyObservers(effect);
  69136. }
  69137. }
  69138. // Restore depth buffer
  69139. engine.setDepthBuffer(true);
  69140. engine.setDepthWrite(true);
  69141. };
  69142. /**
  69143. * Finalize the result of the output of the postprocesses.
  69144. * @param doNotPresent If true the result will not be displayed to the screen.
  69145. * @param targetTexture The target texture to render to.
  69146. * @param faceIndex The index of the face to bind the target texture to.
  69147. * @param postProcesses The array of post processes to render.
  69148. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  69149. * @hidden
  69150. */
  69151. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  69152. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69153. var camera = this._scene.activeCamera;
  69154. if (!camera) {
  69155. return;
  69156. }
  69157. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69158. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69159. return;
  69160. }
  69161. var engine = this._scene.getEngine();
  69162. for (var index = 0, len = postProcesses.length; index < len; index++) {
  69163. var pp = postProcesses[index];
  69164. if (index < len - 1) {
  69165. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  69166. }
  69167. else {
  69168. if (targetTexture) {
  69169. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  69170. pp._outputTexture = targetTexture;
  69171. }
  69172. else {
  69173. engine.restoreDefaultFramebuffer();
  69174. pp._outputTexture = null;
  69175. }
  69176. }
  69177. if (doNotPresent) {
  69178. break;
  69179. }
  69180. var effect = pp.apply();
  69181. if (effect) {
  69182. pp.onBeforeRenderObservable.notifyObservers(effect);
  69183. // VBOs
  69184. this._prepareBuffers();
  69185. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69186. // Draw order
  69187. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69188. pp.onAfterRenderObservable.notifyObservers(effect);
  69189. }
  69190. }
  69191. // Restore states
  69192. engine.setDepthBuffer(true);
  69193. engine.setDepthWrite(true);
  69194. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69195. };
  69196. /**
  69197. * Disposes of the post process manager.
  69198. */
  69199. PostProcessManager.prototype.dispose = function () {
  69200. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69201. if (buffer) {
  69202. buffer.dispose();
  69203. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69204. }
  69205. if (this._indexBuffer) {
  69206. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69207. this._indexBuffer = null;
  69208. }
  69209. };
  69210. return PostProcessManager;
  69211. }());
  69212. BABYLON.PostProcessManager = PostProcessManager;
  69213. })(BABYLON || (BABYLON = {}));
  69214. //# sourceMappingURL=babylon.postProcessManager.js.map
  69215. var BABYLON;
  69216. (function (BABYLON) {
  69217. /**
  69218. * PostProcess can be used to apply a shader to a texture after it has been rendered
  69219. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  69220. */
  69221. var PostProcess = /** @class */ (function () {
  69222. /**
  69223. * Creates a new instance PostProcess
  69224. * @param name The name of the PostProcess.
  69225. * @param fragmentUrl The url of the fragment shader to be used.
  69226. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  69227. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  69228. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69229. * @param camera The camera to apply the render pass to.
  69230. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69231. * @param engine The engine which the post process will be applied. (default: current engine)
  69232. * @param reusable If the post process can be reused on the same frame. (default: false)
  69233. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  69234. * @param textureType Type of textures used when performing the post process. (default: 0)
  69235. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  69236. * @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
  69237. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  69238. */
  69239. function PostProcess(
  69240. /** Name of the PostProcess. */
  69241. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  69242. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  69243. if (defines === void 0) { defines = null; }
  69244. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69245. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  69246. if (blockCompilation === void 0) { blockCompilation = false; }
  69247. this.name = name;
  69248. /**
  69249. * Width of the texture to apply the post process on
  69250. */
  69251. this.width = -1;
  69252. /**
  69253. * Height of the texture to apply the post process on
  69254. */
  69255. this.height = -1;
  69256. /**
  69257. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  69258. * @hidden
  69259. */
  69260. this._outputTexture = null;
  69261. /**
  69262. * If the buffer needs to be cleared before applying the post process. (default: true)
  69263. * Should be set to false if shader will overwrite all previous pixels.
  69264. */
  69265. this.autoClear = true;
  69266. /**
  69267. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  69268. */
  69269. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  69270. /**
  69271. * Animations to be used for the post processing
  69272. */
  69273. this.animations = new Array();
  69274. /**
  69275. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  69276. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  69277. */
  69278. this.enablePixelPerfectMode = false;
  69279. /**
  69280. * Force the postprocess to be applied without taking in account viewport
  69281. */
  69282. this.forceFullscreenViewport = true;
  69283. /**
  69284. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  69285. *
  69286. * | Value | Type | Description |
  69287. * | ----- | ----------------------------------- | ----------- |
  69288. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  69289. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  69290. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  69291. *
  69292. */
  69293. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  69294. /**
  69295. * Force textures to be a power of two (default: false)
  69296. */
  69297. this.alwaysForcePOT = false;
  69298. this._samples = 1;
  69299. /**
  69300. * Modify the scale of the post process to be the same as the viewport (default: false)
  69301. */
  69302. this.adaptScaleToCurrentViewport = false;
  69303. this._reusable = false;
  69304. /**
  69305. * Smart array of input and output textures for the post process.
  69306. * @hidden
  69307. */
  69308. this._textures = new BABYLON.SmartArray(2);
  69309. /**
  69310. * The index in _textures that corresponds to the output texture.
  69311. * @hidden
  69312. */
  69313. this._currentRenderTextureInd = 0;
  69314. this._scaleRatio = new BABYLON.Vector2(1, 1);
  69315. this._texelSize = BABYLON.Vector2.Zero();
  69316. // Events
  69317. /**
  69318. * An event triggered when the postprocess is activated.
  69319. */
  69320. this.onActivateObservable = new BABYLON.Observable();
  69321. /**
  69322. * An event triggered when the postprocess changes its size.
  69323. */
  69324. this.onSizeChangedObservable = new BABYLON.Observable();
  69325. /**
  69326. * An event triggered when the postprocess applies its effect.
  69327. */
  69328. this.onApplyObservable = new BABYLON.Observable();
  69329. /**
  69330. * An event triggered before rendering the postprocess
  69331. */
  69332. this.onBeforeRenderObservable = new BABYLON.Observable();
  69333. /**
  69334. * An event triggered after rendering the postprocess
  69335. */
  69336. this.onAfterRenderObservable = new BABYLON.Observable();
  69337. if (camera != null) {
  69338. this._camera = camera;
  69339. this._scene = camera.getScene();
  69340. camera.attachPostProcess(this);
  69341. this._engine = this._scene.getEngine();
  69342. this._scene.postProcesses.push(this);
  69343. }
  69344. else if (engine) {
  69345. this._engine = engine;
  69346. this._engine.postProcesses.push(this);
  69347. }
  69348. this._options = options;
  69349. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  69350. this._reusable = reusable || false;
  69351. this._textureType = textureType;
  69352. this._samplers = samplers || [];
  69353. this._samplers.push("textureSampler");
  69354. this._fragmentUrl = fragmentUrl;
  69355. this._vertexUrl = vertexUrl;
  69356. this._parameters = parameters || [];
  69357. this._parameters.push("scale");
  69358. this._indexParameters = indexParameters;
  69359. if (!blockCompilation) {
  69360. this.updateEffect(defines);
  69361. }
  69362. }
  69363. Object.defineProperty(PostProcess.prototype, "samples", {
  69364. /**
  69365. * Number of sample textures (default: 1)
  69366. */
  69367. get: function () {
  69368. return this._samples;
  69369. },
  69370. set: function (n) {
  69371. var _this = this;
  69372. this._samples = n;
  69373. this._textures.forEach(function (texture) {
  69374. if (texture.samples !== _this._samples) {
  69375. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  69376. }
  69377. });
  69378. },
  69379. enumerable: true,
  69380. configurable: true
  69381. });
  69382. Object.defineProperty(PostProcess.prototype, "onActivate", {
  69383. /**
  69384. * A function that is added to the onActivateObservable
  69385. */
  69386. set: function (callback) {
  69387. if (this._onActivateObserver) {
  69388. this.onActivateObservable.remove(this._onActivateObserver);
  69389. }
  69390. if (callback) {
  69391. this._onActivateObserver = this.onActivateObservable.add(callback);
  69392. }
  69393. },
  69394. enumerable: true,
  69395. configurable: true
  69396. });
  69397. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  69398. /**
  69399. * A function that is added to the onSizeChangedObservable
  69400. */
  69401. set: function (callback) {
  69402. if (this._onSizeChangedObserver) {
  69403. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  69404. }
  69405. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  69406. },
  69407. enumerable: true,
  69408. configurable: true
  69409. });
  69410. Object.defineProperty(PostProcess.prototype, "onApply", {
  69411. /**
  69412. * A function that is added to the onApplyObservable
  69413. */
  69414. set: function (callback) {
  69415. if (this._onApplyObserver) {
  69416. this.onApplyObservable.remove(this._onApplyObserver);
  69417. }
  69418. this._onApplyObserver = this.onApplyObservable.add(callback);
  69419. },
  69420. enumerable: true,
  69421. configurable: true
  69422. });
  69423. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  69424. /**
  69425. * A function that is added to the onBeforeRenderObservable
  69426. */
  69427. set: function (callback) {
  69428. if (this._onBeforeRenderObserver) {
  69429. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69430. }
  69431. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69432. },
  69433. enumerable: true,
  69434. configurable: true
  69435. });
  69436. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  69437. /**
  69438. * A function that is added to the onAfterRenderObservable
  69439. */
  69440. set: function (callback) {
  69441. if (this._onAfterRenderObserver) {
  69442. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69443. }
  69444. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69445. },
  69446. enumerable: true,
  69447. configurable: true
  69448. });
  69449. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  69450. /**
  69451. * 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
  69452. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  69453. */
  69454. get: function () {
  69455. return this._textures.data[this._currentRenderTextureInd];
  69456. },
  69457. set: function (value) {
  69458. this._forcedOutputTexture = value;
  69459. },
  69460. enumerable: true,
  69461. configurable: true
  69462. });
  69463. /**
  69464. * Gets the camera which post process is applied to.
  69465. * @returns The camera the post process is applied to.
  69466. */
  69467. PostProcess.prototype.getCamera = function () {
  69468. return this._camera;
  69469. };
  69470. Object.defineProperty(PostProcess.prototype, "texelSize", {
  69471. /**
  69472. * Gets the texel size of the postprocess.
  69473. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  69474. */
  69475. get: function () {
  69476. if (this._shareOutputWithPostProcess) {
  69477. return this._shareOutputWithPostProcess.texelSize;
  69478. }
  69479. if (this._forcedOutputTexture) {
  69480. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  69481. }
  69482. return this._texelSize;
  69483. },
  69484. enumerable: true,
  69485. configurable: true
  69486. });
  69487. /**
  69488. * Gets the engine which this post process belongs to.
  69489. * @returns The engine the post process was enabled with.
  69490. */
  69491. PostProcess.prototype.getEngine = function () {
  69492. return this._engine;
  69493. };
  69494. /**
  69495. * The effect that is created when initializing the post process.
  69496. * @returns The created effect corrisponding the the postprocess.
  69497. */
  69498. PostProcess.prototype.getEffect = function () {
  69499. return this._effect;
  69500. };
  69501. /**
  69502. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  69503. * @param postProcess The post process to share the output with.
  69504. * @returns This post process.
  69505. */
  69506. PostProcess.prototype.shareOutputWith = function (postProcess) {
  69507. this._disposeTextures();
  69508. this._shareOutputWithPostProcess = postProcess;
  69509. return this;
  69510. };
  69511. /**
  69512. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  69513. * This should be called if the post process that shares output with this post process is disabled/disposed.
  69514. */
  69515. PostProcess.prototype.useOwnOutput = function () {
  69516. if (this._textures.length == 0) {
  69517. this._textures = new BABYLON.SmartArray(2);
  69518. }
  69519. this._shareOutputWithPostProcess = null;
  69520. };
  69521. /**
  69522. * Updates the effect with the current post process compile time values and recompiles the shader.
  69523. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69524. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69525. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69526. * @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
  69527. * @param onCompiled Called when the shader has been compiled.
  69528. * @param onError Called if there is an error when compiling a shader.
  69529. */
  69530. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69531. if (defines === void 0) { defines = null; }
  69532. if (uniforms === void 0) { uniforms = null; }
  69533. if (samplers === void 0) { samplers = null; }
  69534. 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);
  69535. };
  69536. /**
  69537. * The post process is reusable if it can be used multiple times within one frame.
  69538. * @returns If the post process is reusable
  69539. */
  69540. PostProcess.prototype.isReusable = function () {
  69541. return this._reusable;
  69542. };
  69543. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  69544. PostProcess.prototype.markTextureDirty = function () {
  69545. this.width = -1;
  69546. };
  69547. /**
  69548. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  69549. * 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.
  69550. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  69551. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  69552. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  69553. * @returns The target texture that was bound to be written to.
  69554. */
  69555. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  69556. var _this = this;
  69557. if (sourceTexture === void 0) { sourceTexture = null; }
  69558. camera = camera || this._camera;
  69559. var scene = camera.getScene();
  69560. var engine = scene.getEngine();
  69561. var maxSize = engine.getCaps().maxTextureSize;
  69562. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  69563. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  69564. // 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
  69565. var webVRCamera = camera.parent;
  69566. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  69567. requiredWidth /= 2;
  69568. }
  69569. var desiredWidth = (this._options.width || requiredWidth);
  69570. var desiredHeight = this._options.height || requiredHeight;
  69571. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  69572. if (this.adaptScaleToCurrentViewport) {
  69573. var currentViewport = engine.currentViewport;
  69574. if (currentViewport) {
  69575. desiredWidth *= currentViewport.width;
  69576. desiredHeight *= currentViewport.height;
  69577. }
  69578. }
  69579. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  69580. if (!this._options.width) {
  69581. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  69582. }
  69583. if (!this._options.height) {
  69584. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  69585. }
  69586. }
  69587. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  69588. if (this._textures.length > 0) {
  69589. for (var i = 0; i < this._textures.length; i++) {
  69590. this._engine._releaseTexture(this._textures.data[i]);
  69591. }
  69592. this._textures.reset();
  69593. }
  69594. this.width = desiredWidth;
  69595. this.height = desiredHeight;
  69596. var textureSize = { width: this.width, height: this.height };
  69597. var textureOptions = {
  69598. generateMipMaps: false,
  69599. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  69600. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  69601. samplingMode: this.renderTargetSamplingMode,
  69602. type: this._textureType
  69603. };
  69604. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69605. if (this._reusable) {
  69606. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69607. }
  69608. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  69609. this.onSizeChangedObservable.notifyObservers(this);
  69610. }
  69611. this._textures.forEach(function (texture) {
  69612. if (texture.samples !== _this.samples) {
  69613. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  69614. }
  69615. });
  69616. }
  69617. var target;
  69618. if (this._shareOutputWithPostProcess) {
  69619. target = this._shareOutputWithPostProcess.inputTexture;
  69620. }
  69621. else if (this._forcedOutputTexture) {
  69622. target = this._forcedOutputTexture;
  69623. this.width = this._forcedOutputTexture.width;
  69624. this.height = this._forcedOutputTexture.height;
  69625. }
  69626. else {
  69627. target = this.inputTexture;
  69628. }
  69629. // Bind the input of this post process to be used as the output of the previous post process.
  69630. if (this.enablePixelPerfectMode) {
  69631. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  69632. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  69633. }
  69634. else {
  69635. this._scaleRatio.copyFromFloats(1, 1);
  69636. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  69637. }
  69638. this.onActivateObservable.notifyObservers(camera);
  69639. // Clear
  69640. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  69641. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  69642. }
  69643. if (this._reusable) {
  69644. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  69645. }
  69646. return target;
  69647. };
  69648. Object.defineProperty(PostProcess.prototype, "isSupported", {
  69649. /**
  69650. * If the post process is supported.
  69651. */
  69652. get: function () {
  69653. return this._effect.isSupported;
  69654. },
  69655. enumerable: true,
  69656. configurable: true
  69657. });
  69658. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  69659. /**
  69660. * The aspect ratio of the output texture.
  69661. */
  69662. get: function () {
  69663. if (this._shareOutputWithPostProcess) {
  69664. return this._shareOutputWithPostProcess.aspectRatio;
  69665. }
  69666. if (this._forcedOutputTexture) {
  69667. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  69668. }
  69669. return this.width / this.height;
  69670. },
  69671. enumerable: true,
  69672. configurable: true
  69673. });
  69674. /**
  69675. * Get a value indicating if the post-process is ready to be used
  69676. * @returns true if the post-process is ready (shader is compiled)
  69677. */
  69678. PostProcess.prototype.isReady = function () {
  69679. return this._effect && this._effect.isReady();
  69680. };
  69681. /**
  69682. * Binds all textures and uniforms to the shader, this will be run on every pass.
  69683. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  69684. */
  69685. PostProcess.prototype.apply = function () {
  69686. // Check
  69687. if (!this._effect || !this._effect.isReady())
  69688. return null;
  69689. // States
  69690. this._engine.enableEffect(this._effect);
  69691. this._engine.setState(false);
  69692. this._engine.setDepthBuffer(false);
  69693. this._engine.setDepthWrite(false);
  69694. // Alpha
  69695. this._engine.setAlphaMode(this.alphaMode);
  69696. if (this.alphaConstants) {
  69697. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  69698. }
  69699. // Bind the output texture of the preivous post process as the input to this post process.
  69700. var source;
  69701. if (this._shareOutputWithPostProcess) {
  69702. source = this._shareOutputWithPostProcess.inputTexture;
  69703. }
  69704. else if (this._forcedOutputTexture) {
  69705. source = this._forcedOutputTexture;
  69706. }
  69707. else {
  69708. source = this.inputTexture;
  69709. }
  69710. this._effect._bindTexture("textureSampler", source);
  69711. // Parameters
  69712. this._effect.setVector2("scale", this._scaleRatio);
  69713. this.onApplyObservable.notifyObservers(this._effect);
  69714. return this._effect;
  69715. };
  69716. PostProcess.prototype._disposeTextures = function () {
  69717. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  69718. return;
  69719. }
  69720. if (this._textures.length > 0) {
  69721. for (var i = 0; i < this._textures.length; i++) {
  69722. this._engine._releaseTexture(this._textures.data[i]);
  69723. }
  69724. }
  69725. this._textures.dispose();
  69726. };
  69727. /**
  69728. * Disposes the post process.
  69729. * @param camera The camera to dispose the post process on.
  69730. */
  69731. PostProcess.prototype.dispose = function (camera) {
  69732. camera = camera || this._camera;
  69733. this._disposeTextures();
  69734. if (this._scene) {
  69735. var index_1 = this._scene.postProcesses.indexOf(this);
  69736. if (index_1 !== -1) {
  69737. this._scene.postProcesses.splice(index_1, 1);
  69738. }
  69739. }
  69740. else {
  69741. var index_2 = this._engine.postProcesses.indexOf(this);
  69742. if (index_2 !== -1) {
  69743. this._engine.postProcesses.splice(index_2, 1);
  69744. }
  69745. }
  69746. if (!camera) {
  69747. return;
  69748. }
  69749. camera.detachPostProcess(this);
  69750. var index = camera._postProcesses.indexOf(this);
  69751. if (index === 0 && camera._postProcesses.length > 0) {
  69752. var firstPostProcess = this._camera._getFirstPostProcess();
  69753. if (firstPostProcess) {
  69754. firstPostProcess.markTextureDirty();
  69755. }
  69756. }
  69757. this.onActivateObservable.clear();
  69758. this.onAfterRenderObservable.clear();
  69759. this.onApplyObservable.clear();
  69760. this.onBeforeRenderObservable.clear();
  69761. this.onSizeChangedObservable.clear();
  69762. };
  69763. return PostProcess;
  69764. }());
  69765. BABYLON.PostProcess = PostProcess;
  69766. })(BABYLON || (BABYLON = {}));
  69767. //# sourceMappingURL=babylon.postProcess.js.map
  69768. var BABYLON;
  69769. (function (BABYLON) {
  69770. var PassPostProcess = /** @class */ (function (_super) {
  69771. __extends(PassPostProcess, _super);
  69772. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69773. if (camera === void 0) { camera = null; }
  69774. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69775. if (blockCompilation === void 0) { blockCompilation = false; }
  69776. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  69777. }
  69778. return PassPostProcess;
  69779. }(BABYLON.PostProcess));
  69780. BABYLON.PassPostProcess = PassPostProcess;
  69781. })(BABYLON || (BABYLON = {}));
  69782. //# sourceMappingURL=babylon.passPostProcess.js.map
  69783. var __assign = (this && this.__assign) || function () {
  69784. __assign = Object.assign || function(t) {
  69785. for (var s, i = 1, n = arguments.length; i < n; i++) {
  69786. s = arguments[i];
  69787. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  69788. t[p] = s[p];
  69789. }
  69790. return t;
  69791. };
  69792. return __assign.apply(this, arguments);
  69793. };
  69794. var BABYLON;
  69795. (function (BABYLON) {
  69796. /**
  69797. * Default implementation IShadowGenerator.
  69798. * This is the main object responsible of generating shadows in the framework.
  69799. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  69800. */
  69801. var ShadowGenerator = /** @class */ (function () {
  69802. /**
  69803. * Creates a ShadowGenerator object.
  69804. * A ShadowGenerator is the required tool to use the shadows.
  69805. * Each light casting shadows needs to use its own ShadowGenerator.
  69806. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  69807. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  69808. * @param light The light object generating the shadows.
  69809. * @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.
  69810. */
  69811. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  69812. this._bias = 0.00005;
  69813. this._normalBias = 0;
  69814. this._blurBoxOffset = 1;
  69815. this._blurScale = 2;
  69816. this._blurKernel = 1;
  69817. this._useKernelBlur = false;
  69818. this._filter = ShadowGenerator.FILTER_NONE;
  69819. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  69820. this._contactHardeningLightSizeUVRatio = 0.1;
  69821. this._darkness = 0;
  69822. this._transparencyShadow = false;
  69823. /**
  69824. * Controls the extent to which the shadows fade out at the edge of the frustum
  69825. * Used only by directionals and spots
  69826. */
  69827. this.frustumEdgeFalloff = 0;
  69828. /**
  69829. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  69830. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  69831. * It might on the other hand introduce peter panning.
  69832. */
  69833. this.forceBackFacesOnly = false;
  69834. this._lightDirection = BABYLON.Vector3.Zero();
  69835. this._viewMatrix = BABYLON.Matrix.Zero();
  69836. this._projectionMatrix = BABYLON.Matrix.Zero();
  69837. this._transformMatrix = BABYLON.Matrix.Zero();
  69838. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69839. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69840. this._currentFaceIndex = 0;
  69841. this._currentFaceIndexCache = 0;
  69842. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  69843. this._mapSize = mapSize;
  69844. this._light = light;
  69845. this._scene = light.getScene();
  69846. light._shadowGenerator = this;
  69847. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  69848. if (!component) {
  69849. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  69850. this._scene._addComponent(component);
  69851. }
  69852. // Texture type fallback from float to int if not supported.
  69853. var caps = this._scene.getEngine().getCaps();
  69854. if (!useFullFloatFirst) {
  69855. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  69856. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69857. }
  69858. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  69859. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69860. }
  69861. else {
  69862. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69863. }
  69864. }
  69865. else {
  69866. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  69867. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69868. }
  69869. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  69870. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69871. }
  69872. else {
  69873. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69874. }
  69875. }
  69876. this._initializeGenerator();
  69877. this._applyFilterValues();
  69878. }
  69879. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  69880. /**
  69881. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  69882. */
  69883. get: function () {
  69884. return this._bias;
  69885. },
  69886. /**
  69887. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  69888. */
  69889. set: function (bias) {
  69890. this._bias = bias;
  69891. },
  69892. enumerable: true,
  69893. configurable: true
  69894. });
  69895. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  69896. /**
  69897. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  69898. */
  69899. get: function () {
  69900. return this._normalBias;
  69901. },
  69902. /**
  69903. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  69904. */
  69905. set: function (normalBias) {
  69906. this._normalBias = normalBias;
  69907. },
  69908. enumerable: true,
  69909. configurable: true
  69910. });
  69911. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  69912. /**
  69913. * Gets the blur box offset: offset applied during the blur pass.
  69914. * Only usefull if useKernelBlur = false
  69915. */
  69916. get: function () {
  69917. return this._blurBoxOffset;
  69918. },
  69919. /**
  69920. * Sets the blur box offset: offset applied during the blur pass.
  69921. * Only usefull if useKernelBlur = false
  69922. */
  69923. set: function (value) {
  69924. if (this._blurBoxOffset === value) {
  69925. return;
  69926. }
  69927. this._blurBoxOffset = value;
  69928. this._disposeBlurPostProcesses();
  69929. },
  69930. enumerable: true,
  69931. configurable: true
  69932. });
  69933. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  69934. /**
  69935. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  69936. * 2 means half of the size.
  69937. */
  69938. get: function () {
  69939. return this._blurScale;
  69940. },
  69941. /**
  69942. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  69943. * 2 means half of the size.
  69944. */
  69945. set: function (value) {
  69946. if (this._blurScale === value) {
  69947. return;
  69948. }
  69949. this._blurScale = value;
  69950. this._disposeBlurPostProcesses();
  69951. },
  69952. enumerable: true,
  69953. configurable: true
  69954. });
  69955. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  69956. /**
  69957. * Gets the blur kernel: kernel size of the blur pass.
  69958. * Only usefull if useKernelBlur = true
  69959. */
  69960. get: function () {
  69961. return this._blurKernel;
  69962. },
  69963. /**
  69964. * Sets the blur kernel: kernel size of the blur pass.
  69965. * Only usefull if useKernelBlur = true
  69966. */
  69967. set: function (value) {
  69968. if (this._blurKernel === value) {
  69969. return;
  69970. }
  69971. this._blurKernel = value;
  69972. this._disposeBlurPostProcesses();
  69973. },
  69974. enumerable: true,
  69975. configurable: true
  69976. });
  69977. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  69978. /**
  69979. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  69980. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69981. */
  69982. get: function () {
  69983. return this._useKernelBlur;
  69984. },
  69985. /**
  69986. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  69987. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69988. */
  69989. set: function (value) {
  69990. if (this._useKernelBlur === value) {
  69991. return;
  69992. }
  69993. this._useKernelBlur = value;
  69994. this._disposeBlurPostProcesses();
  69995. },
  69996. enumerable: true,
  69997. configurable: true
  69998. });
  69999. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  70000. /**
  70001. * Gets the depth scale used in ESM mode.
  70002. */
  70003. get: function () {
  70004. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  70005. },
  70006. /**
  70007. * Sets the depth scale used in ESM mode.
  70008. * This can override the scale stored on the light.
  70009. */
  70010. set: function (value) {
  70011. this._depthScale = value;
  70012. },
  70013. enumerable: true,
  70014. configurable: true
  70015. });
  70016. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  70017. /**
  70018. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  70019. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  70020. */
  70021. get: function () {
  70022. return this._filter;
  70023. },
  70024. /**
  70025. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  70026. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  70027. */
  70028. set: function (value) {
  70029. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  70030. if (this._light.needCube()) {
  70031. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  70032. this.useExponentialShadowMap = true;
  70033. return;
  70034. }
  70035. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70036. this.useCloseExponentialShadowMap = true;
  70037. return;
  70038. }
  70039. // PCF on cubemap would also be expensive
  70040. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  70041. this.usePoissonSampling = true;
  70042. return;
  70043. }
  70044. }
  70045. // Weblg1 fallback for PCF.
  70046. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  70047. if (this._scene.getEngine().webGLVersion === 1) {
  70048. this.usePoissonSampling = true;
  70049. return;
  70050. }
  70051. }
  70052. if (this._filter === value) {
  70053. return;
  70054. }
  70055. this._filter = value;
  70056. this._disposeBlurPostProcesses();
  70057. this._applyFilterValues();
  70058. this._light._markMeshesAsLightDirty();
  70059. },
  70060. enumerable: true,
  70061. configurable: true
  70062. });
  70063. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  70064. /**
  70065. * Gets if the current filter is set to Poisson Sampling.
  70066. */
  70067. get: function () {
  70068. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  70069. },
  70070. /**
  70071. * Sets the current filter to Poisson Sampling.
  70072. */
  70073. set: function (value) {
  70074. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  70075. return;
  70076. }
  70077. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  70078. },
  70079. enumerable: true,
  70080. configurable: true
  70081. });
  70082. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  70083. /**
  70084. * Gets if the current filter is set to VSM.
  70085. * DEPRECATED. Should use useExponentialShadowMap instead.
  70086. */
  70087. get: function () {
  70088. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70089. return this.useExponentialShadowMap;
  70090. },
  70091. /**
  70092. * Sets the current filter is to VSM.
  70093. * DEPRECATED. Should use useExponentialShadowMap instead.
  70094. */
  70095. set: function (value) {
  70096. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70097. this.useExponentialShadowMap = value;
  70098. },
  70099. enumerable: true,
  70100. configurable: true
  70101. });
  70102. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  70103. /**
  70104. * Gets if the current filter is set to blurred VSM.
  70105. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70106. */
  70107. get: function () {
  70108. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70109. return this.useBlurExponentialShadowMap;
  70110. },
  70111. /**
  70112. * Sets the current filter is to blurred VSM.
  70113. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70114. */
  70115. set: function (value) {
  70116. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70117. this.useBlurExponentialShadowMap = value;
  70118. },
  70119. enumerable: true,
  70120. configurable: true
  70121. });
  70122. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  70123. /**
  70124. * Gets if the current filter is set to ESM.
  70125. */
  70126. get: function () {
  70127. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  70128. },
  70129. /**
  70130. * Sets the current filter is to ESM.
  70131. */
  70132. set: function (value) {
  70133. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  70134. return;
  70135. }
  70136. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70137. },
  70138. enumerable: true,
  70139. configurable: true
  70140. });
  70141. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  70142. /**
  70143. * Gets if the current filter is set to filtered ESM.
  70144. */
  70145. get: function () {
  70146. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  70147. },
  70148. /**
  70149. * Gets if the current filter is set to filtered ESM.
  70150. */
  70151. set: function (value) {
  70152. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  70153. return;
  70154. }
  70155. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70156. },
  70157. enumerable: true,
  70158. configurable: true
  70159. });
  70160. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  70161. /**
  70162. * Gets if the current filter is set to "close ESM" (using the inverse of the
  70163. * exponential to prevent steep falloff artifacts).
  70164. */
  70165. get: function () {
  70166. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  70167. },
  70168. /**
  70169. * Sets the current filter to "close ESM" (using the inverse of the
  70170. * exponential to prevent steep falloff artifacts).
  70171. */
  70172. set: function (value) {
  70173. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  70174. return;
  70175. }
  70176. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70177. },
  70178. enumerable: true,
  70179. configurable: true
  70180. });
  70181. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  70182. /**
  70183. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  70184. * exponential to prevent steep falloff artifacts).
  70185. */
  70186. get: function () {
  70187. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  70188. },
  70189. /**
  70190. * Sets the current filter to filtered "close ESM" (using the inverse of the
  70191. * exponential to prevent steep falloff artifacts).
  70192. */
  70193. set: function (value) {
  70194. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70195. return;
  70196. }
  70197. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70198. },
  70199. enumerable: true,
  70200. configurable: true
  70201. });
  70202. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  70203. /**
  70204. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  70205. */
  70206. get: function () {
  70207. return this.filter === ShadowGenerator.FILTER_PCF;
  70208. },
  70209. /**
  70210. * Sets the current filter to "PCF" (percentage closer filtering).
  70211. */
  70212. set: function (value) {
  70213. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  70214. return;
  70215. }
  70216. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  70217. },
  70218. enumerable: true,
  70219. configurable: true
  70220. });
  70221. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  70222. /**
  70223. * Gets the PCF or PCSS Quality.
  70224. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70225. */
  70226. get: function () {
  70227. return this._filteringQuality;
  70228. },
  70229. /**
  70230. * Sets the PCF or PCSS Quality.
  70231. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70232. */
  70233. set: function (filteringQuality) {
  70234. this._filteringQuality = filteringQuality;
  70235. },
  70236. enumerable: true,
  70237. configurable: true
  70238. });
  70239. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  70240. /**
  70241. * Gets if the current filter is set to "PCSS" (contact hardening).
  70242. */
  70243. get: function () {
  70244. return this.filter === ShadowGenerator.FILTER_PCSS;
  70245. },
  70246. /**
  70247. * Sets the current filter to "PCSS" (contact hardening).
  70248. */
  70249. set: function (value) {
  70250. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  70251. return;
  70252. }
  70253. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  70254. },
  70255. enumerable: true,
  70256. configurable: true
  70257. });
  70258. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  70259. /**
  70260. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70261. * Using a ratio helps keeping shape stability independently of the map size.
  70262. *
  70263. * It does not account for the light projection as it was having too much
  70264. * instability during the light setup or during light position changes.
  70265. *
  70266. * Only valid if useContactHardeningShadow is true.
  70267. */
  70268. get: function () {
  70269. return this._contactHardeningLightSizeUVRatio;
  70270. },
  70271. /**
  70272. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70273. * Using a ratio helps keeping shape stability independently of the map size.
  70274. *
  70275. * It does not account for the light projection as it was having too much
  70276. * instability during the light setup or during light position changes.
  70277. *
  70278. * Only valid if useContactHardeningShadow is true.
  70279. */
  70280. set: function (contactHardeningLightSizeUVRatio) {
  70281. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  70282. },
  70283. enumerable: true,
  70284. configurable: true
  70285. });
  70286. /**
  70287. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  70288. * 0 means strongest and 1 would means no shadow.
  70289. * @returns the darkness.
  70290. */
  70291. ShadowGenerator.prototype.getDarkness = function () {
  70292. return this._darkness;
  70293. };
  70294. /**
  70295. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  70296. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  70297. * @returns the shadow generator allowing fluent coding.
  70298. */
  70299. ShadowGenerator.prototype.setDarkness = function (darkness) {
  70300. if (darkness >= 1.0)
  70301. this._darkness = 1.0;
  70302. else if (darkness <= 0.0)
  70303. this._darkness = 0.0;
  70304. else
  70305. this._darkness = darkness;
  70306. return this;
  70307. };
  70308. /**
  70309. * Sets the ability to have transparent shadow (boolean).
  70310. * @param transparent True if transparent else False
  70311. * @returns the shadow generator allowing fluent coding
  70312. */
  70313. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  70314. this._transparencyShadow = transparent;
  70315. return this;
  70316. };
  70317. /**
  70318. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  70319. * @returns The render target texture if present otherwise, null
  70320. */
  70321. ShadowGenerator.prototype.getShadowMap = function () {
  70322. return this._shadowMap;
  70323. };
  70324. /**
  70325. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  70326. * @returns The render target texture if the shadow map is present otherwise, null
  70327. */
  70328. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  70329. if (this._shadowMap2) {
  70330. return this._shadowMap2;
  70331. }
  70332. return this._shadowMap;
  70333. };
  70334. /**
  70335. * Helper function to add a mesh and its descendants to the list of shadow casters.
  70336. * @param mesh Mesh to add
  70337. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  70338. * @returns the Shadow Generator itself
  70339. */
  70340. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  70341. if (includeDescendants === void 0) { includeDescendants = true; }
  70342. var _a;
  70343. if (!this._shadowMap) {
  70344. return this;
  70345. }
  70346. if (!this._shadowMap.renderList) {
  70347. this._shadowMap.renderList = [];
  70348. }
  70349. this._shadowMap.renderList.push(mesh);
  70350. if (includeDescendants) {
  70351. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  70352. }
  70353. return this;
  70354. };
  70355. /**
  70356. * Helper function to remove a mesh and its descendants from the list of shadow casters
  70357. * @param mesh Mesh to remove
  70358. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  70359. * @returns the Shadow Generator itself
  70360. */
  70361. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  70362. if (includeDescendants === void 0) { includeDescendants = true; }
  70363. if (!this._shadowMap || !this._shadowMap.renderList) {
  70364. return this;
  70365. }
  70366. var index = this._shadowMap.renderList.indexOf(mesh);
  70367. if (index !== -1) {
  70368. this._shadowMap.renderList.splice(index, 1);
  70369. }
  70370. if (includeDescendants) {
  70371. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  70372. var child = _a[_i];
  70373. this.removeShadowCaster(child);
  70374. }
  70375. }
  70376. return this;
  70377. };
  70378. /**
  70379. * Returns the associated light object.
  70380. * @returns the light generating the shadow
  70381. */
  70382. ShadowGenerator.prototype.getLight = function () {
  70383. return this._light;
  70384. };
  70385. ShadowGenerator.prototype._initializeGenerator = function () {
  70386. this._light._markMeshesAsLightDirty();
  70387. this._initializeShadowMap();
  70388. };
  70389. ShadowGenerator.prototype._initializeShadowMap = function () {
  70390. var _this = this;
  70391. // Render target
  70392. var engine = this._scene.getEngine();
  70393. if (engine.webGLVersion > 1) {
  70394. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  70395. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  70396. }
  70397. else {
  70398. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  70399. }
  70400. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70401. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70402. this._shadowMap.anisotropicFilteringLevel = 1;
  70403. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70404. this._shadowMap.renderParticles = false;
  70405. this._shadowMap.ignoreCameraViewport = true;
  70406. // Record Face Index before render.
  70407. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  70408. _this._currentFaceIndex = faceIndex;
  70409. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70410. engine.setColorWrite(false);
  70411. }
  70412. });
  70413. // Custom render function.
  70414. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  70415. // Blur if required afer render.
  70416. this._shadowMap.onAfterUnbindObservable.add(function () {
  70417. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70418. engine.setColorWrite(true);
  70419. }
  70420. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  70421. return;
  70422. }
  70423. var shadowMap = _this.getShadowMapForRendering();
  70424. if (shadowMap) {
  70425. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  70426. }
  70427. });
  70428. // Clear according to the chosen filter.
  70429. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  70430. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  70431. this._shadowMap.onClearObservable.add(function (engine) {
  70432. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70433. engine.clear(clearOne, false, true, false);
  70434. }
  70435. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  70436. engine.clear(clearZero, true, true, false);
  70437. }
  70438. else {
  70439. engine.clear(clearOne, true, true, false);
  70440. }
  70441. });
  70442. };
  70443. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  70444. var _this = this;
  70445. var engine = this._scene.getEngine();
  70446. var targetSize = this._mapSize / this.blurScale;
  70447. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  70448. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  70449. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70450. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70451. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70452. }
  70453. if (this.useKernelBlur) {
  70454. 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);
  70455. this._kernelBlurXPostprocess.width = targetSize;
  70456. this._kernelBlurXPostprocess.height = targetSize;
  70457. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  70458. effect.setTexture("textureSampler", _this._shadowMap);
  70459. });
  70460. 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);
  70461. this._kernelBlurXPostprocess.autoClear = false;
  70462. this._kernelBlurYPostprocess.autoClear = false;
  70463. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70464. this._kernelBlurXPostprocess.packedFloat = true;
  70465. this._kernelBlurYPostprocess.packedFloat = true;
  70466. }
  70467. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  70468. }
  70469. else {
  70470. 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);
  70471. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  70472. effect.setFloat2("screenSize", targetSize, targetSize);
  70473. effect.setTexture("textureSampler", _this._shadowMap);
  70474. });
  70475. this._boxBlurPostprocess.autoClear = false;
  70476. this._blurPostProcesses = [this._boxBlurPostprocess];
  70477. }
  70478. };
  70479. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70480. var index;
  70481. var engine = this._scene.getEngine();
  70482. if (depthOnlySubMeshes.length) {
  70483. engine.setColorWrite(false);
  70484. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70485. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  70486. }
  70487. engine.setColorWrite(true);
  70488. }
  70489. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70490. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  70491. }
  70492. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70493. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  70494. }
  70495. if (this._transparencyShadow) {
  70496. for (index = 0; index < transparentSubMeshes.length; index++) {
  70497. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  70498. }
  70499. }
  70500. };
  70501. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  70502. var _this = this;
  70503. var mesh = subMesh.getRenderingMesh();
  70504. var scene = this._scene;
  70505. var engine = scene.getEngine();
  70506. var material = subMesh.getMaterial();
  70507. if (!material) {
  70508. return;
  70509. }
  70510. // Culling
  70511. engine.setState(material.backFaceCulling);
  70512. // Managing instances
  70513. var batch = mesh._getInstancesRenderList(subMesh._id);
  70514. if (batch.mustReturn) {
  70515. return;
  70516. }
  70517. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  70518. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  70519. engine.enableEffect(this._effect);
  70520. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  70521. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  70522. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  70523. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70524. this._effect.setVector3("lightData", this._cachedDirection);
  70525. }
  70526. else {
  70527. this._effect.setVector3("lightData", this._cachedPosition);
  70528. }
  70529. if (scene.activeCamera) {
  70530. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  70531. }
  70532. // Alpha test
  70533. if (material && material.needAlphaTesting()) {
  70534. var alphaTexture = material.getAlphaTestTexture();
  70535. if (alphaTexture) {
  70536. this._effect.setTexture("diffuseSampler", alphaTexture);
  70537. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  70538. }
  70539. }
  70540. // Bones
  70541. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70542. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  70543. }
  70544. // Morph targets
  70545. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  70546. if (this.forceBackFacesOnly) {
  70547. engine.setState(true, 0, false, true);
  70548. }
  70549. // Draw
  70550. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70551. if (this.forceBackFacesOnly) {
  70552. engine.setState(true, 0, false, false);
  70553. }
  70554. }
  70555. else {
  70556. // Need to reset refresh rate of the shadowMap
  70557. if (this._shadowMap) {
  70558. this._shadowMap.resetRefreshCounter();
  70559. }
  70560. }
  70561. };
  70562. ShadowGenerator.prototype._applyFilterValues = function () {
  70563. if (!this._shadowMap) {
  70564. return;
  70565. }
  70566. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  70567. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  70568. }
  70569. else {
  70570. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70571. }
  70572. };
  70573. /**
  70574. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70575. * @param onCompiled Callback triggered at the and of the effects compilation
  70576. * @param options Sets of optional options forcing the compilation with different modes
  70577. */
  70578. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  70579. var _this = this;
  70580. var localOptions = __assign({ useInstances: false }, options);
  70581. var shadowMap = this.getShadowMap();
  70582. if (!shadowMap) {
  70583. if (onCompiled) {
  70584. onCompiled(this);
  70585. }
  70586. return;
  70587. }
  70588. var renderList = shadowMap.renderList;
  70589. if (!renderList) {
  70590. if (onCompiled) {
  70591. onCompiled(this);
  70592. }
  70593. return;
  70594. }
  70595. var subMeshes = new Array();
  70596. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  70597. var mesh = renderList_1[_i];
  70598. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  70599. }
  70600. if (subMeshes.length === 0) {
  70601. if (onCompiled) {
  70602. onCompiled(this);
  70603. }
  70604. return;
  70605. }
  70606. var currentIndex = 0;
  70607. var checkReady = function () {
  70608. if (!_this._scene || !_this._scene.getEngine()) {
  70609. return;
  70610. }
  70611. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  70612. currentIndex++;
  70613. if (currentIndex >= subMeshes.length) {
  70614. if (onCompiled) {
  70615. onCompiled(_this);
  70616. }
  70617. return;
  70618. }
  70619. }
  70620. setTimeout(checkReady, 16);
  70621. };
  70622. checkReady();
  70623. };
  70624. /**
  70625. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70626. * @param options Sets of optional options forcing the compilation with different modes
  70627. * @returns A promise that resolves when the compilation completes
  70628. */
  70629. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  70630. var _this = this;
  70631. return new Promise(function (resolve) {
  70632. _this.forceCompilation(function () {
  70633. resolve();
  70634. }, options);
  70635. });
  70636. };
  70637. /**
  70638. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  70639. * @param subMesh The submesh we want to render in the shadow map
  70640. * @param useInstances Defines wether will draw in the map using instances
  70641. * @returns true if ready otherwise, false
  70642. */
  70643. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  70644. var defines = [];
  70645. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70646. defines.push("#define FLOAT");
  70647. }
  70648. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  70649. defines.push("#define ESM");
  70650. }
  70651. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  70652. defines.push("#define DEPTHTEXTURE");
  70653. }
  70654. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70655. var mesh = subMesh.getMesh();
  70656. var material = subMesh.getMaterial();
  70657. // Normal bias.
  70658. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  70659. attribs.push(BABYLON.VertexBuffer.NormalKind);
  70660. defines.push("#define NORMAL");
  70661. if (mesh.nonUniformScaling) {
  70662. defines.push("#define NONUNIFORMSCALING");
  70663. }
  70664. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70665. defines.push("#define DIRECTIONINLIGHTDATA");
  70666. }
  70667. }
  70668. // Alpha test
  70669. if (material && material.needAlphaTesting()) {
  70670. var alphaTexture = material.getAlphaTestTexture();
  70671. if (alphaTexture) {
  70672. defines.push("#define ALPHATEST");
  70673. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70674. attribs.push(BABYLON.VertexBuffer.UVKind);
  70675. defines.push("#define UV1");
  70676. }
  70677. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70678. if (alphaTexture.coordinatesIndex === 1) {
  70679. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70680. defines.push("#define UV2");
  70681. }
  70682. }
  70683. }
  70684. }
  70685. // Bones
  70686. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70687. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70688. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70689. if (mesh.numBoneInfluencers > 4) {
  70690. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70691. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70692. }
  70693. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70694. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  70695. }
  70696. else {
  70697. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70698. }
  70699. // Morph targets
  70700. var manager = mesh.morphTargetManager;
  70701. var morphInfluencers = 0;
  70702. if (manager) {
  70703. if (manager.numInfluencers > 0) {
  70704. defines.push("#define MORPHTARGETS");
  70705. morphInfluencers = manager.numInfluencers;
  70706. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  70707. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  70708. }
  70709. }
  70710. // Instances
  70711. if (useInstances) {
  70712. defines.push("#define INSTANCES");
  70713. attribs.push("world0");
  70714. attribs.push("world1");
  70715. attribs.push("world2");
  70716. attribs.push("world3");
  70717. }
  70718. // Get correct effect
  70719. var join = defines.join("\n");
  70720. if (this._cachedDefines !== join) {
  70721. this._cachedDefines = join;
  70722. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  70723. }
  70724. if (!this._effect.isReady()) {
  70725. return false;
  70726. }
  70727. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  70728. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  70729. this._initializeBlurRTTAndPostProcesses();
  70730. }
  70731. }
  70732. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  70733. return false;
  70734. }
  70735. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  70736. return false;
  70737. }
  70738. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  70739. return false;
  70740. }
  70741. return true;
  70742. };
  70743. /**
  70744. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  70745. * @param defines Defines of the material we want to update
  70746. * @param lightIndex Index of the light in the enabled light list of the material
  70747. */
  70748. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  70749. var scene = this._scene;
  70750. var light = this._light;
  70751. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  70752. return;
  70753. }
  70754. defines["SHADOW" + lightIndex] = true;
  70755. if (this.useContactHardeningShadow) {
  70756. defines["SHADOWPCSS" + lightIndex] = true;
  70757. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  70758. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  70759. }
  70760. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  70761. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  70762. }
  70763. // else default to high.
  70764. }
  70765. if (this.usePercentageCloserFiltering) {
  70766. defines["SHADOWPCF" + lightIndex] = true;
  70767. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  70768. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  70769. }
  70770. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  70771. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  70772. }
  70773. // else default to high.
  70774. }
  70775. else if (this.usePoissonSampling) {
  70776. defines["SHADOWPOISSON" + lightIndex] = true;
  70777. }
  70778. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  70779. defines["SHADOWESM" + lightIndex] = true;
  70780. }
  70781. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  70782. defines["SHADOWCLOSEESM" + lightIndex] = true;
  70783. }
  70784. if (light.needCube()) {
  70785. defines["SHADOWCUBE" + lightIndex] = true;
  70786. }
  70787. };
  70788. /**
  70789. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  70790. * defined in the generator but impacting the effect).
  70791. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  70792. * @param effect The effect we are binfing the information for
  70793. */
  70794. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  70795. var light = this._light;
  70796. var scene = this._scene;
  70797. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  70798. return;
  70799. }
  70800. var camera = scene.activeCamera;
  70801. if (!camera) {
  70802. return;
  70803. }
  70804. var shadowMap = this.getShadowMap();
  70805. if (!shadowMap) {
  70806. return;
  70807. }
  70808. if (!light.needCube()) {
  70809. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  70810. }
  70811. // Only PCF uses depth stencil texture.
  70812. if (this._filter === ShadowGenerator.FILTER_PCF) {
  70813. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70814. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  70815. }
  70816. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  70817. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70818. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  70819. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  70820. }
  70821. else {
  70822. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70823. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  70824. }
  70825. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  70826. };
  70827. /**
  70828. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  70829. * (eq to shadow prjection matrix * light transform matrix)
  70830. * @returns The transform matrix used to create the shadow map
  70831. */
  70832. ShadowGenerator.prototype.getTransformMatrix = function () {
  70833. var scene = this._scene;
  70834. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  70835. return this._transformMatrix;
  70836. }
  70837. this._currentRenderID = scene.getRenderId();
  70838. this._currentFaceIndexCache = this._currentFaceIndex;
  70839. var lightPosition = this._light.position;
  70840. if (this._light.computeTransformedInformation()) {
  70841. lightPosition = this._light.transformedPosition;
  70842. }
  70843. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  70844. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  70845. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  70846. }
  70847. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  70848. this._cachedPosition.copyFrom(lightPosition);
  70849. this._cachedDirection.copyFrom(this._lightDirection);
  70850. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  70851. var shadowMap = this.getShadowMap();
  70852. if (shadowMap) {
  70853. var renderList = shadowMap.renderList;
  70854. if (renderList) {
  70855. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  70856. }
  70857. }
  70858. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  70859. }
  70860. return this._transformMatrix;
  70861. };
  70862. /**
  70863. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  70864. * Cube and 2D textures for instance.
  70865. */
  70866. ShadowGenerator.prototype.recreateShadowMap = function () {
  70867. var shadowMap = this._shadowMap;
  70868. if (!shadowMap) {
  70869. return;
  70870. }
  70871. // Track render list.
  70872. var renderList = shadowMap.renderList;
  70873. // Clean up existing data.
  70874. this._disposeRTTandPostProcesses();
  70875. // Reinitializes.
  70876. this._initializeGenerator();
  70877. // Reaffect the filter to ensure a correct fallback if necessary.
  70878. this.filter = this.filter;
  70879. // Reaffect the filter.
  70880. this._applyFilterValues();
  70881. // Reaffect Render List.
  70882. this._shadowMap.renderList = renderList;
  70883. };
  70884. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  70885. if (this._shadowMap2) {
  70886. this._shadowMap2.dispose();
  70887. this._shadowMap2 = null;
  70888. }
  70889. if (this._boxBlurPostprocess) {
  70890. this._boxBlurPostprocess.dispose();
  70891. this._boxBlurPostprocess = null;
  70892. }
  70893. if (this._kernelBlurXPostprocess) {
  70894. this._kernelBlurXPostprocess.dispose();
  70895. this._kernelBlurXPostprocess = null;
  70896. }
  70897. if (this._kernelBlurYPostprocess) {
  70898. this._kernelBlurYPostprocess.dispose();
  70899. this._kernelBlurYPostprocess = null;
  70900. }
  70901. this._blurPostProcesses = [];
  70902. };
  70903. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  70904. if (this._shadowMap) {
  70905. this._shadowMap.dispose();
  70906. this._shadowMap = null;
  70907. }
  70908. this._disposeBlurPostProcesses();
  70909. };
  70910. /**
  70911. * Disposes the ShadowGenerator.
  70912. * Returns nothing.
  70913. */
  70914. ShadowGenerator.prototype.dispose = function () {
  70915. this._disposeRTTandPostProcesses();
  70916. if (this._light) {
  70917. this._light._shadowGenerator = null;
  70918. this._light._markMeshesAsLightDirty();
  70919. }
  70920. };
  70921. /**
  70922. * Serializes the shadow generator setup to a json object.
  70923. * @returns The serialized JSON object
  70924. */
  70925. ShadowGenerator.prototype.serialize = function () {
  70926. var serializationObject = {};
  70927. var shadowMap = this.getShadowMap();
  70928. if (!shadowMap) {
  70929. return serializationObject;
  70930. }
  70931. serializationObject.lightId = this._light.id;
  70932. serializationObject.mapSize = shadowMap.getRenderSize();
  70933. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  70934. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  70935. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70936. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70937. serializationObject.usePoissonSampling = this.usePoissonSampling;
  70938. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  70939. serializationObject.depthScale = this.depthScale;
  70940. serializationObject.darkness = this.getDarkness();
  70941. serializationObject.blurBoxOffset = this.blurBoxOffset;
  70942. serializationObject.blurKernel = this.blurKernel;
  70943. serializationObject.blurScale = this.blurScale;
  70944. serializationObject.useKernelBlur = this.useKernelBlur;
  70945. serializationObject.transparencyShadow = this._transparencyShadow;
  70946. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  70947. serializationObject.bias = this.bias;
  70948. serializationObject.normalBias = this.normalBias;
  70949. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  70950. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  70951. serializationObject.filteringQuality = this.filteringQuality;
  70952. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  70953. serializationObject.renderList = [];
  70954. if (shadowMap.renderList) {
  70955. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  70956. var mesh = shadowMap.renderList[meshIndex];
  70957. serializationObject.renderList.push(mesh.id);
  70958. }
  70959. }
  70960. return serializationObject;
  70961. };
  70962. /**
  70963. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  70964. * @param parsedShadowGenerator The JSON object to parse
  70965. * @param scene The scene to create the shadow map for
  70966. * @returns The parsed shadow generator
  70967. */
  70968. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  70969. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  70970. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  70971. var shadowMap = shadowGenerator.getShadowMap();
  70972. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  70973. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  70974. meshes.forEach(function (mesh) {
  70975. if (!shadowMap) {
  70976. return;
  70977. }
  70978. if (!shadowMap.renderList) {
  70979. shadowMap.renderList = [];
  70980. }
  70981. shadowMap.renderList.push(mesh);
  70982. });
  70983. }
  70984. if (parsedShadowGenerator.usePoissonSampling) {
  70985. shadowGenerator.usePoissonSampling = true;
  70986. }
  70987. else if (parsedShadowGenerator.useExponentialShadowMap) {
  70988. shadowGenerator.useExponentialShadowMap = true;
  70989. }
  70990. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  70991. shadowGenerator.useBlurExponentialShadowMap = true;
  70992. }
  70993. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  70994. shadowGenerator.useCloseExponentialShadowMap = true;
  70995. }
  70996. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  70997. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  70998. }
  70999. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  71000. shadowGenerator.usePercentageCloserFiltering = true;
  71001. }
  71002. else if (parsedShadowGenerator.useContactHardeningShadow) {
  71003. shadowGenerator.useContactHardeningShadow = true;
  71004. }
  71005. if (parsedShadowGenerator.filteringQuality) {
  71006. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  71007. }
  71008. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  71009. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  71010. }
  71011. // Backward compat
  71012. else if (parsedShadowGenerator.useVarianceShadowMap) {
  71013. shadowGenerator.useExponentialShadowMap = true;
  71014. }
  71015. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  71016. shadowGenerator.useBlurExponentialShadowMap = true;
  71017. }
  71018. if (parsedShadowGenerator.depthScale) {
  71019. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  71020. }
  71021. if (parsedShadowGenerator.blurScale) {
  71022. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  71023. }
  71024. if (parsedShadowGenerator.blurBoxOffset) {
  71025. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  71026. }
  71027. if (parsedShadowGenerator.useKernelBlur) {
  71028. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  71029. }
  71030. if (parsedShadowGenerator.blurKernel) {
  71031. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  71032. }
  71033. if (parsedShadowGenerator.bias !== undefined) {
  71034. shadowGenerator.bias = parsedShadowGenerator.bias;
  71035. }
  71036. if (parsedShadowGenerator.normalBias !== undefined) {
  71037. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  71038. }
  71039. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  71040. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  71041. }
  71042. if (parsedShadowGenerator.darkness) {
  71043. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  71044. }
  71045. if (parsedShadowGenerator.transparencyShadow) {
  71046. shadowGenerator.setTransparencyShadow(true);
  71047. }
  71048. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  71049. return shadowGenerator;
  71050. };
  71051. /**
  71052. * Shadow generator mode None: no filtering applied.
  71053. */
  71054. ShadowGenerator.FILTER_NONE = 0;
  71055. /**
  71056. * Shadow generator mode ESM: Exponential Shadow Mapping.
  71057. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71058. */
  71059. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  71060. /**
  71061. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  71062. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  71063. */
  71064. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  71065. /**
  71066. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  71067. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71068. */
  71069. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  71070. /**
  71071. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  71072. * edge artifacts on steep falloff.
  71073. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71074. */
  71075. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  71076. /**
  71077. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  71078. * edge artifacts on steep falloff.
  71079. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71080. */
  71081. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  71082. /**
  71083. * Shadow generator mode PCF: Percentage Closer Filtering
  71084. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71085. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  71086. */
  71087. ShadowGenerator.FILTER_PCF = 6;
  71088. /**
  71089. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  71090. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71091. * Contact Hardening
  71092. */
  71093. ShadowGenerator.FILTER_PCSS = 7;
  71094. /**
  71095. * Reserved for PCF and PCSS
  71096. * Highest Quality.
  71097. *
  71098. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  71099. *
  71100. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  71101. */
  71102. ShadowGenerator.QUALITY_HIGH = 0;
  71103. /**
  71104. * Reserved for PCF and PCSS
  71105. * Good tradeoff for quality/perf cross devices
  71106. *
  71107. * Execute PCF on a 3*3 kernel.
  71108. *
  71109. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  71110. */
  71111. ShadowGenerator.QUALITY_MEDIUM = 1;
  71112. /**
  71113. * Reserved for PCF and PCSS
  71114. * The lowest quality but the fastest.
  71115. *
  71116. * Execute PCF on a 1*1 kernel.
  71117. *
  71118. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  71119. */
  71120. ShadowGenerator.QUALITY_LOW = 2;
  71121. return ShadowGenerator;
  71122. }());
  71123. BABYLON.ShadowGenerator = ShadowGenerator;
  71124. })(BABYLON || (BABYLON = {}));
  71125. //# sourceMappingURL=babylon.shadowGenerator.js.map
  71126. var BABYLON;
  71127. (function (BABYLON) {
  71128. // Adds the parser to the scene parsers.
  71129. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  71130. // Shadows
  71131. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  71132. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  71133. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  71134. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  71135. // SG would be available on their associated lights
  71136. }
  71137. }
  71138. });
  71139. /**
  71140. * Defines the shadow generator component responsible to manage any shadow generators
  71141. * in a given scene.
  71142. */
  71143. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  71144. /**
  71145. * Creates a new instance of the component for the given scene
  71146. * @param scene Defines the scene to register the component in
  71147. */
  71148. function ShadowGeneratorSceneComponent(scene) {
  71149. /**
  71150. * The component name helpfull to identify the component in the list of scene components.
  71151. */
  71152. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  71153. this.scene = scene;
  71154. }
  71155. /**
  71156. * Registers the component in a given scene
  71157. */
  71158. ShadowGeneratorSceneComponent.prototype.register = function () {
  71159. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  71160. };
  71161. /**
  71162. * Rebuilds the elements related to this component in case of
  71163. * context lost for instance.
  71164. */
  71165. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  71166. // Nothing To Do Here.
  71167. };
  71168. /**
  71169. * Serializes the component data to the specified json object
  71170. * @param serializationObject The object to serialize to
  71171. */
  71172. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  71173. // Shadows
  71174. serializationObject.shadowGenerators = [];
  71175. var lights = this.scene.lights;
  71176. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  71177. var light = lights_1[_i];
  71178. var shadowGenerator = light.getShadowGenerator();
  71179. if (shadowGenerator) {
  71180. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  71181. }
  71182. }
  71183. };
  71184. /**
  71185. * Adds all the element from the container to the scene
  71186. * @param container the container holding the elements
  71187. */
  71188. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  71189. // Nothing To Do Here. (directly attached to a light)
  71190. };
  71191. /**
  71192. * Removes all the elements in the container from the scene
  71193. * @param container contains the elements to remove
  71194. */
  71195. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  71196. // Nothing To Do Here. (directly attached to a light)
  71197. };
  71198. /**
  71199. * Rebuilds the elements related to this component in case of
  71200. * context lost for instance.
  71201. */
  71202. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  71203. // Nothing To Do Here.
  71204. };
  71205. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  71206. // Shadows
  71207. var scene = this.scene;
  71208. if (this.scene.shadowsEnabled) {
  71209. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  71210. var light = scene.lights[lightIndex];
  71211. var shadowGenerator = light.getShadowGenerator();
  71212. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  71213. var shadowMap = (shadowGenerator.getShadowMap());
  71214. if (scene.textures.indexOf(shadowMap) !== -1) {
  71215. renderTargets.push(shadowMap);
  71216. }
  71217. }
  71218. }
  71219. }
  71220. };
  71221. return ShadowGeneratorSceneComponent;
  71222. }());
  71223. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  71224. })(BABYLON || (BABYLON = {}));
  71225. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  71226. var BABYLON;
  71227. (function (BABYLON) {
  71228. var DefaultLoadingScreen = /** @class */ (function () {
  71229. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  71230. if (_loadingText === void 0) { _loadingText = ""; }
  71231. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  71232. var _this = this;
  71233. this._renderingCanvas = _renderingCanvas;
  71234. this._loadingText = _loadingText;
  71235. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  71236. // Resize
  71237. this._resizeLoadingUI = function () {
  71238. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  71239. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  71240. if (!_this._loadingDiv) {
  71241. return;
  71242. }
  71243. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  71244. _this._loadingDiv.style.left = canvasRect.left + "px";
  71245. _this._loadingDiv.style.top = canvasRect.top + "px";
  71246. _this._loadingDiv.style.width = canvasRect.width + "px";
  71247. _this._loadingDiv.style.height = canvasRect.height + "px";
  71248. };
  71249. }
  71250. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  71251. if (this._loadingDiv) {
  71252. // Do not add a loading screen if there is already one
  71253. return;
  71254. }
  71255. this._loadingDiv = document.createElement("div");
  71256. this._loadingDiv.id = "babylonjsLoadingDiv";
  71257. this._loadingDiv.style.opacity = "0";
  71258. this._loadingDiv.style.transition = "opacity 1.5s ease";
  71259. this._loadingDiv.style.pointerEvents = "none";
  71260. // Loading text
  71261. this._loadingTextDiv = document.createElement("div");
  71262. this._loadingTextDiv.style.position = "absolute";
  71263. this._loadingTextDiv.style.left = "0";
  71264. this._loadingTextDiv.style.top = "50%";
  71265. this._loadingTextDiv.style.marginTop = "80px";
  71266. this._loadingTextDiv.style.width = "100%";
  71267. this._loadingTextDiv.style.height = "20px";
  71268. this._loadingTextDiv.style.fontFamily = "Arial";
  71269. this._loadingTextDiv.style.fontSize = "14px";
  71270. this._loadingTextDiv.style.color = "white";
  71271. this._loadingTextDiv.style.textAlign = "center";
  71272. this._loadingTextDiv.innerHTML = "Loading";
  71273. this._loadingDiv.appendChild(this._loadingTextDiv);
  71274. //set the predefined text
  71275. this._loadingTextDiv.innerHTML = this._loadingText;
  71276. // Generating keyframes
  71277. var style = document.createElement('style');
  71278. style.type = 'text/css';
  71279. 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 }";
  71280. style.innerHTML = keyFrames;
  71281. document.getElementsByTagName('head')[0].appendChild(style);
  71282. // Loading img
  71283. var imgBack = new Image();
  71284. 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";
  71285. imgBack.style.position = "absolute";
  71286. imgBack.style.left = "50%";
  71287. imgBack.style.top = "50%";
  71288. imgBack.style.marginLeft = "-60px";
  71289. imgBack.style.marginTop = "-60px";
  71290. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  71291. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  71292. imgBack.style.transformOrigin = "50% 50%";
  71293. imgBack.style.webkitTransformOrigin = "50% 50%";
  71294. this._loadingDiv.appendChild(imgBack);
  71295. this._resizeLoadingUI();
  71296. window.addEventListener("resize", this._resizeLoadingUI);
  71297. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71298. document.body.appendChild(this._loadingDiv);
  71299. this._loadingDiv.style.opacity = "1";
  71300. };
  71301. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  71302. var _this = this;
  71303. if (!this._loadingDiv) {
  71304. return;
  71305. }
  71306. var onTransitionEnd = function () {
  71307. if (!_this._loadingDiv) {
  71308. return;
  71309. }
  71310. document.body.removeChild(_this._loadingDiv);
  71311. window.removeEventListener("resize", _this._resizeLoadingUI);
  71312. _this._loadingDiv = null;
  71313. };
  71314. this._loadingDiv.style.opacity = "0";
  71315. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  71316. };
  71317. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  71318. set: function (text) {
  71319. this._loadingText = text;
  71320. if (this._loadingTextDiv) {
  71321. this._loadingTextDiv.innerHTML = this._loadingText;
  71322. }
  71323. },
  71324. enumerable: true,
  71325. configurable: true
  71326. });
  71327. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  71328. get: function () {
  71329. return this._loadingDivBackgroundColor;
  71330. },
  71331. set: function (color) {
  71332. this._loadingDivBackgroundColor = color;
  71333. if (!this._loadingDiv) {
  71334. return;
  71335. }
  71336. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71337. },
  71338. enumerable: true,
  71339. configurable: true
  71340. });
  71341. return DefaultLoadingScreen;
  71342. }());
  71343. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  71344. })(BABYLON || (BABYLON = {}));
  71345. //# sourceMappingURL=babylon.loadingScreen.js.map
  71346. var BABYLON;
  71347. (function (BABYLON) {
  71348. var SceneLoaderProgressEvent = /** @class */ (function () {
  71349. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  71350. this.lengthComputable = lengthComputable;
  71351. this.loaded = loaded;
  71352. this.total = total;
  71353. }
  71354. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  71355. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  71356. };
  71357. return SceneLoaderProgressEvent;
  71358. }());
  71359. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  71360. var SceneLoader = /** @class */ (function () {
  71361. function SceneLoader() {
  71362. }
  71363. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  71364. get: function () {
  71365. return 0;
  71366. },
  71367. enumerable: true,
  71368. configurable: true
  71369. });
  71370. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  71371. get: function () {
  71372. return 1;
  71373. },
  71374. enumerable: true,
  71375. configurable: true
  71376. });
  71377. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  71378. get: function () {
  71379. return 2;
  71380. },
  71381. enumerable: true,
  71382. configurable: true
  71383. });
  71384. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  71385. get: function () {
  71386. return 3;
  71387. },
  71388. enumerable: true,
  71389. configurable: true
  71390. });
  71391. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  71392. get: function () {
  71393. return SceneLoader._ForceFullSceneLoadingForIncremental;
  71394. },
  71395. set: function (value) {
  71396. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  71397. },
  71398. enumerable: true,
  71399. configurable: true
  71400. });
  71401. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  71402. get: function () {
  71403. return SceneLoader._ShowLoadingScreen;
  71404. },
  71405. set: function (value) {
  71406. SceneLoader._ShowLoadingScreen = value;
  71407. },
  71408. enumerable: true,
  71409. configurable: true
  71410. });
  71411. Object.defineProperty(SceneLoader, "loggingLevel", {
  71412. get: function () {
  71413. return SceneLoader._loggingLevel;
  71414. },
  71415. set: function (value) {
  71416. SceneLoader._loggingLevel = value;
  71417. },
  71418. enumerable: true,
  71419. configurable: true
  71420. });
  71421. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  71422. get: function () {
  71423. return SceneLoader._CleanBoneMatrixWeights;
  71424. },
  71425. set: function (value) {
  71426. SceneLoader._CleanBoneMatrixWeights = value;
  71427. },
  71428. enumerable: true,
  71429. configurable: true
  71430. });
  71431. SceneLoader._getDefaultPlugin = function () {
  71432. return SceneLoader._registeredPlugins[".babylon"];
  71433. };
  71434. SceneLoader._getPluginForExtension = function (extension) {
  71435. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  71436. if (registeredPlugin) {
  71437. return registeredPlugin;
  71438. }
  71439. 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");
  71440. return SceneLoader._getDefaultPlugin();
  71441. };
  71442. SceneLoader._getPluginForDirectLoad = function (data) {
  71443. for (var extension in SceneLoader._registeredPlugins) {
  71444. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  71445. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  71446. return SceneLoader._registeredPlugins[extension];
  71447. }
  71448. }
  71449. return SceneLoader._getDefaultPlugin();
  71450. };
  71451. SceneLoader._getPluginForFilename = function (sceneFilename) {
  71452. if (sceneFilename.name) {
  71453. sceneFilename = sceneFilename.name;
  71454. }
  71455. var queryStringPosition = sceneFilename.indexOf("?");
  71456. if (queryStringPosition !== -1) {
  71457. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  71458. }
  71459. var dotPosition = sceneFilename.lastIndexOf(".");
  71460. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  71461. return SceneLoader._getPluginForExtension(extension);
  71462. };
  71463. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  71464. SceneLoader._getDirectLoad = function (sceneFilename) {
  71465. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  71466. return sceneFilename.substr(5);
  71467. }
  71468. return null;
  71469. };
  71470. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  71471. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  71472. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  71473. var plugin;
  71474. if (registeredPlugin.plugin.createPlugin) {
  71475. plugin = registeredPlugin.plugin.createPlugin();
  71476. }
  71477. else {
  71478. plugin = registeredPlugin.plugin;
  71479. }
  71480. var useArrayBuffer = registeredPlugin.isBinary;
  71481. var database;
  71482. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  71483. var dataCallback = function (data, responseURL) {
  71484. if (scene.isDisposed) {
  71485. onError("Scene has been disposed");
  71486. return;
  71487. }
  71488. scene.database = database;
  71489. onSuccess(plugin, data, responseURL);
  71490. };
  71491. var request = null;
  71492. var pluginDisposed = false;
  71493. var onDisposeObservable = plugin.onDisposeObservable;
  71494. if (onDisposeObservable) {
  71495. onDisposeObservable.add(function () {
  71496. pluginDisposed = true;
  71497. if (request) {
  71498. request.abort();
  71499. request = null;
  71500. }
  71501. onDispose();
  71502. });
  71503. }
  71504. var manifestChecked = function () {
  71505. if (pluginDisposed) {
  71506. return;
  71507. }
  71508. var url = rootUrl + sceneFilename;
  71509. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  71510. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  71511. } : undefined, database, useArrayBuffer, function (request, exception) {
  71512. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  71513. });
  71514. };
  71515. if (directLoad) {
  71516. dataCallback(directLoad);
  71517. return plugin;
  71518. }
  71519. if (rootUrl.indexOf("file:") === -1) {
  71520. var engine = scene.getEngine();
  71521. var canUseOfflineSupport = engine.enableOfflineSupport;
  71522. if (canUseOfflineSupport) {
  71523. // Also check for exceptions
  71524. var exceptionFound = false;
  71525. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  71526. var regex = _a[_i];
  71527. if (regex.test(rootUrl + sceneFilename)) {
  71528. exceptionFound = true;
  71529. break;
  71530. }
  71531. }
  71532. canUseOfflineSupport = !exceptionFound;
  71533. }
  71534. if (canUseOfflineSupport) {
  71535. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  71536. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  71537. }
  71538. else {
  71539. manifestChecked();
  71540. }
  71541. }
  71542. // Loading file from disk via input file or drag'n'drop
  71543. else {
  71544. var fileOrString = sceneFilename;
  71545. if (fileOrString.name) { // File
  71546. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  71547. }
  71548. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  71549. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  71550. }
  71551. else {
  71552. onError("Unable to find file named " + sceneFilename);
  71553. }
  71554. }
  71555. return plugin;
  71556. };
  71557. // Public functions
  71558. SceneLoader.GetPluginForExtension = function (extension) {
  71559. return SceneLoader._getPluginForExtension(extension).plugin;
  71560. };
  71561. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  71562. return !!SceneLoader._registeredPlugins[extension];
  71563. };
  71564. SceneLoader.RegisterPlugin = function (plugin) {
  71565. if (typeof plugin.extensions === "string") {
  71566. var extension = plugin.extensions;
  71567. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71568. plugin: plugin,
  71569. isBinary: false
  71570. };
  71571. }
  71572. else {
  71573. var extensions = plugin.extensions;
  71574. Object.keys(extensions).forEach(function (extension) {
  71575. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71576. plugin: plugin,
  71577. isBinary: extensions[extension].isBinary
  71578. };
  71579. });
  71580. }
  71581. };
  71582. /**
  71583. * Import meshes into a scene
  71584. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71585. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71586. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71587. * @param scene the instance of BABYLON.Scene to append to
  71588. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  71589. * @param onProgress a callback with a progress event for each file being loaded
  71590. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71591. * @param pluginExtension the extension used to determine the plugin
  71592. * @returns The loaded plugin
  71593. */
  71594. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71595. if (sceneFilename === void 0) { sceneFilename = ""; }
  71596. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71597. if (onSuccess === void 0) { onSuccess = null; }
  71598. if (onProgress === void 0) { onProgress = null; }
  71599. if (onError === void 0) { onError = null; }
  71600. if (pluginExtension === void 0) { pluginExtension = null; }
  71601. if (!scene) {
  71602. BABYLON.Tools.Error("No scene available to import mesh to");
  71603. return null;
  71604. }
  71605. if (!sceneFilename) {
  71606. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71607. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71608. }
  71609. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71610. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71611. return null;
  71612. }
  71613. var loadingToken = {};
  71614. scene._addPendingData(loadingToken);
  71615. var disposeHandler = function () {
  71616. scene._removePendingData(loadingToken);
  71617. };
  71618. var errorHandler = function (message, exception) {
  71619. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  71620. if (onError) {
  71621. onError(scene, errorMessage, exception);
  71622. }
  71623. else {
  71624. BABYLON.Tools.Error(errorMessage);
  71625. // should the exception be thrown?
  71626. }
  71627. disposeHandler();
  71628. };
  71629. var progressHandler = onProgress ? function (event) {
  71630. try {
  71631. onProgress(event);
  71632. }
  71633. catch (e) {
  71634. errorHandler("Error in onProgress callback", e);
  71635. }
  71636. } : undefined;
  71637. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  71638. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  71639. if (onSuccess) {
  71640. try {
  71641. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  71642. }
  71643. catch (e) {
  71644. errorHandler("Error in onSuccess callback", e);
  71645. }
  71646. }
  71647. scene._removePendingData(loadingToken);
  71648. };
  71649. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71650. if (plugin.rewriteRootURL) {
  71651. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  71652. }
  71653. if (sceneFilename === "") {
  71654. if (sceneFilename === "") {
  71655. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  71656. }
  71657. }
  71658. if (plugin.importMesh) {
  71659. var syncedPlugin = plugin;
  71660. var meshes = new Array();
  71661. var particleSystems = new Array();
  71662. var skeletons = new Array();
  71663. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  71664. return;
  71665. }
  71666. scene.loadingPluginName = plugin.name;
  71667. successHandler(meshes, particleSystems, skeletons, []);
  71668. }
  71669. else {
  71670. var asyncedPlugin = plugin;
  71671. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function (result) {
  71672. scene.loadingPluginName = plugin.name;
  71673. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  71674. }).catch(function (error) {
  71675. errorHandler(error.message, error);
  71676. });
  71677. }
  71678. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71679. };
  71680. /**
  71681. * Import meshes into a scene
  71682. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71683. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71684. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71685. * @param scene the instance of BABYLON.Scene to append to
  71686. * @param onProgress a callback with a progress event for each file being loaded
  71687. * @param pluginExtension the extension used to determine the plugin
  71688. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  71689. */
  71690. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71691. if (sceneFilename === void 0) { sceneFilename = ""; }
  71692. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71693. if (onProgress === void 0) { onProgress = null; }
  71694. if (pluginExtension === void 0) { pluginExtension = null; }
  71695. return new Promise(function (resolve, reject) {
  71696. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  71697. resolve({
  71698. meshes: meshes,
  71699. particleSystems: particleSystems,
  71700. skeletons: skeletons,
  71701. animationGroups: animationGroups
  71702. });
  71703. }, onProgress, function (scene, message, exception) {
  71704. reject(exception || new Error(message));
  71705. }, pluginExtension);
  71706. });
  71707. };
  71708. /**
  71709. * Load a scene
  71710. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71711. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71712. * @param engine is the instance of BABYLON.Engine to use to create the scene
  71713. * @param onSuccess a callback with the scene when import succeeds
  71714. * @param onProgress a callback with a progress event for each file being loaded
  71715. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71716. * @param pluginExtension the extension used to determine the plugin
  71717. * @returns The loaded plugin
  71718. */
  71719. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  71720. if (onSuccess === void 0) { onSuccess = null; }
  71721. if (onProgress === void 0) { onProgress = null; }
  71722. if (onError === void 0) { onError = null; }
  71723. if (pluginExtension === void 0) { pluginExtension = null; }
  71724. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  71725. };
  71726. /**
  71727. * Load a scene
  71728. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71729. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71730. * @param engine is the instance of BABYLON.Engine to use to create the scene
  71731. * @param onProgress a callback with a progress event for each file being loaded
  71732. * @param pluginExtension the extension used to determine the plugin
  71733. * @returns The loaded scene
  71734. */
  71735. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  71736. if (onProgress === void 0) { onProgress = null; }
  71737. if (pluginExtension === void 0) { pluginExtension = null; }
  71738. return new Promise(function (resolve, reject) {
  71739. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  71740. resolve(scene);
  71741. }, onProgress, function (scene, message, exception) {
  71742. reject(exception || new Error(message));
  71743. }, pluginExtension);
  71744. });
  71745. };
  71746. /**
  71747. * Append a scene
  71748. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71749. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71750. * @param scene is the instance of BABYLON.Scene to append to
  71751. * @param onSuccess a callback with the scene when import succeeds
  71752. * @param onProgress a callback with a progress event for each file being loaded
  71753. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71754. * @param pluginExtension the extension used to determine the plugin
  71755. * @returns The loaded plugin
  71756. */
  71757. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71758. if (sceneFilename === void 0) { sceneFilename = ""; }
  71759. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71760. if (onSuccess === void 0) { onSuccess = null; }
  71761. if (onProgress === void 0) { onProgress = null; }
  71762. if (onError === void 0) { onError = null; }
  71763. if (pluginExtension === void 0) { pluginExtension = null; }
  71764. if (!scene) {
  71765. BABYLON.Tools.Error("No scene available to append to");
  71766. return null;
  71767. }
  71768. if (!sceneFilename) {
  71769. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71770. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71771. }
  71772. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71773. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71774. return null;
  71775. }
  71776. if (SceneLoader.ShowLoadingScreen) {
  71777. scene.getEngine().displayLoadingUI();
  71778. }
  71779. var loadingToken = {};
  71780. scene._addPendingData(loadingToken);
  71781. var disposeHandler = function () {
  71782. scene._removePendingData(loadingToken);
  71783. scene.getEngine().hideLoadingUI();
  71784. };
  71785. var errorHandler = function (message, exception) {
  71786. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  71787. if (onError) {
  71788. onError(scene, errorMessage, exception);
  71789. }
  71790. else {
  71791. BABYLON.Tools.Error(errorMessage);
  71792. // should the exception be thrown?
  71793. }
  71794. disposeHandler();
  71795. };
  71796. var progressHandler = onProgress ? function (event) {
  71797. try {
  71798. onProgress(event);
  71799. }
  71800. catch (e) {
  71801. errorHandler("Error in onProgress callback", e);
  71802. }
  71803. } : undefined;
  71804. var successHandler = function () {
  71805. if (onSuccess) {
  71806. try {
  71807. onSuccess(scene);
  71808. }
  71809. catch (e) {
  71810. errorHandler("Error in onSuccess callback", e);
  71811. }
  71812. }
  71813. scene._removePendingData(loadingToken);
  71814. };
  71815. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71816. if (sceneFilename === "") {
  71817. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  71818. }
  71819. if (plugin.load) {
  71820. var syncedPlugin = plugin;
  71821. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  71822. return;
  71823. }
  71824. scene.loadingPluginName = plugin.name;
  71825. successHandler();
  71826. }
  71827. else {
  71828. var asyncedPlugin = plugin;
  71829. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function () {
  71830. scene.loadingPluginName = plugin.name;
  71831. successHandler();
  71832. }).catch(function (error) {
  71833. errorHandler(error.message, error);
  71834. });
  71835. }
  71836. if (SceneLoader.ShowLoadingScreen) {
  71837. scene.executeWhenReady(function () {
  71838. scene.getEngine().hideLoadingUI();
  71839. });
  71840. }
  71841. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71842. };
  71843. /**
  71844. * Append a scene
  71845. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71846. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71847. * @param scene is the instance of BABYLON.Scene to append to
  71848. * @param onProgress a callback with a progress event for each file being loaded
  71849. * @param pluginExtension the extension used to determine the plugin
  71850. * @returns The given scene
  71851. */
  71852. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71853. if (sceneFilename === void 0) { sceneFilename = ""; }
  71854. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71855. if (onProgress === void 0) { onProgress = null; }
  71856. if (pluginExtension === void 0) { pluginExtension = null; }
  71857. return new Promise(function (resolve, reject) {
  71858. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  71859. resolve(scene);
  71860. }, onProgress, function (scene, message, exception) {
  71861. reject(exception || new Error(message));
  71862. }, pluginExtension);
  71863. });
  71864. };
  71865. /**
  71866. * Load a scene into an asset container
  71867. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71868. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71869. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  71870. * @param onSuccess a callback with the scene when import succeeds
  71871. * @param onProgress a callback with a progress event for each file being loaded
  71872. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71873. * @param pluginExtension the extension used to determine the plugin
  71874. * @returns The loaded plugin
  71875. */
  71876. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71877. if (sceneFilename === void 0) { sceneFilename = ""; }
  71878. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71879. if (onSuccess === void 0) { onSuccess = null; }
  71880. if (onProgress === void 0) { onProgress = null; }
  71881. if (onError === void 0) { onError = null; }
  71882. if (pluginExtension === void 0) { pluginExtension = null; }
  71883. if (!scene) {
  71884. BABYLON.Tools.Error("No scene available to load asset container to");
  71885. return null;
  71886. }
  71887. if (!sceneFilename) {
  71888. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71889. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71890. }
  71891. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71892. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71893. return null;
  71894. }
  71895. var loadingToken = {};
  71896. scene._addPendingData(loadingToken);
  71897. var disposeHandler = function () {
  71898. scene._removePendingData(loadingToken);
  71899. };
  71900. var errorHandler = function (message, exception) {
  71901. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  71902. if (onError) {
  71903. onError(scene, errorMessage, exception);
  71904. }
  71905. else {
  71906. BABYLON.Tools.Error(errorMessage);
  71907. // should the exception be thrown?
  71908. }
  71909. disposeHandler();
  71910. };
  71911. var progressHandler = onProgress ? function (event) {
  71912. try {
  71913. onProgress(event);
  71914. }
  71915. catch (e) {
  71916. errorHandler("Error in onProgress callback", e);
  71917. }
  71918. } : undefined;
  71919. var successHandler = function (assets) {
  71920. if (onSuccess) {
  71921. try {
  71922. onSuccess(assets);
  71923. }
  71924. catch (e) {
  71925. errorHandler("Error in onSuccess callback", e);
  71926. }
  71927. }
  71928. scene._removePendingData(loadingToken);
  71929. };
  71930. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71931. if (plugin.loadAssetContainer) {
  71932. var syncedPlugin = plugin;
  71933. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  71934. if (!assetContainer) {
  71935. return;
  71936. }
  71937. scene.loadingPluginName = plugin.name;
  71938. successHandler(assetContainer);
  71939. }
  71940. else if (plugin.loadAssetContainerAsync) {
  71941. var asyncedPlugin = plugin;
  71942. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function (assetContainer) {
  71943. scene.loadingPluginName = plugin.name;
  71944. successHandler(assetContainer);
  71945. }).catch(function (error) {
  71946. errorHandler(error.message, error);
  71947. });
  71948. }
  71949. else {
  71950. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  71951. }
  71952. if (SceneLoader.ShowLoadingScreen) {
  71953. scene.executeWhenReady(function () {
  71954. scene.getEngine().hideLoadingUI();
  71955. });
  71956. }
  71957. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71958. };
  71959. /**
  71960. * Load a scene into an asset container
  71961. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  71962. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  71963. * @param scene is the instance of BABYLON.Scene to append to
  71964. * @param onProgress a callback with a progress event for each file being loaded
  71965. * @param pluginExtension the extension used to determine the plugin
  71966. * @returns The loaded asset container
  71967. */
  71968. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71969. if (sceneFilename === void 0) { sceneFilename = ""; }
  71970. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71971. if (onProgress === void 0) { onProgress = null; }
  71972. if (pluginExtension === void 0) { pluginExtension = null; }
  71973. return new Promise(function (resolve, reject) {
  71974. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  71975. resolve(assetContainer);
  71976. }, onProgress, function (scene, message, exception) {
  71977. reject(exception || new Error(message));
  71978. }, pluginExtension);
  71979. });
  71980. };
  71981. // Flags
  71982. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  71983. SceneLoader._ShowLoadingScreen = true;
  71984. SceneLoader._CleanBoneMatrixWeights = false;
  71985. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  71986. // Members
  71987. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  71988. SceneLoader._registeredPlugins = {};
  71989. return SceneLoader;
  71990. }());
  71991. BABYLON.SceneLoader = SceneLoader;
  71992. ;
  71993. })(BABYLON || (BABYLON = {}));
  71994. //# sourceMappingURL=babylon.sceneLoader.js.map
  71995. var BABYLON;
  71996. (function (BABYLON) {
  71997. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  71998. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  71999. var parsedMaterial = parsedData.materials[index];
  72000. if (parsedMaterial.id === id) {
  72001. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  72002. }
  72003. }
  72004. return null;
  72005. };
  72006. var isDescendantOf = function (mesh, names, hierarchyIds) {
  72007. for (var i in names) {
  72008. if (mesh.name === names[i]) {
  72009. hierarchyIds.push(mesh.id);
  72010. return true;
  72011. }
  72012. }
  72013. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  72014. hierarchyIds.push(mesh.id);
  72015. return true;
  72016. }
  72017. return false;
  72018. };
  72019. var logOperation = function (operation, producer) {
  72020. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  72021. };
  72022. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  72023. if (addToScene === void 0) { addToScene = false; }
  72024. var container = new BABYLON.AssetContainer(scene);
  72025. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72026. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72027. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72028. // and avoid problems with multiple concurrent .babylon loads.
  72029. var log = "importScene has failed JSON parse";
  72030. try {
  72031. var parsedData = JSON.parse(data);
  72032. log = "";
  72033. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72034. var index;
  72035. var cache;
  72036. // Lights
  72037. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  72038. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  72039. var parsedLight = parsedData.lights[index];
  72040. var light = BABYLON.Light.Parse(parsedLight, scene);
  72041. if (light) {
  72042. container.lights.push(light);
  72043. log += (index === 0 ? "\n\tLights:" : "");
  72044. log += "\n\t\t" + light.toString(fullDetails);
  72045. }
  72046. }
  72047. }
  72048. // Animations
  72049. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  72050. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  72051. var parsedAnimation = parsedData.animations[index];
  72052. var animation = BABYLON.Animation.Parse(parsedAnimation);
  72053. scene.animations.push(animation);
  72054. container.animations.push(animation);
  72055. log += (index === 0 ? "\n\tAnimations:" : "");
  72056. log += "\n\t\t" + animation.toString(fullDetails);
  72057. }
  72058. }
  72059. // Materials
  72060. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  72061. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  72062. var parsedMaterial = parsedData.materials[index];
  72063. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  72064. container.materials.push(mat);
  72065. log += (index === 0 ? "\n\tMaterials:" : "");
  72066. log += "\n\t\t" + mat.toString(fullDetails);
  72067. }
  72068. }
  72069. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72070. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  72071. var parsedMultiMaterial = parsedData.multiMaterials[index];
  72072. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72073. container.multiMaterials.push(mmat);
  72074. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  72075. log += "\n\t\t" + mmat.toString(fullDetails);
  72076. }
  72077. }
  72078. // Morph targets
  72079. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72080. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72081. var managerData = _a[_i];
  72082. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  72083. }
  72084. }
  72085. // Skeletons
  72086. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72087. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  72088. var parsedSkeleton = parsedData.skeletons[index];
  72089. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72090. container.skeletons.push(skeleton);
  72091. log += (index === 0 ? "\n\tSkeletons:" : "");
  72092. log += "\n\t\t" + skeleton.toString(fullDetails);
  72093. }
  72094. }
  72095. // Geometries
  72096. var geometries = parsedData.geometries;
  72097. if (geometries !== undefined && geometries !== null) {
  72098. var addedGeometry = new Array();
  72099. // Boxes
  72100. var boxes = geometries.boxes;
  72101. if (boxes !== undefined && boxes !== null) {
  72102. for (index = 0, cache = boxes.length; index < cache; index++) {
  72103. var parsedBox = boxes[index];
  72104. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  72105. }
  72106. }
  72107. // Spheres
  72108. var spheres = geometries.spheres;
  72109. if (spheres !== undefined && spheres !== null) {
  72110. for (index = 0, cache = spheres.length; index < cache; index++) {
  72111. var parsedSphere = spheres[index];
  72112. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  72113. }
  72114. }
  72115. // Cylinders
  72116. var cylinders = geometries.cylinders;
  72117. if (cylinders !== undefined && cylinders !== null) {
  72118. for (index = 0, cache = cylinders.length; index < cache; index++) {
  72119. var parsedCylinder = cylinders[index];
  72120. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  72121. }
  72122. }
  72123. // Toruses
  72124. var toruses = geometries.toruses;
  72125. if (toruses !== undefined && toruses !== null) {
  72126. for (index = 0, cache = toruses.length; index < cache; index++) {
  72127. var parsedTorus = toruses[index];
  72128. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  72129. }
  72130. }
  72131. // Grounds
  72132. var grounds = geometries.grounds;
  72133. if (grounds !== undefined && grounds !== null) {
  72134. for (index = 0, cache = grounds.length; index < cache; index++) {
  72135. var parsedGround = grounds[index];
  72136. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  72137. }
  72138. }
  72139. // Planes
  72140. var planes = geometries.planes;
  72141. if (planes !== undefined && planes !== null) {
  72142. for (index = 0, cache = planes.length; index < cache; index++) {
  72143. var parsedPlane = planes[index];
  72144. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  72145. }
  72146. }
  72147. // TorusKnots
  72148. var torusKnots = geometries.torusKnots;
  72149. if (torusKnots !== undefined && torusKnots !== null) {
  72150. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  72151. var parsedTorusKnot = torusKnots[index];
  72152. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  72153. }
  72154. }
  72155. // VertexData
  72156. var vertexData = geometries.vertexData;
  72157. if (vertexData !== undefined && vertexData !== null) {
  72158. for (index = 0, cache = vertexData.length; index < cache; index++) {
  72159. var parsedVertexData = vertexData[index];
  72160. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  72161. }
  72162. }
  72163. addedGeometry.forEach(function (g) {
  72164. if (g) {
  72165. container.geometries.push(g);
  72166. }
  72167. });
  72168. }
  72169. // Transform nodes
  72170. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  72171. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  72172. var parsedTransformNode = parsedData.transformNodes[index];
  72173. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  72174. container.transformNodes.push(node);
  72175. }
  72176. }
  72177. // Meshes
  72178. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72179. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72180. var parsedMesh = parsedData.meshes[index];
  72181. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  72182. container.meshes.push(mesh);
  72183. log += (index === 0 ? "\n\tMeshes:" : "");
  72184. log += "\n\t\t" + mesh.toString(fullDetails);
  72185. }
  72186. }
  72187. // Cameras
  72188. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  72189. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  72190. var parsedCamera = parsedData.cameras[index];
  72191. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  72192. container.cameras.push(camera);
  72193. log += (index === 0 ? "\n\tCameras:" : "");
  72194. log += "\n\t\t" + camera.toString(fullDetails);
  72195. }
  72196. }
  72197. // Browsing all the graph to connect the dots
  72198. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  72199. var camera = scene.cameras[index];
  72200. if (camera._waitingParentId) {
  72201. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  72202. camera._waitingParentId = null;
  72203. }
  72204. }
  72205. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72206. var light_1 = scene.lights[index];
  72207. if (light_1 && light_1._waitingParentId) {
  72208. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  72209. light_1._waitingParentId = null;
  72210. }
  72211. }
  72212. // Sounds
  72213. // TODO: add sound
  72214. var loadedSounds = [];
  72215. var loadedSound;
  72216. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  72217. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  72218. var parsedSound = parsedData.sounds[index];
  72219. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  72220. if (!parsedSound.url)
  72221. parsedSound.url = parsedSound.name;
  72222. if (!loadedSounds[parsedSound.url]) {
  72223. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  72224. loadedSounds[parsedSound.url] = loadedSound;
  72225. container.sounds.push(loadedSound);
  72226. }
  72227. else {
  72228. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  72229. }
  72230. }
  72231. else {
  72232. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  72233. }
  72234. }
  72235. }
  72236. loadedSounds = [];
  72237. // Connect parents & children and parse actions
  72238. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  72239. var transformNode = scene.transformNodes[index];
  72240. if (transformNode._waitingParentId) {
  72241. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  72242. transformNode._waitingParentId = null;
  72243. }
  72244. }
  72245. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72246. var mesh = scene.meshes[index];
  72247. if (mesh._waitingParentId) {
  72248. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  72249. mesh._waitingParentId = null;
  72250. }
  72251. if (mesh._waitingActions) {
  72252. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  72253. mesh._waitingActions = null;
  72254. }
  72255. }
  72256. // freeze world matrix application
  72257. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72258. var currentMesh = scene.meshes[index];
  72259. if (currentMesh._waitingFreezeWorldMatrix) {
  72260. currentMesh.freezeWorldMatrix();
  72261. currentMesh._waitingFreezeWorldMatrix = null;
  72262. }
  72263. else {
  72264. currentMesh.computeWorldMatrix(true);
  72265. }
  72266. }
  72267. // Lights exclusions / inclusions
  72268. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72269. var light_2 = scene.lights[index];
  72270. // Excluded check
  72271. if (light_2._excludedMeshesIds.length > 0) {
  72272. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  72273. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  72274. if (excludedMesh) {
  72275. light_2.excludedMeshes.push(excludedMesh);
  72276. }
  72277. }
  72278. light_2._excludedMeshesIds = [];
  72279. }
  72280. // Included check
  72281. if (light_2._includedOnlyMeshesIds.length > 0) {
  72282. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  72283. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  72284. if (includedOnlyMesh) {
  72285. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  72286. }
  72287. }
  72288. light_2._includedOnlyMeshesIds = [];
  72289. }
  72290. }
  72291. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  72292. // Actions (scene)
  72293. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  72294. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  72295. }
  72296. if (!addToScene) {
  72297. container.removeAllFromScene();
  72298. }
  72299. }
  72300. catch (err) {
  72301. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  72302. if (onError) {
  72303. onError(msg, err);
  72304. }
  72305. else {
  72306. BABYLON.Tools.Log(msg);
  72307. throw err;
  72308. }
  72309. }
  72310. finally {
  72311. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72312. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72313. }
  72314. }
  72315. return container;
  72316. };
  72317. BABYLON.SceneLoader.RegisterPlugin({
  72318. name: "babylon.js",
  72319. extensions: ".babylon",
  72320. canDirectLoad: function (data) {
  72321. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  72322. return true;
  72323. }
  72324. return false;
  72325. },
  72326. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  72327. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72328. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72329. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72330. // and avoid problems with multiple concurrent .babylon loads.
  72331. var log = "importMesh has failed JSON parse";
  72332. try {
  72333. var parsedData = JSON.parse(data);
  72334. log = "";
  72335. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72336. if (!meshesNames) {
  72337. meshesNames = null;
  72338. }
  72339. else if (!Array.isArray(meshesNames)) {
  72340. meshesNames = [meshesNames];
  72341. }
  72342. var hierarchyIds = new Array();
  72343. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72344. var loadedSkeletonsIds = [];
  72345. var loadedMaterialsIds = [];
  72346. var index;
  72347. var cache;
  72348. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72349. var parsedMesh = parsedData.meshes[index];
  72350. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  72351. if (meshesNames !== null) {
  72352. // Remove found mesh name from list.
  72353. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  72354. }
  72355. //Geometry?
  72356. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  72357. //does the file contain geometries?
  72358. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  72359. //find the correct geometry and add it to the scene
  72360. var found = false;
  72361. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  72362. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  72363. return;
  72364. }
  72365. else {
  72366. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  72367. if (parsedGeometryData.id === parsedMesh.geometryId) {
  72368. switch (geometryType) {
  72369. case "boxes":
  72370. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  72371. break;
  72372. case "spheres":
  72373. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  72374. break;
  72375. case "cylinders":
  72376. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  72377. break;
  72378. case "toruses":
  72379. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  72380. break;
  72381. case "grounds":
  72382. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  72383. break;
  72384. case "planes":
  72385. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  72386. break;
  72387. case "torusKnots":
  72388. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  72389. break;
  72390. case "vertexData":
  72391. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  72392. break;
  72393. }
  72394. found = true;
  72395. }
  72396. });
  72397. }
  72398. });
  72399. if (found === false) {
  72400. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  72401. }
  72402. }
  72403. }
  72404. // Material ?
  72405. if (parsedMesh.materialId) {
  72406. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  72407. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72408. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  72409. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  72410. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  72411. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  72412. var subMatId = parsedMultiMaterial.materials[matIndex];
  72413. loadedMaterialsIds.push(subMatId);
  72414. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  72415. if (mat) {
  72416. log += "\n\tMaterial " + mat.toString(fullDetails);
  72417. }
  72418. }
  72419. loadedMaterialsIds.push(parsedMultiMaterial.id);
  72420. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72421. if (mmat) {
  72422. materialFound = true;
  72423. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  72424. }
  72425. break;
  72426. }
  72427. }
  72428. }
  72429. if (materialFound === false) {
  72430. loadedMaterialsIds.push(parsedMesh.materialId);
  72431. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  72432. if (!mat) {
  72433. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  72434. }
  72435. else {
  72436. log += "\n\tMaterial " + mat.toString(fullDetails);
  72437. }
  72438. }
  72439. }
  72440. // Skeleton ?
  72441. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72442. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  72443. if (skeletonAlreadyLoaded === false) {
  72444. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  72445. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  72446. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  72447. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72448. skeletons.push(skeleton);
  72449. loadedSkeletonsIds.push(parsedSkeleton.id);
  72450. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  72451. }
  72452. }
  72453. }
  72454. }
  72455. // Morph targets ?
  72456. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72457. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72458. var managerData = _a[_i];
  72459. BABYLON.MorphTargetManager.Parse(managerData, scene);
  72460. }
  72461. }
  72462. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  72463. meshes.push(mesh);
  72464. log += "\n\tMesh " + mesh.toString(fullDetails);
  72465. }
  72466. }
  72467. // Connecting parents
  72468. var currentMesh;
  72469. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72470. currentMesh = scene.meshes[index];
  72471. if (currentMesh._waitingParentId) {
  72472. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  72473. currentMesh._waitingParentId = null;
  72474. }
  72475. }
  72476. // freeze and compute world matrix application
  72477. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72478. currentMesh = scene.meshes[index];
  72479. if (currentMesh._waitingFreezeWorldMatrix) {
  72480. currentMesh.freezeWorldMatrix();
  72481. currentMesh._waitingFreezeWorldMatrix = null;
  72482. }
  72483. else {
  72484. currentMesh.computeWorldMatrix(true);
  72485. }
  72486. }
  72487. }
  72488. // Particles
  72489. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  72490. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  72491. if (parser) {
  72492. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  72493. var parsedParticleSystem = parsedData.particleSystems[index];
  72494. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  72495. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  72496. }
  72497. }
  72498. }
  72499. }
  72500. return true;
  72501. }
  72502. catch (err) {
  72503. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  72504. if (onError) {
  72505. onError(msg, err);
  72506. }
  72507. else {
  72508. BABYLON.Tools.Log(msg);
  72509. throw err;
  72510. }
  72511. }
  72512. finally {
  72513. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72514. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72515. }
  72516. }
  72517. return false;
  72518. },
  72519. load: function (scene, data, rootUrl, onError) {
  72520. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72521. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72522. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72523. // and avoid problems with multiple concurrent .babylon loads.
  72524. var log = "importScene has failed JSON parse";
  72525. try {
  72526. var parsedData = JSON.parse(data);
  72527. log = "";
  72528. // Scene
  72529. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  72530. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  72531. }
  72532. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  72533. scene.autoClear = parsedData.autoClear;
  72534. }
  72535. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  72536. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  72537. }
  72538. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  72539. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  72540. }
  72541. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  72542. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  72543. }
  72544. // Fog
  72545. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  72546. scene.fogMode = parsedData.fogMode;
  72547. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  72548. scene.fogStart = parsedData.fogStart;
  72549. scene.fogEnd = parsedData.fogEnd;
  72550. scene.fogDensity = parsedData.fogDensity;
  72551. log += "\tFog mode for scene: ";
  72552. switch (scene.fogMode) {
  72553. // getters not compiling, so using hardcoded
  72554. case 1:
  72555. log += "exp\n";
  72556. break;
  72557. case 2:
  72558. log += "exp2\n";
  72559. break;
  72560. case 3:
  72561. log += "linear\n";
  72562. break;
  72563. }
  72564. }
  72565. //Physics
  72566. if (parsedData.physicsEnabled) {
  72567. var physicsPlugin;
  72568. if (parsedData.physicsEngine === "cannon") {
  72569. physicsPlugin = new BABYLON.CannonJSPlugin();
  72570. }
  72571. else if (parsedData.physicsEngine === "oimo") {
  72572. physicsPlugin = new BABYLON.OimoJSPlugin();
  72573. }
  72574. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  72575. //else - default engine, which is currently oimo
  72576. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  72577. scene.enablePhysics(physicsGravity, physicsPlugin);
  72578. }
  72579. // Metadata
  72580. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  72581. scene.metadata = parsedData.metadata;
  72582. }
  72583. //collisions, if defined. otherwise, default is true
  72584. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  72585. scene.collisionsEnabled = parsedData.collisionsEnabled;
  72586. }
  72587. scene.workerCollisions = !!parsedData.workerCollisions;
  72588. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  72589. if (!container) {
  72590. return false;
  72591. }
  72592. if (parsedData.autoAnimate) {
  72593. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  72594. }
  72595. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  72596. scene.setActiveCameraByID(parsedData.activeCameraID);
  72597. }
  72598. // Environment texture
  72599. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  72600. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  72601. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  72602. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  72603. if (parsedData.environmentTextureRotationY) {
  72604. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  72605. }
  72606. scene.environmentTexture = hdrTexture;
  72607. }
  72608. else {
  72609. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  72610. if (parsedData.environmentTextureRotationY) {
  72611. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  72612. }
  72613. scene.environmentTexture = cubeTexture;
  72614. }
  72615. if (parsedData.createDefaultSkybox === true) {
  72616. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  72617. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  72618. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  72619. }
  72620. }
  72621. // Finish
  72622. return true;
  72623. }
  72624. catch (err) {
  72625. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  72626. if (onError) {
  72627. onError(msg, err);
  72628. }
  72629. else {
  72630. BABYLON.Tools.Log(msg);
  72631. throw err;
  72632. }
  72633. }
  72634. finally {
  72635. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72636. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72637. }
  72638. }
  72639. return false;
  72640. },
  72641. loadAssetContainer: function (scene, data, rootUrl, onError) {
  72642. var container = loadAssetContainer(scene, data, rootUrl, onError);
  72643. return container;
  72644. }
  72645. });
  72646. })(BABYLON || (BABYLON = {}));
  72647. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  72648. var BABYLON;
  72649. (function (BABYLON) {
  72650. var FilesInput = /** @class */ (function () {
  72651. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  72652. this.onProcessFileCallback = function () { return true; };
  72653. this._engine = engine;
  72654. this._currentScene = scene;
  72655. this._sceneLoadedCallback = sceneLoadedCallback;
  72656. this._progressCallback = progressCallback;
  72657. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  72658. this._textureLoadingCallback = textureLoadingCallback;
  72659. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  72660. this._onReloadCallback = onReloadCallback;
  72661. this._errorCallback = errorCallback;
  72662. }
  72663. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  72664. var _this = this;
  72665. if (elementToMonitor) {
  72666. this._elementToMonitor = elementToMonitor;
  72667. this._dragEnterHandler = function (e) { _this.drag(e); };
  72668. this._dragOverHandler = function (e) { _this.drag(e); };
  72669. this._dropHandler = function (e) { _this.drop(e); };
  72670. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  72671. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  72672. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  72673. }
  72674. };
  72675. FilesInput.prototype.dispose = function () {
  72676. if (!this._elementToMonitor) {
  72677. return;
  72678. }
  72679. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  72680. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  72681. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  72682. };
  72683. FilesInput.prototype.renderFunction = function () {
  72684. if (this._additionalRenderLoopLogicCallback) {
  72685. this._additionalRenderLoopLogicCallback();
  72686. }
  72687. if (this._currentScene) {
  72688. if (this._textureLoadingCallback) {
  72689. var remaining = this._currentScene.getWaitingItemsCount();
  72690. if (remaining > 0) {
  72691. this._textureLoadingCallback(remaining);
  72692. }
  72693. }
  72694. this._currentScene.render();
  72695. }
  72696. };
  72697. FilesInput.prototype.drag = function (e) {
  72698. e.stopPropagation();
  72699. e.preventDefault();
  72700. };
  72701. FilesInput.prototype.drop = function (eventDrop) {
  72702. eventDrop.stopPropagation();
  72703. eventDrop.preventDefault();
  72704. this.loadFiles(eventDrop);
  72705. };
  72706. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  72707. var _this = this;
  72708. var reader = folder.createReader();
  72709. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  72710. reader.readEntries(function (entries) {
  72711. remaining.count += entries.length;
  72712. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  72713. var entry = entries_1[_i];
  72714. if (entry.isFile) {
  72715. entry.file(function (file) {
  72716. file.correctName = relativePath + file.name;
  72717. files.push(file);
  72718. if (--remaining.count === 0) {
  72719. callback();
  72720. }
  72721. });
  72722. }
  72723. else if (entry.isDirectory) {
  72724. _this._traverseFolder(entry, files, remaining, callback);
  72725. }
  72726. }
  72727. if (--remaining.count) {
  72728. callback();
  72729. }
  72730. });
  72731. };
  72732. FilesInput.prototype._processFiles = function (files) {
  72733. for (var i = 0; i < files.length; i++) {
  72734. var name = files[i].correctName.toLowerCase();
  72735. var extension = name.split('.').pop();
  72736. if (!this.onProcessFileCallback(files[i], name, extension)) {
  72737. continue;
  72738. }
  72739. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  72740. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  72741. this._sceneFileToLoad = files[i];
  72742. }
  72743. else {
  72744. FilesInput.FilesToLoad[name] = files[i];
  72745. }
  72746. }
  72747. };
  72748. FilesInput.prototype.loadFiles = function (event) {
  72749. var _this = this;
  72750. // Handling data transfer via drag'n'drop
  72751. if (event && event.dataTransfer && event.dataTransfer.files) {
  72752. this._filesToLoad = event.dataTransfer.files;
  72753. }
  72754. // Handling files from input files
  72755. if (event && event.target && event.target.files) {
  72756. this._filesToLoad = event.target.files;
  72757. }
  72758. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  72759. return;
  72760. }
  72761. if (this._startingProcessingFilesCallback) {
  72762. this._startingProcessingFilesCallback(this._filesToLoad);
  72763. }
  72764. if (this._filesToLoad && this._filesToLoad.length > 0) {
  72765. var files_1 = new Array();
  72766. var folders = [];
  72767. var items = event.dataTransfer ? event.dataTransfer.items : null;
  72768. for (var i = 0; i < this._filesToLoad.length; i++) {
  72769. var fileToLoad = this._filesToLoad[i];
  72770. var name_1 = fileToLoad.name.toLowerCase();
  72771. var entry = void 0;
  72772. fileToLoad.correctName = name_1;
  72773. if (items) {
  72774. var item = items[i];
  72775. if (item.getAsEntry) {
  72776. entry = item.getAsEntry();
  72777. }
  72778. else if (item.webkitGetAsEntry) {
  72779. entry = item.webkitGetAsEntry();
  72780. }
  72781. }
  72782. if (!entry) {
  72783. files_1.push(fileToLoad);
  72784. }
  72785. else {
  72786. if (entry.isDirectory) {
  72787. folders.push(entry);
  72788. }
  72789. else {
  72790. files_1.push(fileToLoad);
  72791. }
  72792. }
  72793. }
  72794. if (folders.length === 0) {
  72795. this._processFiles(files_1);
  72796. this._processReload();
  72797. }
  72798. else {
  72799. var remaining = { count: folders.length };
  72800. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  72801. var folder = folders_1[_i];
  72802. this._traverseFolder(folder, files_1, remaining, function () {
  72803. _this._processFiles(files_1);
  72804. if (remaining.count === 0) {
  72805. _this._processReload();
  72806. }
  72807. });
  72808. }
  72809. }
  72810. }
  72811. };
  72812. FilesInput.prototype._processReload = function () {
  72813. if (this._onReloadCallback) {
  72814. this._onReloadCallback(this._sceneFileToLoad);
  72815. }
  72816. else {
  72817. this.reload();
  72818. }
  72819. };
  72820. FilesInput.prototype.reload = function () {
  72821. var _this = this;
  72822. // If a scene file has been provided
  72823. if (this._sceneFileToLoad) {
  72824. if (this._currentScene) {
  72825. if (BABYLON.Tools.errorsCount > 0) {
  72826. BABYLON.Tools.ClearLogCache();
  72827. }
  72828. this._engine.stopRenderLoop();
  72829. }
  72830. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  72831. if (_this._progressCallback) {
  72832. _this._progressCallback(progress);
  72833. }
  72834. }).then(function (scene) {
  72835. if (_this._currentScene) {
  72836. _this._currentScene.dispose();
  72837. }
  72838. _this._currentScene = scene;
  72839. if (_this._sceneLoadedCallback) {
  72840. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  72841. }
  72842. // Wait for textures and shaders to be ready
  72843. _this._currentScene.executeWhenReady(function () {
  72844. _this._engine.runRenderLoop(function () {
  72845. _this.renderFunction();
  72846. });
  72847. });
  72848. }).catch(function (error) {
  72849. if (_this._errorCallback) {
  72850. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  72851. }
  72852. });
  72853. }
  72854. else {
  72855. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  72856. }
  72857. };
  72858. FilesInput.FilesToLoad = {};
  72859. return FilesInput;
  72860. }());
  72861. BABYLON.FilesInput = FilesInput;
  72862. })(BABYLON || (BABYLON = {}));
  72863. //# sourceMappingURL=babylon.filesInput.js.map
  72864. var BABYLON;
  72865. (function (BABYLON) {
  72866. var Tags = /** @class */ (function () {
  72867. function Tags() {
  72868. }
  72869. Tags.EnableFor = function (obj) {
  72870. obj._tags = obj._tags || {};
  72871. obj.hasTags = function () {
  72872. return Tags.HasTags(obj);
  72873. };
  72874. obj.addTags = function (tagsString) {
  72875. return Tags.AddTagsTo(obj, tagsString);
  72876. };
  72877. obj.removeTags = function (tagsString) {
  72878. return Tags.RemoveTagsFrom(obj, tagsString);
  72879. };
  72880. obj.matchesTagsQuery = function (tagsQuery) {
  72881. return Tags.MatchesQuery(obj, tagsQuery);
  72882. };
  72883. };
  72884. Tags.DisableFor = function (obj) {
  72885. delete obj._tags;
  72886. delete obj.hasTags;
  72887. delete obj.addTags;
  72888. delete obj.removeTags;
  72889. delete obj.matchesTagsQuery;
  72890. };
  72891. Tags.HasTags = function (obj) {
  72892. if (!obj._tags) {
  72893. return false;
  72894. }
  72895. return !BABYLON.Tools.IsEmpty(obj._tags);
  72896. };
  72897. Tags.GetTags = function (obj, asString) {
  72898. if (asString === void 0) { asString = true; }
  72899. if (!obj._tags) {
  72900. return null;
  72901. }
  72902. if (asString) {
  72903. var tagsArray = [];
  72904. for (var tag in obj._tags) {
  72905. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  72906. tagsArray.push(tag);
  72907. }
  72908. }
  72909. return tagsArray.join(" ");
  72910. }
  72911. else {
  72912. return obj._tags;
  72913. }
  72914. };
  72915. // the tags 'true' and 'false' are reserved and cannot be used as tags
  72916. // a tag cannot start with '||', '&&', and '!'
  72917. // it cannot contain whitespaces
  72918. Tags.AddTagsTo = function (obj, tagsString) {
  72919. if (!tagsString) {
  72920. return;
  72921. }
  72922. if (typeof tagsString !== "string") {
  72923. return;
  72924. }
  72925. var tags = tagsString.split(" ");
  72926. tags.forEach(function (tag, index, array) {
  72927. Tags._AddTagTo(obj, tag);
  72928. });
  72929. };
  72930. Tags._AddTagTo = function (obj, tag) {
  72931. tag = tag.trim();
  72932. if (tag === "" || tag === "true" || tag === "false") {
  72933. return;
  72934. }
  72935. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  72936. return;
  72937. }
  72938. Tags.EnableFor(obj);
  72939. obj._tags[tag] = true;
  72940. };
  72941. Tags.RemoveTagsFrom = function (obj, tagsString) {
  72942. if (!Tags.HasTags(obj)) {
  72943. return;
  72944. }
  72945. var tags = tagsString.split(" ");
  72946. for (var t in tags) {
  72947. Tags._RemoveTagFrom(obj, tags[t]);
  72948. }
  72949. };
  72950. Tags._RemoveTagFrom = function (obj, tag) {
  72951. delete obj._tags[tag];
  72952. };
  72953. Tags.MatchesQuery = function (obj, tagsQuery) {
  72954. if (tagsQuery === undefined) {
  72955. return true;
  72956. }
  72957. if (tagsQuery === "") {
  72958. return Tags.HasTags(obj);
  72959. }
  72960. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  72961. };
  72962. return Tags;
  72963. }());
  72964. BABYLON.Tags = Tags;
  72965. })(BABYLON || (BABYLON = {}));
  72966. //# sourceMappingURL=babylon.tags.js.map
  72967. var BABYLON;
  72968. (function (BABYLON) {
  72969. /**
  72970. * Class used to evalaute queries containing `and` and `or` operators
  72971. */
  72972. var AndOrNotEvaluator = /** @class */ (function () {
  72973. function AndOrNotEvaluator() {
  72974. }
  72975. /**
  72976. * Evaluate a query
  72977. * @param query defines the query to evaluate
  72978. * @param evaluateCallback defines the callback used to filter result
  72979. * @returns true if the query matches
  72980. */
  72981. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  72982. if (!query.match(/\([^\(\)]*\)/g)) {
  72983. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  72984. }
  72985. else {
  72986. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  72987. // remove parenthesis
  72988. r = r.slice(1, r.length - 1);
  72989. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  72990. });
  72991. }
  72992. if (query === "true") {
  72993. return true;
  72994. }
  72995. if (query === "false") {
  72996. return false;
  72997. }
  72998. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  72999. };
  73000. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  73001. evaluateCallback = evaluateCallback || (function (r) {
  73002. return r === "true" ? true : false;
  73003. });
  73004. var result;
  73005. var or = parenthesisContent.split("||");
  73006. for (var i in or) {
  73007. if (or.hasOwnProperty(i)) {
  73008. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  73009. var and = ori.split("&&");
  73010. if (and.length > 1) {
  73011. for (var j = 0; j < and.length; ++j) {
  73012. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  73013. if (andj !== "true" && andj !== "false") {
  73014. if (andj[0] === "!") {
  73015. result = !evaluateCallback(andj.substring(1));
  73016. }
  73017. else {
  73018. result = evaluateCallback(andj);
  73019. }
  73020. }
  73021. else {
  73022. result = andj === "true" ? true : false;
  73023. }
  73024. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  73025. ori = "false";
  73026. break;
  73027. }
  73028. }
  73029. }
  73030. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  73031. result = true;
  73032. break;
  73033. }
  73034. // result equals false (or undefined)
  73035. if (ori !== "true" && ori !== "false") {
  73036. if (ori[0] === "!") {
  73037. result = !evaluateCallback(ori.substring(1));
  73038. }
  73039. else {
  73040. result = evaluateCallback(ori);
  73041. }
  73042. }
  73043. else {
  73044. result = ori === "true" ? true : false;
  73045. }
  73046. }
  73047. }
  73048. // the whole parenthesis scope is replaced by 'true' or 'false'
  73049. return result ? "true" : "false";
  73050. };
  73051. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  73052. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  73053. // remove whitespaces
  73054. r = r.replace(/[\s]/g, function () { return ""; });
  73055. return r.length % 2 ? "!" : "";
  73056. });
  73057. booleanString = booleanString.trim();
  73058. if (booleanString === "!true") {
  73059. booleanString = "false";
  73060. }
  73061. else if (booleanString === "!false") {
  73062. booleanString = "true";
  73063. }
  73064. return booleanString;
  73065. };
  73066. return AndOrNotEvaluator;
  73067. }());
  73068. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  73069. })(BABYLON || (BABYLON = {}));
  73070. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  73071. var BABYLON;
  73072. (function (BABYLON) {
  73073. /**
  73074. * Class used to enable access to IndexedDB
  73075. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  73076. */
  73077. var Database = /** @class */ (function () {
  73078. /**
  73079. * Creates a new Database
  73080. * @param urlToScene defines the url to load the scene
  73081. * @param callbackManifestChecked defines the callback to use when manifest is checked
  73082. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  73083. */
  73084. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  73085. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  73086. var _this = this;
  73087. // Handling various flavors of prefixed version of IndexedDB
  73088. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  73089. this.callbackManifestChecked = callbackManifestChecked;
  73090. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  73091. this.db = null;
  73092. this._enableSceneOffline = false;
  73093. this._enableTexturesOffline = false;
  73094. this.manifestVersionFound = 0;
  73095. this.mustUpdateRessources = false;
  73096. this.hasReachedQuota = false;
  73097. if (!Database.IDBStorageEnabled) {
  73098. this.callbackManifestChecked(true);
  73099. }
  73100. else {
  73101. if (disableManifestCheck) {
  73102. this._enableSceneOffline = true;
  73103. this._enableTexturesOffline = true;
  73104. this.manifestVersionFound = 1;
  73105. BABYLON.Tools.SetImmediate(function () {
  73106. _this.callbackManifestChecked(true);
  73107. });
  73108. }
  73109. else {
  73110. this._checkManifestFile();
  73111. }
  73112. }
  73113. }
  73114. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  73115. /**
  73116. * Gets a boolean indicating if scene must be saved in the database
  73117. */
  73118. get: function () {
  73119. return this._enableSceneOffline;
  73120. },
  73121. enumerable: true,
  73122. configurable: true
  73123. });
  73124. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  73125. /**
  73126. * Gets a boolean indicating if textures must be saved in the database
  73127. */
  73128. get: function () {
  73129. return this._enableTexturesOffline;
  73130. },
  73131. enumerable: true,
  73132. configurable: true
  73133. });
  73134. Database.prototype._checkManifestFile = function () {
  73135. var _this = this;
  73136. var noManifestFile = function () {
  73137. _this._enableSceneOffline = false;
  73138. _this._enableTexturesOffline = false;
  73139. _this.callbackManifestChecked(false);
  73140. };
  73141. var timeStampUsed = false;
  73142. var manifestURL = this.currentSceneUrl + ".manifest";
  73143. var xhr = new XMLHttpRequest();
  73144. if (navigator.onLine) {
  73145. // Adding a timestamp to by-pass browsers' cache
  73146. timeStampUsed = true;
  73147. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  73148. }
  73149. xhr.open("GET", manifestURL, true);
  73150. xhr.addEventListener("load", function () {
  73151. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73152. try {
  73153. var manifestFile = JSON.parse(xhr.response);
  73154. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  73155. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  73156. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  73157. _this.manifestVersionFound = manifestFile.version;
  73158. }
  73159. if (_this.callbackManifestChecked) {
  73160. _this.callbackManifestChecked(true);
  73161. }
  73162. }
  73163. catch (ex) {
  73164. noManifestFile();
  73165. }
  73166. }
  73167. else {
  73168. noManifestFile();
  73169. }
  73170. }, false);
  73171. xhr.addEventListener("error", function (event) {
  73172. if (timeStampUsed) {
  73173. timeStampUsed = false;
  73174. // Let's retry without the timeStamp
  73175. // It could fail when coupled with HTML5 Offline API
  73176. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  73177. xhr.open("GET", retryManifestURL, true);
  73178. xhr.send();
  73179. }
  73180. else {
  73181. noManifestFile();
  73182. }
  73183. }, false);
  73184. try {
  73185. xhr.send();
  73186. }
  73187. catch (ex) {
  73188. BABYLON.Tools.Error("Error on XHR send request.");
  73189. this.callbackManifestChecked(false);
  73190. }
  73191. };
  73192. /**
  73193. * Open the database and make it available
  73194. * @param successCallback defines the callback to call on success
  73195. * @param errorCallback defines the callback to call on error
  73196. */
  73197. Database.prototype.openAsync = function (successCallback, errorCallback) {
  73198. var _this = this;
  73199. var handleError = function () {
  73200. _this.isSupported = false;
  73201. if (errorCallback)
  73202. errorCallback();
  73203. };
  73204. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  73205. // Your browser doesn't support IndexedDB
  73206. this.isSupported = false;
  73207. if (errorCallback)
  73208. errorCallback();
  73209. }
  73210. else {
  73211. // If the DB hasn't been opened or created yet
  73212. if (!this.db) {
  73213. this.hasReachedQuota = false;
  73214. this.isSupported = true;
  73215. var request = this.idbFactory.open("babylonjs", 1);
  73216. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  73217. request.onerror = function (event) {
  73218. handleError();
  73219. };
  73220. // executes when a version change transaction cannot complete due to other active transactions
  73221. request.onblocked = function (event) {
  73222. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  73223. handleError();
  73224. };
  73225. // DB has been opened successfully
  73226. request.onsuccess = function (event) {
  73227. _this.db = request.result;
  73228. successCallback();
  73229. };
  73230. // Initialization of the DB. Creating Scenes & Textures stores
  73231. request.onupgradeneeded = function (event) {
  73232. _this.db = (event.target).result;
  73233. if (_this.db) {
  73234. try {
  73235. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  73236. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  73237. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  73238. }
  73239. catch (ex) {
  73240. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  73241. handleError();
  73242. }
  73243. }
  73244. };
  73245. }
  73246. // DB has already been created and opened
  73247. else {
  73248. if (successCallback)
  73249. successCallback();
  73250. }
  73251. }
  73252. };
  73253. /**
  73254. * Loads an image from the database
  73255. * @param url defines the url to load from
  73256. * @param image defines the target DOM image
  73257. */
  73258. Database.prototype.loadImageFromDB = function (url, image) {
  73259. var _this = this;
  73260. var completeURL = Database._ReturnFullUrlLocation(url);
  73261. var saveAndLoadImage = function () {
  73262. if (!_this.hasReachedQuota && _this.db !== null) {
  73263. // the texture is not yet in the DB, let's try to save it
  73264. _this._saveImageIntoDBAsync(completeURL, image);
  73265. }
  73266. // If the texture is not in the DB and we've reached the DB quota limit
  73267. // let's load it directly from the web
  73268. else {
  73269. image.src = url;
  73270. }
  73271. };
  73272. if (!this.mustUpdateRessources) {
  73273. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  73274. }
  73275. // First time we're download the images or update requested in the manifest file by a version change
  73276. else {
  73277. saveAndLoadImage();
  73278. }
  73279. };
  73280. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  73281. if (this.isSupported && this.db !== null) {
  73282. var texture;
  73283. var transaction = this.db.transaction(["textures"]);
  73284. transaction.onabort = function (event) {
  73285. image.src = url;
  73286. };
  73287. transaction.oncomplete = function (event) {
  73288. var blobTextureURL;
  73289. if (texture) {
  73290. var URL = window.URL || window.webkitURL;
  73291. blobTextureURL = URL.createObjectURL(texture.data);
  73292. image.onerror = function () {
  73293. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  73294. image.src = url;
  73295. };
  73296. image.src = blobTextureURL;
  73297. }
  73298. else {
  73299. notInDBCallback();
  73300. }
  73301. };
  73302. var getRequest = transaction.objectStore("textures").get(url);
  73303. getRequest.onsuccess = function (event) {
  73304. texture = (event.target).result;
  73305. };
  73306. getRequest.onerror = function (event) {
  73307. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  73308. image.src = url;
  73309. };
  73310. }
  73311. else {
  73312. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73313. image.src = url;
  73314. }
  73315. };
  73316. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  73317. var _this = this;
  73318. if (this.isSupported) {
  73319. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  73320. var generateBlobUrl = function () {
  73321. var blobTextureURL;
  73322. if (blob) {
  73323. var URL = window.URL || window.webkitURL;
  73324. try {
  73325. blobTextureURL = URL.createObjectURL(blob);
  73326. }
  73327. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  73328. catch (ex) {
  73329. blobTextureURL = URL.createObjectURL(blob);
  73330. }
  73331. }
  73332. if (blobTextureURL) {
  73333. image.src = blobTextureURL;
  73334. }
  73335. };
  73336. if (Database.IsUASupportingBlobStorage) { // Create XHR
  73337. var xhr = new XMLHttpRequest(), blob;
  73338. xhr.open("GET", url, true);
  73339. xhr.responseType = "blob";
  73340. xhr.addEventListener("load", function () {
  73341. if (xhr.status === 200 && _this.db) {
  73342. // Blob as response (XHR2)
  73343. blob = xhr.response;
  73344. var transaction = _this.db.transaction(["textures"], "readwrite");
  73345. // the transaction could abort because of a QuotaExceededError error
  73346. transaction.onabort = function (event) {
  73347. try {
  73348. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73349. var srcElement = (event.srcElement || event.target);
  73350. var error = srcElement.error;
  73351. if (error && error.name === "QuotaExceededError") {
  73352. _this.hasReachedQuota = true;
  73353. }
  73354. }
  73355. catch (ex) { }
  73356. generateBlobUrl();
  73357. };
  73358. transaction.oncomplete = function (event) {
  73359. generateBlobUrl();
  73360. };
  73361. var newTexture = { textureUrl: url, data: blob };
  73362. try {
  73363. // Put the blob into the dabase
  73364. var addRequest = transaction.objectStore("textures").put(newTexture);
  73365. addRequest.onsuccess = function (event) {
  73366. };
  73367. addRequest.onerror = function (event) {
  73368. generateBlobUrl();
  73369. };
  73370. }
  73371. catch (ex) {
  73372. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  73373. if (ex.code === 25) {
  73374. Database.IsUASupportingBlobStorage = false;
  73375. }
  73376. image.src = url;
  73377. }
  73378. }
  73379. else {
  73380. image.src = url;
  73381. }
  73382. }, false);
  73383. xhr.addEventListener("error", function (event) {
  73384. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  73385. image.src = url;
  73386. }, false);
  73387. xhr.send();
  73388. }
  73389. else {
  73390. image.src = url;
  73391. }
  73392. }
  73393. else {
  73394. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73395. image.src = url;
  73396. }
  73397. };
  73398. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  73399. var _this = this;
  73400. var updateVersion = function () {
  73401. // the version is not yet in the DB or we need to update it
  73402. _this._saveVersionIntoDBAsync(url, versionLoaded);
  73403. };
  73404. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  73405. };
  73406. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  73407. var _this = this;
  73408. if (this.isSupported && this.db) {
  73409. var version;
  73410. try {
  73411. var transaction = this.db.transaction(["versions"]);
  73412. transaction.oncomplete = function (event) {
  73413. if (version) {
  73414. // If the version in the JSON file is different from the version in DB
  73415. if (_this.manifestVersionFound !== version.data) {
  73416. _this.mustUpdateRessources = true;
  73417. updateInDBCallback();
  73418. }
  73419. else {
  73420. callback(version.data);
  73421. }
  73422. }
  73423. // version was not found in DB
  73424. else {
  73425. _this.mustUpdateRessources = true;
  73426. updateInDBCallback();
  73427. }
  73428. };
  73429. transaction.onabort = function (event) {
  73430. callback(-1);
  73431. };
  73432. var getRequest = transaction.objectStore("versions").get(url);
  73433. getRequest.onsuccess = function (event) {
  73434. version = (event.target).result;
  73435. };
  73436. getRequest.onerror = function (event) {
  73437. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  73438. callback(-1);
  73439. };
  73440. }
  73441. catch (ex) {
  73442. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  73443. callback(-1);
  73444. }
  73445. }
  73446. else {
  73447. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73448. callback(-1);
  73449. }
  73450. };
  73451. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  73452. var _this = this;
  73453. if (this.isSupported && !this.hasReachedQuota && this.db) {
  73454. try {
  73455. // Open a transaction to the database
  73456. var transaction = this.db.transaction(["versions"], "readwrite");
  73457. // the transaction could abort because of a QuotaExceededError error
  73458. transaction.onabort = function (event) {
  73459. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73460. var error = event.srcElement['error'];
  73461. if (error && error.name === "QuotaExceededError") {
  73462. _this.hasReachedQuota = true;
  73463. }
  73464. }
  73465. catch (ex) { }
  73466. callback(-1);
  73467. };
  73468. transaction.oncomplete = function (event) {
  73469. callback(_this.manifestVersionFound);
  73470. };
  73471. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  73472. // Put the scene into the database
  73473. var addRequest = transaction.objectStore("versions").put(newVersion);
  73474. addRequest.onsuccess = function (event) {
  73475. };
  73476. addRequest.onerror = function (event) {
  73477. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  73478. };
  73479. }
  73480. catch (ex) {
  73481. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  73482. callback(-1);
  73483. }
  73484. }
  73485. else {
  73486. callback(-1);
  73487. }
  73488. };
  73489. /**
  73490. * Loads a file from database
  73491. * @param url defines the URL to load from
  73492. * @param sceneLoaded defines a callback to call on success
  73493. * @param progressCallBack defines a callback to call when progress changed
  73494. * @param errorCallback defines a callback to call on error
  73495. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  73496. */
  73497. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  73498. var _this = this;
  73499. var completeUrl = Database._ReturnFullUrlLocation(url);
  73500. var saveAndLoadFile = function () {
  73501. // the scene is not yet in the DB, let's try to save it
  73502. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73503. };
  73504. this._checkVersionFromDB(completeUrl, function (version) {
  73505. if (version !== -1) {
  73506. if (!_this.mustUpdateRessources) {
  73507. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  73508. }
  73509. else {
  73510. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73511. }
  73512. }
  73513. else {
  73514. if (errorCallback) {
  73515. errorCallback();
  73516. }
  73517. }
  73518. });
  73519. };
  73520. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  73521. if (this.isSupported && this.db) {
  73522. var targetStore;
  73523. if (url.indexOf(".babylon") !== -1) {
  73524. targetStore = "scenes";
  73525. }
  73526. else {
  73527. targetStore = "textures";
  73528. }
  73529. var file;
  73530. var transaction = this.db.transaction([targetStore]);
  73531. transaction.oncomplete = function (event) {
  73532. if (file) {
  73533. callback(file.data);
  73534. }
  73535. // file was not found in DB
  73536. else {
  73537. notInDBCallback();
  73538. }
  73539. };
  73540. transaction.onabort = function (event) {
  73541. notInDBCallback();
  73542. };
  73543. var getRequest = transaction.objectStore(targetStore).get(url);
  73544. getRequest.onsuccess = function (event) {
  73545. file = (event.target).result;
  73546. };
  73547. getRequest.onerror = function (event) {
  73548. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  73549. notInDBCallback();
  73550. };
  73551. }
  73552. else {
  73553. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73554. callback();
  73555. }
  73556. };
  73557. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  73558. var _this = this;
  73559. if (this.isSupported) {
  73560. var targetStore;
  73561. if (url.indexOf(".babylon") !== -1) {
  73562. targetStore = "scenes";
  73563. }
  73564. else {
  73565. targetStore = "textures";
  73566. }
  73567. // Create XHR
  73568. var xhr = new XMLHttpRequest();
  73569. var fileData;
  73570. xhr.open("GET", url + "?" + Date.now(), true);
  73571. if (useArrayBuffer) {
  73572. xhr.responseType = "arraybuffer";
  73573. }
  73574. if (progressCallback) {
  73575. xhr.onprogress = progressCallback;
  73576. }
  73577. xhr.addEventListener("load", function () {
  73578. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  73579. // Blob as response (XHR2)
  73580. //fileData = xhr.responseText;
  73581. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  73582. if (!_this.hasReachedQuota && _this.db) {
  73583. // Open a transaction to the database
  73584. var transaction = _this.db.transaction([targetStore], "readwrite");
  73585. // the transaction could abort because of a QuotaExceededError error
  73586. transaction.onabort = function (event) {
  73587. try {
  73588. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73589. var error = event.srcElement['error'];
  73590. if (error && error.name === "QuotaExceededError") {
  73591. _this.hasReachedQuota = true;
  73592. }
  73593. }
  73594. catch (ex) { }
  73595. callback(fileData);
  73596. };
  73597. transaction.oncomplete = function (event) {
  73598. callback(fileData);
  73599. };
  73600. var newFile;
  73601. if (targetStore === "scenes") {
  73602. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  73603. }
  73604. else {
  73605. newFile = { textureUrl: url, data: fileData };
  73606. }
  73607. try {
  73608. // Put the scene into the database
  73609. var addRequest = transaction.objectStore(targetStore).put(newFile);
  73610. addRequest.onsuccess = function (event) {
  73611. };
  73612. addRequest.onerror = function (event) {
  73613. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  73614. };
  73615. }
  73616. catch (ex) {
  73617. callback(fileData);
  73618. }
  73619. }
  73620. else {
  73621. callback(fileData);
  73622. }
  73623. }
  73624. else {
  73625. if (xhr.status >= 400 && errorCallback) {
  73626. errorCallback(xhr);
  73627. }
  73628. else {
  73629. callback();
  73630. }
  73631. }
  73632. }, false);
  73633. xhr.addEventListener("error", function (event) {
  73634. BABYLON.Tools.Error("error on XHR request.");
  73635. callback();
  73636. }, false);
  73637. xhr.send();
  73638. }
  73639. else {
  73640. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73641. callback();
  73642. }
  73643. };
  73644. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  73645. Database.IsUASupportingBlobStorage = true;
  73646. /** Gets a boolean indicating if Database storate is enabled */
  73647. Database.IDBStorageEnabled = true;
  73648. Database._ParseURL = function (url) {
  73649. var a = document.createElement('a');
  73650. a.href = url;
  73651. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  73652. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  73653. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  73654. return absLocation;
  73655. };
  73656. Database._ReturnFullUrlLocation = function (url) {
  73657. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  73658. return (Database._ParseURL(window.location.href) + url);
  73659. }
  73660. else {
  73661. return url;
  73662. }
  73663. };
  73664. return Database;
  73665. }());
  73666. BABYLON.Database = Database;
  73667. })(BABYLON || (BABYLON = {}));
  73668. //# sourceMappingURL=babylon.database.js.map
  73669. var BABYLON;
  73670. (function (BABYLON) {
  73671. var FresnelParameters = /** @class */ (function () {
  73672. function FresnelParameters() {
  73673. this._isEnabled = true;
  73674. this.leftColor = BABYLON.Color3.White();
  73675. this.rightColor = BABYLON.Color3.Black();
  73676. this.bias = 0;
  73677. this.power = 1;
  73678. }
  73679. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  73680. get: function () {
  73681. return this._isEnabled;
  73682. },
  73683. set: function (value) {
  73684. if (this._isEnabled === value) {
  73685. return;
  73686. }
  73687. this._isEnabled = value;
  73688. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  73689. },
  73690. enumerable: true,
  73691. configurable: true
  73692. });
  73693. FresnelParameters.prototype.clone = function () {
  73694. var newFresnelParameters = new FresnelParameters();
  73695. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  73696. return newFresnelParameters;
  73697. };
  73698. FresnelParameters.prototype.serialize = function () {
  73699. var serializationObject = {};
  73700. serializationObject.isEnabled = this.isEnabled;
  73701. serializationObject.leftColor = this.leftColor.asArray();
  73702. serializationObject.rightColor = this.rightColor.asArray();
  73703. serializationObject.bias = this.bias;
  73704. serializationObject.power = this.power;
  73705. return serializationObject;
  73706. };
  73707. FresnelParameters.Parse = function (parsedFresnelParameters) {
  73708. var fresnelParameters = new FresnelParameters();
  73709. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  73710. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  73711. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  73712. fresnelParameters.bias = parsedFresnelParameters.bias;
  73713. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  73714. return fresnelParameters;
  73715. };
  73716. return FresnelParameters;
  73717. }());
  73718. BABYLON.FresnelParameters = FresnelParameters;
  73719. })(BABYLON || (BABYLON = {}));
  73720. //# sourceMappingURL=babylon.fresnelParameters.js.map
  73721. var BABYLON;
  73722. (function (BABYLON) {
  73723. var MultiMaterial = /** @class */ (function (_super) {
  73724. __extends(MultiMaterial, _super);
  73725. function MultiMaterial(name, scene) {
  73726. var _this = _super.call(this, name, scene, true) || this;
  73727. scene.multiMaterials.push(_this);
  73728. _this.subMaterials = new Array();
  73729. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  73730. return _this;
  73731. }
  73732. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  73733. get: function () {
  73734. return this._subMaterials;
  73735. },
  73736. set: function (value) {
  73737. this._subMaterials = value;
  73738. this._hookArray(value);
  73739. },
  73740. enumerable: true,
  73741. configurable: true
  73742. });
  73743. MultiMaterial.prototype._hookArray = function (array) {
  73744. var _this = this;
  73745. var oldPush = array.push;
  73746. array.push = function () {
  73747. var items = [];
  73748. for (var _i = 0; _i < arguments.length; _i++) {
  73749. items[_i] = arguments[_i];
  73750. }
  73751. var result = oldPush.apply(array, items);
  73752. _this._markAllSubMeshesAsTexturesDirty();
  73753. return result;
  73754. };
  73755. var oldSplice = array.splice;
  73756. array.splice = function (index, deleteCount) {
  73757. var deleted = oldSplice.apply(array, [index, deleteCount]);
  73758. _this._markAllSubMeshesAsTexturesDirty();
  73759. return deleted;
  73760. };
  73761. };
  73762. // Properties
  73763. MultiMaterial.prototype.getSubMaterial = function (index) {
  73764. if (index < 0 || index >= this.subMaterials.length) {
  73765. return this.getScene().defaultMaterial;
  73766. }
  73767. return this.subMaterials[index];
  73768. };
  73769. MultiMaterial.prototype.getActiveTextures = function () {
  73770. var _a;
  73771. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  73772. if (subMaterial) {
  73773. return subMaterial.getActiveTextures();
  73774. }
  73775. else {
  73776. return [];
  73777. }
  73778. }));
  73779. };
  73780. // Methods
  73781. MultiMaterial.prototype.getClassName = function () {
  73782. return "MultiMaterial";
  73783. };
  73784. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  73785. for (var index = 0; index < this.subMaterials.length; index++) {
  73786. var subMaterial = this.subMaterials[index];
  73787. if (subMaterial) {
  73788. if (subMaterial.storeEffectOnSubMeshes) {
  73789. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  73790. return false;
  73791. }
  73792. continue;
  73793. }
  73794. if (!subMaterial.isReady(mesh)) {
  73795. return false;
  73796. }
  73797. }
  73798. }
  73799. return true;
  73800. };
  73801. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  73802. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  73803. for (var index = 0; index < this.subMaterials.length; index++) {
  73804. var subMaterial = null;
  73805. var current = this.subMaterials[index];
  73806. if (cloneChildren && current) {
  73807. subMaterial = current.clone(name + "-" + current.name);
  73808. }
  73809. else {
  73810. subMaterial = this.subMaterials[index];
  73811. }
  73812. newMultiMaterial.subMaterials.push(subMaterial);
  73813. }
  73814. return newMultiMaterial;
  73815. };
  73816. MultiMaterial.prototype.serialize = function () {
  73817. var serializationObject = {};
  73818. serializationObject.name = this.name;
  73819. serializationObject.id = this.id;
  73820. if (BABYLON.Tags) {
  73821. serializationObject.tags = BABYLON.Tags.GetTags(this);
  73822. }
  73823. serializationObject.materials = [];
  73824. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  73825. var subMat = this.subMaterials[matIndex];
  73826. if (subMat) {
  73827. serializationObject.materials.push(subMat.id);
  73828. }
  73829. else {
  73830. serializationObject.materials.push(null);
  73831. }
  73832. }
  73833. return serializationObject;
  73834. };
  73835. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  73836. var scene = this.getScene();
  73837. if (!scene) {
  73838. return;
  73839. }
  73840. var index = scene.multiMaterials.indexOf(this);
  73841. if (index >= 0) {
  73842. scene.multiMaterials.splice(index, 1);
  73843. }
  73844. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  73845. };
  73846. return MultiMaterial;
  73847. }(BABYLON.Material));
  73848. BABYLON.MultiMaterial = MultiMaterial;
  73849. })(BABYLON || (BABYLON = {}));
  73850. //# sourceMappingURL=babylon.multiMaterial.js.map
  73851. var BABYLON;
  73852. (function (BABYLON) {
  73853. var FreeCameraTouchInput = /** @class */ (function () {
  73854. function FreeCameraTouchInput() {
  73855. this._offsetX = null;
  73856. this._offsetY = null;
  73857. this._pointerPressed = new Array();
  73858. this.touchAngularSensibility = 200000.0;
  73859. this.touchMoveSensibility = 250.0;
  73860. }
  73861. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  73862. var _this = this;
  73863. var previousPosition = null;
  73864. if (this._pointerInput === undefined) {
  73865. this._onLostFocus = function (evt) {
  73866. _this._offsetX = null;
  73867. _this._offsetY = null;
  73868. };
  73869. this._pointerInput = function (p, s) {
  73870. var evt = p.event;
  73871. if (evt.pointerType === "mouse") {
  73872. return;
  73873. }
  73874. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73875. if (!noPreventDefault) {
  73876. evt.preventDefault();
  73877. }
  73878. _this._pointerPressed.push(evt.pointerId);
  73879. if (_this._pointerPressed.length !== 1) {
  73880. return;
  73881. }
  73882. previousPosition = {
  73883. x: evt.clientX,
  73884. y: evt.clientY
  73885. };
  73886. }
  73887. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  73888. if (!noPreventDefault) {
  73889. evt.preventDefault();
  73890. }
  73891. var index = _this._pointerPressed.indexOf(evt.pointerId);
  73892. if (index === -1) {
  73893. return;
  73894. }
  73895. _this._pointerPressed.splice(index, 1);
  73896. if (index != 0) {
  73897. return;
  73898. }
  73899. previousPosition = null;
  73900. _this._offsetX = null;
  73901. _this._offsetY = null;
  73902. }
  73903. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  73904. if (!noPreventDefault) {
  73905. evt.preventDefault();
  73906. }
  73907. if (!previousPosition) {
  73908. return;
  73909. }
  73910. var index = _this._pointerPressed.indexOf(evt.pointerId);
  73911. if (index != 0) {
  73912. return;
  73913. }
  73914. _this._offsetX = evt.clientX - previousPosition.x;
  73915. _this._offsetY = -(evt.clientY - previousPosition.y);
  73916. }
  73917. };
  73918. }
  73919. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  73920. if (this._onLostFocus) {
  73921. element.addEventListener("blur", this._onLostFocus);
  73922. }
  73923. };
  73924. FreeCameraTouchInput.prototype.detachControl = function (element) {
  73925. if (this._pointerInput && element) {
  73926. if (this._observer) {
  73927. this.camera.getScene().onPointerObservable.remove(this._observer);
  73928. this._observer = null;
  73929. }
  73930. if (this._onLostFocus) {
  73931. element.removeEventListener("blur", this._onLostFocus);
  73932. this._onLostFocus = null;
  73933. }
  73934. this._pointerPressed = [];
  73935. this._offsetX = null;
  73936. this._offsetY = null;
  73937. }
  73938. };
  73939. FreeCameraTouchInput.prototype.checkInputs = function () {
  73940. if (this._offsetX && this._offsetY) {
  73941. var camera = this.camera;
  73942. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  73943. if (this._pointerPressed.length > 1) {
  73944. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  73945. }
  73946. else {
  73947. var speed = camera._computeLocalCameraSpeed();
  73948. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  73949. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  73950. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  73951. }
  73952. }
  73953. };
  73954. FreeCameraTouchInput.prototype.getClassName = function () {
  73955. return "FreeCameraTouchInput";
  73956. };
  73957. FreeCameraTouchInput.prototype.getSimpleName = function () {
  73958. return "touch";
  73959. };
  73960. __decorate([
  73961. BABYLON.serialize()
  73962. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  73963. __decorate([
  73964. BABYLON.serialize()
  73965. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  73966. return FreeCameraTouchInput;
  73967. }());
  73968. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  73969. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  73970. })(BABYLON || (BABYLON = {}));
  73971. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  73972. var BABYLON;
  73973. (function (BABYLON) {
  73974. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  73975. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  73976. });
  73977. // We're mainly based on the logic defined into the FreeCamera code
  73978. var TouchCamera = /** @class */ (function (_super) {
  73979. __extends(TouchCamera, _super);
  73980. //-- end properties for backward compatibility for inputs
  73981. function TouchCamera(name, position, scene) {
  73982. var _this = _super.call(this, name, position, scene) || this;
  73983. _this.inputs.addTouch();
  73984. _this._setupInputs();
  73985. return _this;
  73986. }
  73987. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  73988. //-- Begin properties for backward compatibility for inputs
  73989. get: function () {
  73990. var touch = this.inputs.attached["touch"];
  73991. if (touch)
  73992. return touch.touchAngularSensibility;
  73993. return 0;
  73994. },
  73995. set: function (value) {
  73996. var touch = this.inputs.attached["touch"];
  73997. if (touch)
  73998. touch.touchAngularSensibility = value;
  73999. },
  74000. enumerable: true,
  74001. configurable: true
  74002. });
  74003. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  74004. get: function () {
  74005. var touch = this.inputs.attached["touch"];
  74006. if (touch)
  74007. return touch.touchMoveSensibility;
  74008. return 0;
  74009. },
  74010. set: function (value) {
  74011. var touch = this.inputs.attached["touch"];
  74012. if (touch)
  74013. touch.touchMoveSensibility = value;
  74014. },
  74015. enumerable: true,
  74016. configurable: true
  74017. });
  74018. TouchCamera.prototype.getClassName = function () {
  74019. return "TouchCamera";
  74020. };
  74021. /** @hidden */
  74022. TouchCamera.prototype._setupInputs = function () {
  74023. var mouse = this.inputs.attached["mouse"];
  74024. if (mouse) {
  74025. mouse.touchEnabled = false;
  74026. }
  74027. };
  74028. return TouchCamera;
  74029. }(BABYLON.FreeCamera));
  74030. BABYLON.TouchCamera = TouchCamera;
  74031. })(BABYLON || (BABYLON = {}));
  74032. //# sourceMappingURL=babylon.touchCamera.js.map
  74033. var BABYLON;
  74034. (function (BABYLON) {
  74035. var ProceduralTexture = /** @class */ (function (_super) {
  74036. __extends(ProceduralTexture, _super);
  74037. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  74038. if (fallbackTexture === void 0) { fallbackTexture = null; }
  74039. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74040. if (isCube === void 0) { isCube = false; }
  74041. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  74042. _this.isCube = isCube;
  74043. _this.isEnabled = true;
  74044. _this._currentRefreshId = -1;
  74045. _this._refreshRate = 1;
  74046. _this._vertexBuffers = {};
  74047. _this._uniforms = new Array();
  74048. _this._samplers = new Array();
  74049. /** @hidden */
  74050. _this._textures = {};
  74051. _this._floats = {};
  74052. _this._ints = {};
  74053. _this._floatsArrays = {};
  74054. _this._colors3 = {};
  74055. _this._colors4 = {};
  74056. _this._vectors2 = {};
  74057. _this._vectors3 = {};
  74058. _this._matrices = {};
  74059. _this._fallbackTextureUsed = false;
  74060. _this._cachedDefines = "";
  74061. scene = _this.getScene();
  74062. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  74063. if (!component) {
  74064. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  74065. scene._addComponent(component);
  74066. }
  74067. scene.proceduralTextures.push(_this);
  74068. _this._engine = scene.getEngine();
  74069. _this.name = name;
  74070. _this.isRenderTarget = true;
  74071. _this._size = size;
  74072. _this._generateMipMaps = generateMipMaps;
  74073. _this.setFragment(fragment);
  74074. _this._fallbackTexture = fallbackTexture;
  74075. if (isCube) {
  74076. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  74077. _this.setFloat("face", 0);
  74078. }
  74079. else {
  74080. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  74081. }
  74082. // VBO
  74083. var vertices = [];
  74084. vertices.push(1, 1);
  74085. vertices.push(-1, 1);
  74086. vertices.push(-1, -1);
  74087. vertices.push(1, -1);
  74088. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74089. _this._createIndexBuffer();
  74090. return _this;
  74091. }
  74092. ProceduralTexture.prototype._createIndexBuffer = function () {
  74093. var engine = this._engine;
  74094. // Indices
  74095. var indices = [];
  74096. indices.push(0);
  74097. indices.push(1);
  74098. indices.push(2);
  74099. indices.push(0);
  74100. indices.push(2);
  74101. indices.push(3);
  74102. this._indexBuffer = engine.createIndexBuffer(indices);
  74103. };
  74104. /** @hidden */
  74105. ProceduralTexture.prototype._rebuild = function () {
  74106. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74107. if (vb) {
  74108. vb._rebuild();
  74109. }
  74110. this._createIndexBuffer();
  74111. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  74112. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  74113. }
  74114. };
  74115. ProceduralTexture.prototype.reset = function () {
  74116. if (this._effect === undefined) {
  74117. return;
  74118. }
  74119. var engine = this._engine;
  74120. engine._releaseEffect(this._effect);
  74121. };
  74122. ProceduralTexture.prototype._getDefines = function () {
  74123. return "";
  74124. };
  74125. ProceduralTexture.prototype.isReady = function () {
  74126. var _this = this;
  74127. var engine = this._engine;
  74128. var shaders;
  74129. if (!this._fragment) {
  74130. return false;
  74131. }
  74132. if (this._fallbackTextureUsed) {
  74133. return true;
  74134. }
  74135. var defines = this._getDefines();
  74136. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  74137. return true;
  74138. }
  74139. if (this._fragment.fragmentElement !== undefined) {
  74140. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  74141. }
  74142. else {
  74143. shaders = { vertex: "procedural", fragment: this._fragment };
  74144. }
  74145. this._cachedDefines = defines;
  74146. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  74147. _this.releaseInternalTexture();
  74148. if (_this._fallbackTexture) {
  74149. _this._texture = _this._fallbackTexture._texture;
  74150. if (_this._texture) {
  74151. _this._texture.incrementReferences();
  74152. }
  74153. }
  74154. _this._fallbackTextureUsed = true;
  74155. });
  74156. return this._effect.isReady();
  74157. };
  74158. ProceduralTexture.prototype.resetRefreshCounter = function () {
  74159. this._currentRefreshId = -1;
  74160. };
  74161. ProceduralTexture.prototype.setFragment = function (fragment) {
  74162. this._fragment = fragment;
  74163. };
  74164. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  74165. get: function () {
  74166. return this._refreshRate;
  74167. },
  74168. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  74169. set: function (value) {
  74170. this._refreshRate = value;
  74171. this.resetRefreshCounter();
  74172. },
  74173. enumerable: true,
  74174. configurable: true
  74175. });
  74176. /** @hidden */
  74177. ProceduralTexture.prototype._shouldRender = function () {
  74178. if (!this.isEnabled || !this.isReady() || !this._texture) {
  74179. return false;
  74180. }
  74181. if (this._fallbackTextureUsed) {
  74182. return false;
  74183. }
  74184. if (this._currentRefreshId === -1) { // At least render once
  74185. this._currentRefreshId = 1;
  74186. return true;
  74187. }
  74188. if (this.refreshRate === this._currentRefreshId) {
  74189. this._currentRefreshId = 1;
  74190. return true;
  74191. }
  74192. this._currentRefreshId++;
  74193. return false;
  74194. };
  74195. ProceduralTexture.prototype.getRenderSize = function () {
  74196. return this._size;
  74197. };
  74198. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  74199. if (this._fallbackTextureUsed) {
  74200. return;
  74201. }
  74202. this.releaseInternalTexture();
  74203. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  74204. // Update properties
  74205. this._size = size;
  74206. this._generateMipMaps = generateMipMaps;
  74207. };
  74208. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  74209. if (this._uniforms.indexOf(uniformName) === -1) {
  74210. this._uniforms.push(uniformName);
  74211. }
  74212. };
  74213. ProceduralTexture.prototype.setTexture = function (name, texture) {
  74214. if (this._samplers.indexOf(name) === -1) {
  74215. this._samplers.push(name);
  74216. }
  74217. this._textures[name] = texture;
  74218. return this;
  74219. };
  74220. ProceduralTexture.prototype.setFloat = function (name, value) {
  74221. this._checkUniform(name);
  74222. this._floats[name] = value;
  74223. return this;
  74224. };
  74225. /**
  74226. * Set the value of an uniform to an integer value
  74227. * @param name defines the name of the uniform
  74228. * @param value defines the value to set
  74229. * @returns the current procedural texture
  74230. */
  74231. ProceduralTexture.prototype.setInt = function (name, value) {
  74232. this._checkUniform(name);
  74233. this._ints[name] = value;
  74234. return this;
  74235. };
  74236. ProceduralTexture.prototype.setFloats = function (name, value) {
  74237. this._checkUniform(name);
  74238. this._floatsArrays[name] = value;
  74239. return this;
  74240. };
  74241. ProceduralTexture.prototype.setColor3 = function (name, value) {
  74242. this._checkUniform(name);
  74243. this._colors3[name] = value;
  74244. return this;
  74245. };
  74246. ProceduralTexture.prototype.setColor4 = function (name, value) {
  74247. this._checkUniform(name);
  74248. this._colors4[name] = value;
  74249. return this;
  74250. };
  74251. ProceduralTexture.prototype.setVector2 = function (name, value) {
  74252. this._checkUniform(name);
  74253. this._vectors2[name] = value;
  74254. return this;
  74255. };
  74256. ProceduralTexture.prototype.setVector3 = function (name, value) {
  74257. this._checkUniform(name);
  74258. this._vectors3[name] = value;
  74259. return this;
  74260. };
  74261. ProceduralTexture.prototype.setMatrix = function (name, value) {
  74262. this._checkUniform(name);
  74263. this._matrices[name] = value;
  74264. return this;
  74265. };
  74266. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74267. var scene = this.getScene();
  74268. if (!scene) {
  74269. return;
  74270. }
  74271. var engine = this._engine;
  74272. // Render
  74273. engine.enableEffect(this._effect);
  74274. engine.setState(false);
  74275. // Texture
  74276. for (var name in this._textures) {
  74277. this._effect.setTexture(name, this._textures[name]);
  74278. }
  74279. // Float
  74280. for (name in this._ints) {
  74281. this._effect.setInt(name, this._ints[name]);
  74282. }
  74283. // Float
  74284. for (name in this._floats) {
  74285. this._effect.setFloat(name, this._floats[name]);
  74286. }
  74287. // Floats
  74288. for (name in this._floatsArrays) {
  74289. this._effect.setArray(name, this._floatsArrays[name]);
  74290. }
  74291. // Color3
  74292. for (name in this._colors3) {
  74293. this._effect.setColor3(name, this._colors3[name]);
  74294. }
  74295. // Color4
  74296. for (name in this._colors4) {
  74297. var color = this._colors4[name];
  74298. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  74299. }
  74300. // Vector2
  74301. for (name in this._vectors2) {
  74302. this._effect.setVector2(name, this._vectors2[name]);
  74303. }
  74304. // Vector3
  74305. for (name in this._vectors3) {
  74306. this._effect.setVector3(name, this._vectors3[name]);
  74307. }
  74308. // Matrix
  74309. for (name in this._matrices) {
  74310. this._effect.setMatrix(name, this._matrices[name]);
  74311. }
  74312. if (!this._texture) {
  74313. return;
  74314. }
  74315. if (this.isCube) {
  74316. for (var face = 0; face < 6; face++) {
  74317. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  74318. // VBOs
  74319. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74320. this._effect.setFloat("face", face);
  74321. // Clear
  74322. engine.clear(scene.clearColor, true, true, true);
  74323. // Draw order
  74324. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74325. // Mipmaps
  74326. if (face === 5) {
  74327. engine.generateMipMapsForCubemap(this._texture);
  74328. }
  74329. }
  74330. }
  74331. else {
  74332. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  74333. // VBOs
  74334. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74335. // Clear
  74336. engine.clear(scene.clearColor, true, true, true);
  74337. // Draw order
  74338. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74339. }
  74340. // Unbind
  74341. engine.unBindFramebuffer(this._texture, this.isCube);
  74342. if (this.onGenerated) {
  74343. this.onGenerated();
  74344. }
  74345. };
  74346. ProceduralTexture.prototype.clone = function () {
  74347. var textureSize = this.getSize();
  74348. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  74349. // Base texture
  74350. newTexture.hasAlpha = this.hasAlpha;
  74351. newTexture.level = this.level;
  74352. // RenderTarget Texture
  74353. newTexture.coordinatesMode = this.coordinatesMode;
  74354. return newTexture;
  74355. };
  74356. ProceduralTexture.prototype.dispose = function () {
  74357. var scene = this.getScene();
  74358. if (!scene) {
  74359. return;
  74360. }
  74361. var index = scene.proceduralTextures.indexOf(this);
  74362. if (index >= 0) {
  74363. scene.proceduralTextures.splice(index, 1);
  74364. }
  74365. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74366. if (vertexBuffer) {
  74367. vertexBuffer.dispose();
  74368. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74369. }
  74370. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  74371. this._indexBuffer = null;
  74372. }
  74373. _super.prototype.dispose.call(this);
  74374. };
  74375. __decorate([
  74376. BABYLON.serialize()
  74377. ], ProceduralTexture.prototype, "_size", void 0);
  74378. __decorate([
  74379. BABYLON.serialize()
  74380. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  74381. __decorate([
  74382. BABYLON.serialize()
  74383. ], ProceduralTexture.prototype, "isEnabled", void 0);
  74384. __decorate([
  74385. BABYLON.serialize()
  74386. ], ProceduralTexture.prototype, "refreshRate", null);
  74387. return ProceduralTexture;
  74388. }(BABYLON.Texture));
  74389. BABYLON.ProceduralTexture = ProceduralTexture;
  74390. })(BABYLON || (BABYLON = {}));
  74391. //# sourceMappingURL=babylon.proceduralTexture.js.map
  74392. var BABYLON;
  74393. (function (BABYLON) {
  74394. /**
  74395. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  74396. * in a given scene.
  74397. */
  74398. var ProceduralTextureSceneComponent = /** @class */ (function () {
  74399. /**
  74400. * Creates a new instance of the component for the given scene
  74401. * @param scene Defines the scene to register the component in
  74402. */
  74403. function ProceduralTextureSceneComponent(scene) {
  74404. /**
  74405. * The component name helpfull to identify the component in the list of scene components.
  74406. */
  74407. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  74408. this.scene = scene;
  74409. this.scene.proceduralTextures = new Array();
  74410. scene.layers = new Array();
  74411. }
  74412. /**
  74413. * Registers the component in a given scene
  74414. */
  74415. ProceduralTextureSceneComponent.prototype.register = function () {
  74416. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  74417. };
  74418. /**
  74419. * Rebuilds the elements related to this component in case of
  74420. * context lost for instance.
  74421. */
  74422. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  74423. // Nothing to do here.
  74424. };
  74425. /**
  74426. * Disposes the component and the associated ressources.
  74427. */
  74428. ProceduralTextureSceneComponent.prototype.dispose = function () {
  74429. // Nothing to do here.
  74430. };
  74431. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  74432. if (this.scene.proceduralTexturesEnabled) {
  74433. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  74434. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  74435. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  74436. if (proceduralTexture._shouldRender()) {
  74437. proceduralTexture.render();
  74438. }
  74439. }
  74440. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  74441. }
  74442. };
  74443. return ProceduralTextureSceneComponent;
  74444. }());
  74445. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  74446. })(BABYLON || (BABYLON = {}));
  74447. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  74448. var BABYLON;
  74449. (function (BABYLON) {
  74450. var CustomProceduralTexture = /** @class */ (function (_super) {
  74451. __extends(CustomProceduralTexture, _super);
  74452. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  74453. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  74454. _this._animate = true;
  74455. _this._time = 0;
  74456. _this._texturePath = texturePath;
  74457. //Try to load json
  74458. _this.loadJson(texturePath);
  74459. _this.refreshRate = 1;
  74460. return _this;
  74461. }
  74462. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  74463. var _this = this;
  74464. var noConfigFile = function () {
  74465. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  74466. try {
  74467. _this.setFragment(_this._texturePath);
  74468. }
  74469. catch (ex) {
  74470. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  74471. }
  74472. };
  74473. var configFileUrl = jsonUrl + "/config.json";
  74474. var xhr = new XMLHttpRequest();
  74475. xhr.open("GET", configFileUrl, true);
  74476. xhr.addEventListener("load", function () {
  74477. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  74478. try {
  74479. _this._config = JSON.parse(xhr.response);
  74480. _this.updateShaderUniforms();
  74481. _this.updateTextures();
  74482. _this.setFragment(_this._texturePath + "/custom");
  74483. _this._animate = _this._config.animate;
  74484. _this.refreshRate = _this._config.refreshrate;
  74485. }
  74486. catch (ex) {
  74487. noConfigFile();
  74488. }
  74489. }
  74490. else {
  74491. noConfigFile();
  74492. }
  74493. }, false);
  74494. xhr.addEventListener("error", function () {
  74495. noConfigFile();
  74496. }, false);
  74497. try {
  74498. xhr.send();
  74499. }
  74500. catch (ex) {
  74501. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  74502. }
  74503. };
  74504. CustomProceduralTexture.prototype.isReady = function () {
  74505. if (!_super.prototype.isReady.call(this)) {
  74506. return false;
  74507. }
  74508. for (var name in this._textures) {
  74509. var texture = this._textures[name];
  74510. if (!texture.isReady()) {
  74511. return false;
  74512. }
  74513. }
  74514. return true;
  74515. };
  74516. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74517. var scene = this.getScene();
  74518. if (this._animate && scene) {
  74519. this._time += scene.getAnimationRatio() * 0.03;
  74520. this.updateShaderUniforms();
  74521. }
  74522. _super.prototype.render.call(this, useCameraPostProcess);
  74523. };
  74524. CustomProceduralTexture.prototype.updateTextures = function () {
  74525. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  74526. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  74527. }
  74528. };
  74529. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  74530. if (this._config) {
  74531. for (var j = 0; j < this._config.uniforms.length; j++) {
  74532. var uniform = this._config.uniforms[j];
  74533. switch (uniform.type) {
  74534. case "float":
  74535. this.setFloat(uniform.name, uniform.value);
  74536. break;
  74537. case "color3":
  74538. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  74539. break;
  74540. case "color4":
  74541. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  74542. break;
  74543. case "vector2":
  74544. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  74545. break;
  74546. case "vector3":
  74547. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  74548. break;
  74549. }
  74550. }
  74551. }
  74552. this.setFloat("time", this._time);
  74553. };
  74554. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  74555. get: function () {
  74556. return this._animate;
  74557. },
  74558. set: function (value) {
  74559. this._animate = value;
  74560. },
  74561. enumerable: true,
  74562. configurable: true
  74563. });
  74564. return CustomProceduralTexture;
  74565. }(BABYLON.ProceduralTexture));
  74566. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  74567. })(BABYLON || (BABYLON = {}));
  74568. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  74569. var BABYLON;
  74570. (function (BABYLON) {
  74571. var FreeCameraGamepadInput = /** @class */ (function () {
  74572. function FreeCameraGamepadInput() {
  74573. this.gamepadAngularSensibility = 200;
  74574. this.gamepadMoveSensibility = 40;
  74575. // private members
  74576. this._cameraTransform = BABYLON.Matrix.Identity();
  74577. this._deltaTransform = BABYLON.Vector3.Zero();
  74578. this._vector3 = BABYLON.Vector3.Zero();
  74579. this._vector2 = BABYLON.Vector2.Zero();
  74580. }
  74581. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74582. var _this = this;
  74583. var manager = this.camera.getScene().gamepadManager;
  74584. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74585. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74586. // prioritize XBOX gamepads.
  74587. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74588. _this.gamepad = gamepad;
  74589. }
  74590. }
  74591. });
  74592. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74593. if (_this.gamepad === gamepad) {
  74594. _this.gamepad = null;
  74595. }
  74596. });
  74597. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74598. };
  74599. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  74600. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74601. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74602. this.gamepad = null;
  74603. };
  74604. FreeCameraGamepadInput.prototype.checkInputs = function () {
  74605. if (this.gamepad && this.gamepad.leftStick) {
  74606. var camera = this.camera;
  74607. var LSValues = this.gamepad.leftStick;
  74608. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  74609. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  74610. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  74611. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  74612. var RSValues = this.gamepad.rightStick;
  74613. if (RSValues) {
  74614. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  74615. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  74616. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  74617. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  74618. }
  74619. else {
  74620. RSValues = { x: 0, y: 0 };
  74621. }
  74622. if (!camera.rotationQuaternion) {
  74623. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  74624. }
  74625. else {
  74626. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  74627. }
  74628. var speed = camera._computeLocalCameraSpeed() * 50.0;
  74629. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  74630. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  74631. camera.cameraDirection.addInPlace(this._deltaTransform);
  74632. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  74633. camera.cameraRotation.addInPlace(this._vector2);
  74634. }
  74635. };
  74636. FreeCameraGamepadInput.prototype.getClassName = function () {
  74637. return "FreeCameraGamepadInput";
  74638. };
  74639. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  74640. return "gamepad";
  74641. };
  74642. __decorate([
  74643. BABYLON.serialize()
  74644. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  74645. __decorate([
  74646. BABYLON.serialize()
  74647. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  74648. return FreeCameraGamepadInput;
  74649. }());
  74650. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  74651. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  74652. })(BABYLON || (BABYLON = {}));
  74653. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  74654. var BABYLON;
  74655. (function (BABYLON) {
  74656. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  74657. function ArcRotateCameraGamepadInput() {
  74658. this.gamepadRotationSensibility = 80;
  74659. this.gamepadMoveSensibility = 40;
  74660. }
  74661. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74662. var _this = this;
  74663. var manager = this.camera.getScene().gamepadManager;
  74664. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74665. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74666. // prioritize XBOX gamepads.
  74667. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74668. _this.gamepad = gamepad;
  74669. }
  74670. }
  74671. });
  74672. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74673. if (_this.gamepad === gamepad) {
  74674. _this.gamepad = null;
  74675. }
  74676. });
  74677. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74678. };
  74679. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  74680. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74681. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74682. this.gamepad = null;
  74683. };
  74684. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  74685. if (this.gamepad) {
  74686. var camera = this.camera;
  74687. var RSValues = this.gamepad.rightStick;
  74688. if (RSValues) {
  74689. if (RSValues.x != 0) {
  74690. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  74691. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  74692. camera.inertialAlphaOffset += normalizedRX;
  74693. }
  74694. }
  74695. if (RSValues.y != 0) {
  74696. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  74697. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  74698. camera.inertialBetaOffset += normalizedRY;
  74699. }
  74700. }
  74701. }
  74702. var LSValues = this.gamepad.leftStick;
  74703. if (LSValues && LSValues.y != 0) {
  74704. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  74705. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  74706. this.camera.inertialRadiusOffset -= normalizedLY;
  74707. }
  74708. }
  74709. }
  74710. };
  74711. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  74712. return "ArcRotateCameraGamepadInput";
  74713. };
  74714. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  74715. return "gamepad";
  74716. };
  74717. __decorate([
  74718. BABYLON.serialize()
  74719. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  74720. __decorate([
  74721. BABYLON.serialize()
  74722. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  74723. return ArcRotateCameraGamepadInput;
  74724. }());
  74725. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  74726. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  74727. })(BABYLON || (BABYLON = {}));
  74728. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  74729. var BABYLON;
  74730. (function (BABYLON) {
  74731. var GamepadManager = /** @class */ (function () {
  74732. function GamepadManager(_scene) {
  74733. var _this = this;
  74734. this._scene = _scene;
  74735. this._babylonGamepads = [];
  74736. this._oneGamepadConnected = false;
  74737. /** @hidden */
  74738. this._isMonitoring = false;
  74739. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  74740. if (!BABYLON.Tools.IsWindowObjectExist()) {
  74741. this._gamepadEventSupported = false;
  74742. }
  74743. else {
  74744. this._gamepadEventSupported = 'GamepadEvent' in window;
  74745. this._gamepadSupport = (navigator.getGamepads ||
  74746. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  74747. }
  74748. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  74749. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  74750. for (var i in _this._babylonGamepads) {
  74751. var gamepad = _this._babylonGamepads[i];
  74752. if (gamepad && gamepad._isConnected) {
  74753. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  74754. }
  74755. }
  74756. });
  74757. this._onGamepadConnectedEvent = function (evt) {
  74758. var gamepad = evt.gamepad;
  74759. if (gamepad.index in _this._babylonGamepads) {
  74760. if (_this._babylonGamepads[gamepad.index].isConnected) {
  74761. return;
  74762. }
  74763. }
  74764. var newGamepad;
  74765. if (_this._babylonGamepads[gamepad.index]) {
  74766. newGamepad = _this._babylonGamepads[gamepad.index];
  74767. newGamepad.browserGamepad = gamepad;
  74768. newGamepad._isConnected = true;
  74769. }
  74770. else {
  74771. newGamepad = _this._addNewGamepad(gamepad);
  74772. }
  74773. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  74774. _this._startMonitoringGamepads();
  74775. };
  74776. this._onGamepadDisconnectedEvent = function (evt) {
  74777. var gamepad = evt.gamepad;
  74778. // Remove the gamepad from the list of gamepads to monitor.
  74779. for (var i in _this._babylonGamepads) {
  74780. if (_this._babylonGamepads[i].index === gamepad.index) {
  74781. var disconnectedGamepad = _this._babylonGamepads[i];
  74782. disconnectedGamepad._isConnected = false;
  74783. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  74784. break;
  74785. }
  74786. }
  74787. };
  74788. if (this._gamepadSupport) {
  74789. //first add already-connected gamepads
  74790. this._updateGamepadObjects();
  74791. if (this._babylonGamepads.length) {
  74792. this._startMonitoringGamepads();
  74793. }
  74794. // Checking if the gamepad connected event is supported (like in Firefox)
  74795. if (this._gamepadEventSupported) {
  74796. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  74797. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  74798. }
  74799. else {
  74800. this._startMonitoringGamepads();
  74801. }
  74802. }
  74803. }
  74804. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  74805. get: function () {
  74806. return this._babylonGamepads;
  74807. },
  74808. enumerable: true,
  74809. configurable: true
  74810. });
  74811. GamepadManager.prototype.getGamepadByType = function (type) {
  74812. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  74813. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  74814. var gamepad = _a[_i];
  74815. if (gamepad && gamepad.type === type) {
  74816. return gamepad;
  74817. }
  74818. }
  74819. return null;
  74820. };
  74821. GamepadManager.prototype.dispose = function () {
  74822. if (this._gamepadEventSupported) {
  74823. if (this._onGamepadConnectedEvent) {
  74824. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  74825. }
  74826. if (this._onGamepadDisconnectedEvent) {
  74827. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  74828. }
  74829. this._onGamepadConnectedEvent = null;
  74830. this._onGamepadDisconnectedEvent = null;
  74831. }
  74832. this._babylonGamepads.forEach(function (gamepad) {
  74833. gamepad.dispose();
  74834. });
  74835. this.onGamepadConnectedObservable.clear();
  74836. this.onGamepadDisconnectedObservable.clear();
  74837. this._oneGamepadConnected = false;
  74838. this._stopMonitoringGamepads();
  74839. this._babylonGamepads = [];
  74840. };
  74841. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  74842. if (!this._oneGamepadConnected) {
  74843. this._oneGamepadConnected = true;
  74844. }
  74845. var newGamepad;
  74846. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  74847. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  74848. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  74849. }
  74850. // if pose is supported, use the (WebVR) pose enabled controller
  74851. else if (gamepad.pose) {
  74852. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  74853. }
  74854. else {
  74855. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  74856. }
  74857. this._babylonGamepads[newGamepad.index] = newGamepad;
  74858. return newGamepad;
  74859. };
  74860. GamepadManager.prototype._startMonitoringGamepads = function () {
  74861. if (!this._isMonitoring) {
  74862. this._isMonitoring = true;
  74863. //back-comp
  74864. if (!this._scene) {
  74865. this._checkGamepadsStatus();
  74866. }
  74867. }
  74868. };
  74869. GamepadManager.prototype._stopMonitoringGamepads = function () {
  74870. this._isMonitoring = false;
  74871. };
  74872. /** @hidden */
  74873. GamepadManager.prototype._checkGamepadsStatus = function () {
  74874. var _this = this;
  74875. // Hack to be compatible Chrome
  74876. this._updateGamepadObjects();
  74877. for (var i in this._babylonGamepads) {
  74878. var gamepad = this._babylonGamepads[i];
  74879. if (!gamepad || !gamepad.isConnected) {
  74880. continue;
  74881. }
  74882. gamepad.update();
  74883. }
  74884. if (this._isMonitoring && !this._scene) {
  74885. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  74886. }
  74887. };
  74888. // This function is called only on Chrome, which does not properly support
  74889. // connection/disconnection events and forces you to recopy again the gamepad object
  74890. GamepadManager.prototype._updateGamepadObjects = function () {
  74891. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  74892. for (var i = 0; i < gamepads.length; i++) {
  74893. var gamepad = gamepads[i];
  74894. if (gamepad) {
  74895. if (!this._babylonGamepads[gamepad.index]) {
  74896. var newGamepad = this._addNewGamepad(gamepad);
  74897. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  74898. }
  74899. else {
  74900. // Forced to copy again this object for Chrome for unknown reason
  74901. this._babylonGamepads[i].browserGamepad = gamepad;
  74902. if (!this._babylonGamepads[i].isConnected) {
  74903. this._babylonGamepads[i]._isConnected = true;
  74904. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  74905. }
  74906. }
  74907. }
  74908. }
  74909. };
  74910. return GamepadManager;
  74911. }());
  74912. BABYLON.GamepadManager = GamepadManager;
  74913. })(BABYLON || (BABYLON = {}));
  74914. //# sourceMappingURL=babylon.gamepadManager.js.map
  74915. var BABYLON;
  74916. (function (BABYLON) {
  74917. var StickValues = /** @class */ (function () {
  74918. function StickValues(x, y) {
  74919. this.x = x;
  74920. this.y = y;
  74921. }
  74922. return StickValues;
  74923. }());
  74924. BABYLON.StickValues = StickValues;
  74925. var Gamepad = /** @class */ (function () {
  74926. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  74927. if (leftStickX === void 0) { leftStickX = 0; }
  74928. if (leftStickY === void 0) { leftStickY = 1; }
  74929. if (rightStickX === void 0) { rightStickX = 2; }
  74930. if (rightStickY === void 0) { rightStickY = 3; }
  74931. this.id = id;
  74932. this.index = index;
  74933. this.browserGamepad = browserGamepad;
  74934. this._leftStick = { x: 0, y: 0 };
  74935. this._rightStick = { x: 0, y: 0 };
  74936. /** @hidden */
  74937. this._isConnected = true;
  74938. this._invertLeftStickY = false;
  74939. this.type = Gamepad.GAMEPAD;
  74940. this._leftStickAxisX = leftStickX;
  74941. this._leftStickAxisY = leftStickY;
  74942. this._rightStickAxisX = rightStickX;
  74943. this._rightStickAxisY = rightStickY;
  74944. if (this.browserGamepad.axes.length >= 2) {
  74945. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  74946. }
  74947. if (this.browserGamepad.axes.length >= 4) {
  74948. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  74949. }
  74950. }
  74951. Object.defineProperty(Gamepad.prototype, "isConnected", {
  74952. get: function () {
  74953. return this._isConnected;
  74954. },
  74955. enumerable: true,
  74956. configurable: true
  74957. });
  74958. Gamepad.prototype.onleftstickchanged = function (callback) {
  74959. this._onleftstickchanged = callback;
  74960. };
  74961. Gamepad.prototype.onrightstickchanged = function (callback) {
  74962. this._onrightstickchanged = callback;
  74963. };
  74964. Object.defineProperty(Gamepad.prototype, "leftStick", {
  74965. get: function () {
  74966. return this._leftStick;
  74967. },
  74968. set: function (newValues) {
  74969. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  74970. this._onleftstickchanged(newValues);
  74971. }
  74972. this._leftStick = newValues;
  74973. },
  74974. enumerable: true,
  74975. configurable: true
  74976. });
  74977. Object.defineProperty(Gamepad.prototype, "rightStick", {
  74978. get: function () {
  74979. return this._rightStick;
  74980. },
  74981. set: function (newValues) {
  74982. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  74983. this._onrightstickchanged(newValues);
  74984. }
  74985. this._rightStick = newValues;
  74986. },
  74987. enumerable: true,
  74988. configurable: true
  74989. });
  74990. Gamepad.prototype.update = function () {
  74991. if (this._leftStick) {
  74992. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  74993. if (this._invertLeftStickY) {
  74994. this.leftStick.y *= -1;
  74995. }
  74996. }
  74997. if (this._rightStick) {
  74998. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  74999. }
  75000. };
  75001. Gamepad.prototype.dispose = function () {
  75002. };
  75003. Gamepad.GAMEPAD = 0;
  75004. Gamepad.GENERIC = 1;
  75005. Gamepad.XBOX = 2;
  75006. Gamepad.POSE_ENABLED = 3;
  75007. return Gamepad;
  75008. }());
  75009. BABYLON.Gamepad = Gamepad;
  75010. var GenericPad = /** @class */ (function (_super) {
  75011. __extends(GenericPad, _super);
  75012. function GenericPad(id, index, browserGamepad) {
  75013. var _this = _super.call(this, id, index, browserGamepad) || this;
  75014. _this.onButtonDownObservable = new BABYLON.Observable();
  75015. _this.onButtonUpObservable = new BABYLON.Observable();
  75016. _this.type = Gamepad.GENERIC;
  75017. _this._buttons = new Array(browserGamepad.buttons.length);
  75018. return _this;
  75019. }
  75020. GenericPad.prototype.onbuttondown = function (callback) {
  75021. this._onbuttondown = callback;
  75022. };
  75023. GenericPad.prototype.onbuttonup = function (callback) {
  75024. this._onbuttonup = callback;
  75025. };
  75026. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  75027. if (newValue !== currentValue) {
  75028. if (newValue === 1) {
  75029. if (this._onbuttondown) {
  75030. this._onbuttondown(buttonIndex);
  75031. }
  75032. this.onButtonDownObservable.notifyObservers(buttonIndex);
  75033. }
  75034. if (newValue === 0) {
  75035. if (this._onbuttonup) {
  75036. this._onbuttonup(buttonIndex);
  75037. }
  75038. this.onButtonUpObservable.notifyObservers(buttonIndex);
  75039. }
  75040. }
  75041. return newValue;
  75042. };
  75043. GenericPad.prototype.update = function () {
  75044. _super.prototype.update.call(this);
  75045. for (var index = 0; index < this._buttons.length; index++) {
  75046. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  75047. }
  75048. };
  75049. GenericPad.prototype.dispose = function () {
  75050. _super.prototype.dispose.call(this);
  75051. this.onButtonDownObservable.clear();
  75052. this.onButtonUpObservable.clear();
  75053. };
  75054. return GenericPad;
  75055. }(Gamepad));
  75056. BABYLON.GenericPad = GenericPad;
  75057. })(BABYLON || (BABYLON = {}));
  75058. //# sourceMappingURL=babylon.gamepad.js.map
  75059. var BABYLON;
  75060. (function (BABYLON) {
  75061. /**
  75062. * Defines supported buttons for XBox360 compatible gamepads
  75063. */
  75064. var Xbox360Button;
  75065. (function (Xbox360Button) {
  75066. /** A */
  75067. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  75068. /** B */
  75069. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  75070. /** X */
  75071. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  75072. /** Y */
  75073. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  75074. /** Start */
  75075. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  75076. /** Back */
  75077. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  75078. /** Left button */
  75079. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  75080. /** Right button */
  75081. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  75082. /** Left stick */
  75083. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  75084. /** Right stick */
  75085. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  75086. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  75087. /** Defines values for XBox360 DPad */
  75088. var Xbox360Dpad;
  75089. (function (Xbox360Dpad) {
  75090. /** Up */
  75091. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  75092. /** Down */
  75093. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  75094. /** Left */
  75095. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  75096. /** Right */
  75097. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  75098. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  75099. /**
  75100. * Defines a XBox360 gamepad
  75101. */
  75102. var Xbox360Pad = /** @class */ (function (_super) {
  75103. __extends(Xbox360Pad, _super);
  75104. /**
  75105. * Creates a new XBox360 gamepad object
  75106. * @param id defines the id of this gamepad
  75107. * @param index defines its index
  75108. * @param gamepad defines the internal HTML gamepad object
  75109. * @param xboxOne defines if it is a XBox One gamepad
  75110. */
  75111. function Xbox360Pad(id, index, gamepad, xboxOne) {
  75112. if (xboxOne === void 0) { xboxOne = false; }
  75113. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  75114. _this._leftTrigger = 0;
  75115. _this._rightTrigger = 0;
  75116. /** Observable raised when a button is pressed */
  75117. _this.onButtonDownObservable = new BABYLON.Observable();
  75118. /** Observable raised when a button is released */
  75119. _this.onButtonUpObservable = new BABYLON.Observable();
  75120. /** Observable raised when a pad is pressed */
  75121. _this.onPadDownObservable = new BABYLON.Observable();
  75122. /** Observable raised when a pad is released */
  75123. _this.onPadUpObservable = new BABYLON.Observable();
  75124. _this._buttonA = 0;
  75125. _this._buttonB = 0;
  75126. _this._buttonX = 0;
  75127. _this._buttonY = 0;
  75128. _this._buttonBack = 0;
  75129. _this._buttonStart = 0;
  75130. _this._buttonLB = 0;
  75131. _this._buttonRB = 0;
  75132. _this._buttonLeftStick = 0;
  75133. _this._buttonRightStick = 0;
  75134. _this._dPadUp = 0;
  75135. _this._dPadDown = 0;
  75136. _this._dPadLeft = 0;
  75137. _this._dPadRight = 0;
  75138. _this._isXboxOnePad = false;
  75139. _this.type = BABYLON.Gamepad.XBOX;
  75140. _this._isXboxOnePad = xboxOne;
  75141. return _this;
  75142. }
  75143. /**
  75144. * Defines the callback to call when left trigger is pressed
  75145. * @param callback defines the callback to use
  75146. */
  75147. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  75148. this._onlefttriggerchanged = callback;
  75149. };
  75150. /**
  75151. * Defines the callback to call when right trigger is pressed
  75152. * @param callback defines the callback to use
  75153. */
  75154. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  75155. this._onrighttriggerchanged = callback;
  75156. };
  75157. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  75158. /**
  75159. * Gets or sets left trigger value
  75160. */
  75161. get: function () {
  75162. return this._leftTrigger;
  75163. },
  75164. set: function (newValue) {
  75165. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  75166. this._onlefttriggerchanged(newValue);
  75167. }
  75168. this._leftTrigger = newValue;
  75169. },
  75170. enumerable: true,
  75171. configurable: true
  75172. });
  75173. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  75174. /**
  75175. * Gets or sets right trigger value
  75176. */
  75177. get: function () {
  75178. return this._rightTrigger;
  75179. },
  75180. set: function (newValue) {
  75181. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  75182. this._onrighttriggerchanged(newValue);
  75183. }
  75184. this._rightTrigger = newValue;
  75185. },
  75186. enumerable: true,
  75187. configurable: true
  75188. });
  75189. /**
  75190. * Defines the callback to call when a button is pressed
  75191. * @param callback defines the callback to use
  75192. */
  75193. Xbox360Pad.prototype.onbuttondown = function (callback) {
  75194. this._onbuttondown = callback;
  75195. };
  75196. /**
  75197. * Defines the callback to call when a button is released
  75198. * @param callback defines the callback to use
  75199. */
  75200. Xbox360Pad.prototype.onbuttonup = function (callback) {
  75201. this._onbuttonup = callback;
  75202. };
  75203. /**
  75204. * Defines the callback to call when a pad is pressed
  75205. * @param callback defines the callback to use
  75206. */
  75207. Xbox360Pad.prototype.ondpaddown = function (callback) {
  75208. this._ondpaddown = callback;
  75209. };
  75210. /**
  75211. * Defines the callback to call when a pad is released
  75212. * @param callback defines the callback to use
  75213. */
  75214. Xbox360Pad.prototype.ondpadup = function (callback) {
  75215. this._ondpadup = callback;
  75216. };
  75217. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  75218. if (newValue !== currentValue) {
  75219. if (newValue === 1) {
  75220. if (this._onbuttondown) {
  75221. this._onbuttondown(buttonType);
  75222. }
  75223. this.onButtonDownObservable.notifyObservers(buttonType);
  75224. }
  75225. if (newValue === 0) {
  75226. if (this._onbuttonup) {
  75227. this._onbuttonup(buttonType);
  75228. }
  75229. this.onButtonUpObservable.notifyObservers(buttonType);
  75230. }
  75231. }
  75232. return newValue;
  75233. };
  75234. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  75235. if (newValue !== currentValue) {
  75236. if (newValue === 1) {
  75237. if (this._ondpaddown) {
  75238. this._ondpaddown(buttonType);
  75239. }
  75240. this.onPadDownObservable.notifyObservers(buttonType);
  75241. }
  75242. if (newValue === 0) {
  75243. if (this._ondpadup) {
  75244. this._ondpadup(buttonType);
  75245. }
  75246. this.onPadUpObservable.notifyObservers(buttonType);
  75247. }
  75248. }
  75249. return newValue;
  75250. };
  75251. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  75252. /** Gets or sets value of A button */
  75253. get: function () {
  75254. return this._buttonA;
  75255. },
  75256. set: function (value) {
  75257. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  75258. },
  75259. enumerable: true,
  75260. configurable: true
  75261. });
  75262. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  75263. /** Gets or sets value of B button */
  75264. get: function () {
  75265. return this._buttonB;
  75266. },
  75267. set: function (value) {
  75268. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  75269. },
  75270. enumerable: true,
  75271. configurable: true
  75272. });
  75273. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  75274. /** Gets or sets value of X button */
  75275. get: function () {
  75276. return this._buttonX;
  75277. },
  75278. set: function (value) {
  75279. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  75280. },
  75281. enumerable: true,
  75282. configurable: true
  75283. });
  75284. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  75285. /** Gets or sets value of Y button */
  75286. get: function () {
  75287. return this._buttonY;
  75288. },
  75289. set: function (value) {
  75290. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  75291. },
  75292. enumerable: true,
  75293. configurable: true
  75294. });
  75295. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  75296. /** Gets or sets value of Start button */
  75297. get: function () {
  75298. return this._buttonStart;
  75299. },
  75300. set: function (value) {
  75301. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  75302. },
  75303. enumerable: true,
  75304. configurable: true
  75305. });
  75306. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  75307. /** Gets or sets value of Back button */
  75308. get: function () {
  75309. return this._buttonBack;
  75310. },
  75311. set: function (value) {
  75312. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  75313. },
  75314. enumerable: true,
  75315. configurable: true
  75316. });
  75317. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  75318. /** Gets or sets value of Left button */
  75319. get: function () {
  75320. return this._buttonLB;
  75321. },
  75322. set: function (value) {
  75323. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  75324. },
  75325. enumerable: true,
  75326. configurable: true
  75327. });
  75328. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  75329. /** Gets or sets value of Right button */
  75330. get: function () {
  75331. return this._buttonRB;
  75332. },
  75333. set: function (value) {
  75334. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  75335. },
  75336. enumerable: true,
  75337. configurable: true
  75338. });
  75339. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  75340. /** Gets or sets value of left stick */
  75341. get: function () {
  75342. return this._buttonLeftStick;
  75343. },
  75344. set: function (value) {
  75345. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  75346. },
  75347. enumerable: true,
  75348. configurable: true
  75349. });
  75350. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  75351. /** Gets or sets value of right stick */
  75352. get: function () {
  75353. return this._buttonRightStick;
  75354. },
  75355. set: function (value) {
  75356. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  75357. },
  75358. enumerable: true,
  75359. configurable: true
  75360. });
  75361. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  75362. /** Gets or sets value of DPad up */
  75363. get: function () {
  75364. return this._dPadUp;
  75365. },
  75366. set: function (value) {
  75367. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  75368. },
  75369. enumerable: true,
  75370. configurable: true
  75371. });
  75372. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  75373. /** Gets or sets value of DPad down */
  75374. get: function () {
  75375. return this._dPadDown;
  75376. },
  75377. set: function (value) {
  75378. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  75379. },
  75380. enumerable: true,
  75381. configurable: true
  75382. });
  75383. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  75384. /** Gets or sets value of DPad left */
  75385. get: function () {
  75386. return this._dPadLeft;
  75387. },
  75388. set: function (value) {
  75389. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  75390. },
  75391. enumerable: true,
  75392. configurable: true
  75393. });
  75394. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  75395. /** Gets or sets value of DPad right */
  75396. get: function () {
  75397. return this._dPadRight;
  75398. },
  75399. set: function (value) {
  75400. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  75401. },
  75402. enumerable: true,
  75403. configurable: true
  75404. });
  75405. /**
  75406. * Force the gamepad to synchronize with device values
  75407. */
  75408. Xbox360Pad.prototype.update = function () {
  75409. _super.prototype.update.call(this);
  75410. if (this._isXboxOnePad) {
  75411. this.buttonA = this.browserGamepad.buttons[0].value;
  75412. this.buttonB = this.browserGamepad.buttons[1].value;
  75413. this.buttonX = this.browserGamepad.buttons[2].value;
  75414. this.buttonY = this.browserGamepad.buttons[3].value;
  75415. this.buttonLB = this.browserGamepad.buttons[4].value;
  75416. this.buttonRB = this.browserGamepad.buttons[5].value;
  75417. this.leftTrigger = this.browserGamepad.axes[2];
  75418. this.rightTrigger = this.browserGamepad.axes[5];
  75419. this.buttonBack = this.browserGamepad.buttons[9].value;
  75420. this.buttonStart = this.browserGamepad.buttons[8].value;
  75421. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  75422. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  75423. this.dPadUp = this.browserGamepad.buttons[11].value;
  75424. this.dPadDown = this.browserGamepad.buttons[12].value;
  75425. this.dPadLeft = this.browserGamepad.buttons[13].value;
  75426. this.dPadRight = this.browserGamepad.buttons[14].value;
  75427. }
  75428. else {
  75429. this.buttonA = this.browserGamepad.buttons[0].value;
  75430. this.buttonB = this.browserGamepad.buttons[1].value;
  75431. this.buttonX = this.browserGamepad.buttons[2].value;
  75432. this.buttonY = this.browserGamepad.buttons[3].value;
  75433. this.buttonLB = this.browserGamepad.buttons[4].value;
  75434. this.buttonRB = this.browserGamepad.buttons[5].value;
  75435. this.leftTrigger = this.browserGamepad.buttons[6].value;
  75436. this.rightTrigger = this.browserGamepad.buttons[7].value;
  75437. this.buttonBack = this.browserGamepad.buttons[8].value;
  75438. this.buttonStart = this.browserGamepad.buttons[9].value;
  75439. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  75440. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  75441. this.dPadUp = this.browserGamepad.buttons[12].value;
  75442. this.dPadDown = this.browserGamepad.buttons[13].value;
  75443. this.dPadLeft = this.browserGamepad.buttons[14].value;
  75444. this.dPadRight = this.browserGamepad.buttons[15].value;
  75445. }
  75446. };
  75447. Xbox360Pad.prototype.dispose = function () {
  75448. _super.prototype.dispose.call(this);
  75449. this.onButtonDownObservable.clear();
  75450. this.onButtonUpObservable.clear();
  75451. this.onPadDownObservable.clear();
  75452. this.onPadUpObservable.clear();
  75453. };
  75454. return Xbox360Pad;
  75455. }(BABYLON.Gamepad));
  75456. BABYLON.Xbox360Pad = Xbox360Pad;
  75457. })(BABYLON || (BABYLON = {}));
  75458. //# sourceMappingURL=babylon.xboxGamepad.js.map
  75459. var BABYLON;
  75460. (function (BABYLON) {
  75461. /**
  75462. * Defines the types of pose enabled controllers that are supported
  75463. */
  75464. var PoseEnabledControllerType;
  75465. (function (PoseEnabledControllerType) {
  75466. /**
  75467. * HTC Vive
  75468. */
  75469. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  75470. /**
  75471. * Oculus Rift
  75472. */
  75473. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  75474. /**
  75475. * Windows mixed reality
  75476. */
  75477. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  75478. /**
  75479. * Samsung gear VR
  75480. */
  75481. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  75482. /**
  75483. * Google Daydream
  75484. */
  75485. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  75486. /**
  75487. * Generic
  75488. */
  75489. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  75490. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  75491. /**
  75492. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75493. */
  75494. var PoseEnabledControllerHelper = /** @class */ (function () {
  75495. function PoseEnabledControllerHelper() {
  75496. }
  75497. /**
  75498. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75499. * @param vrGamepad the gamepad to initialized
  75500. * @returns a vr controller of the type the gamepad identified as
  75501. */
  75502. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  75503. // Oculus Touch
  75504. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  75505. return new BABYLON.OculusTouchController(vrGamepad);
  75506. }
  75507. // Windows Mixed Reality controllers
  75508. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  75509. return new BABYLON.WindowsMotionController(vrGamepad);
  75510. }
  75511. // HTC Vive
  75512. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  75513. return new BABYLON.ViveController(vrGamepad);
  75514. }
  75515. // Samsung/Oculus Gear VR or Oculus Go
  75516. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  75517. return new BABYLON.GearVRController(vrGamepad);
  75518. }
  75519. // Google Daydream
  75520. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  75521. return new BABYLON.DaydreamController(vrGamepad);
  75522. }
  75523. // Generic
  75524. else {
  75525. return new BABYLON.GenericController(vrGamepad);
  75526. }
  75527. };
  75528. return PoseEnabledControllerHelper;
  75529. }());
  75530. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  75531. /**
  75532. * Defines the PoseEnabledController object that contains state of a vr capable controller
  75533. */
  75534. var PoseEnabledController = /** @class */ (function (_super) {
  75535. __extends(PoseEnabledController, _super);
  75536. /**
  75537. * Creates a new PoseEnabledController from a gamepad
  75538. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  75539. */
  75540. function PoseEnabledController(browserGamepad) {
  75541. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  75542. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  75543. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  75544. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  75545. /**
  75546. * The device position in babylon space
  75547. */
  75548. _this.devicePosition = BABYLON.Vector3.Zero();
  75549. /**
  75550. * The device rotation in babylon space
  75551. */
  75552. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  75553. /**
  75554. * The scale factor of the device in babylon space
  75555. */
  75556. _this.deviceScaleFactor = 1;
  75557. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  75558. /**
  75559. * Internal, matrix used to convert room space to babylon space
  75560. * @hidden
  75561. */
  75562. _this._deviceToWorld = BABYLON.Matrix.Identity();
  75563. /**
  75564. * Node to be used when casting a ray from the controller
  75565. * @hidden
  75566. */
  75567. _this._pointingPoseNode = null;
  75568. _this._workingMatrix = BABYLON.Matrix.Identity();
  75569. /**
  75570. * @hidden
  75571. */
  75572. _this._meshAttachedObservable = new BABYLON.Observable();
  75573. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  75574. _this.controllerType = PoseEnabledControllerType.GENERIC;
  75575. _this.position = BABYLON.Vector3.Zero();
  75576. _this.rotationQuaternion = new BABYLON.Quaternion();
  75577. _this._calculatedPosition = BABYLON.Vector3.Zero();
  75578. _this._calculatedRotation = new BABYLON.Quaternion();
  75579. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  75580. return _this;
  75581. }
  75582. /**
  75583. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  75584. */
  75585. PoseEnabledController.prototype.update = function () {
  75586. _super.prototype.update.call(this);
  75587. this._updatePoseAndMesh();
  75588. };
  75589. /**
  75590. * Updates only the pose device and mesh without doing any button event checking
  75591. */
  75592. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  75593. var pose = this.browserGamepad.pose;
  75594. this.updateFromDevice(pose);
  75595. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  75596. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  75597. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  75598. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  75599. if (this._mesh) {
  75600. this._mesh.position.copyFrom(this.devicePosition);
  75601. if (this._mesh.rotationQuaternion) {
  75602. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  75603. }
  75604. }
  75605. };
  75606. /**
  75607. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75608. * @param poseData raw pose fromthe device
  75609. */
  75610. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  75611. if (poseData) {
  75612. this.rawPose = poseData;
  75613. if (poseData.position) {
  75614. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  75615. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  75616. this._deviceRoomPosition.z *= -1;
  75617. }
  75618. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  75619. this._calculatedPosition.addInPlace(this.position);
  75620. }
  75621. var pose = this.rawPose;
  75622. if (poseData.orientation && pose.orientation) {
  75623. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  75624. if (this._mesh) {
  75625. if (this._mesh.getScene().useRightHandedSystem) {
  75626. this._deviceRoomRotationQuaternion.z *= -1;
  75627. this._deviceRoomRotationQuaternion.w *= -1;
  75628. }
  75629. else {
  75630. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  75631. }
  75632. }
  75633. // if the camera is set, rotate to the camera's rotation
  75634. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  75635. }
  75636. }
  75637. };
  75638. /**
  75639. * Attaches a mesh to the controller
  75640. * @param mesh the mesh to be attached
  75641. */
  75642. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  75643. if (this._mesh) {
  75644. this._mesh.parent = null;
  75645. }
  75646. this._mesh = mesh;
  75647. if (this._poseControlledCamera) {
  75648. this._mesh.parent = this._poseControlledCamera;
  75649. }
  75650. if (!this._mesh.rotationQuaternion) {
  75651. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  75652. }
  75653. // 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
  75654. this._updatePoseAndMesh();
  75655. if (this._pointingPoseNode) {
  75656. var parents = [];
  75657. var obj = this._pointingPoseNode;
  75658. while (obj.parent) {
  75659. parents.push(obj.parent);
  75660. obj = obj.parent;
  75661. }
  75662. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  75663. }
  75664. this._meshAttachedObservable.notifyObservers(mesh);
  75665. };
  75666. /**
  75667. * Attaches the controllers mesh to a camera
  75668. * @param camera the camera the mesh should be attached to
  75669. */
  75670. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  75671. this._poseControlledCamera = camera;
  75672. if (this._mesh) {
  75673. this._mesh.parent = this._poseControlledCamera;
  75674. }
  75675. };
  75676. /**
  75677. * Disposes of the controller
  75678. */
  75679. PoseEnabledController.prototype.dispose = function () {
  75680. if (this._mesh) {
  75681. this._mesh.dispose();
  75682. }
  75683. this._mesh = null;
  75684. _super.prototype.dispose.call(this);
  75685. };
  75686. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  75687. /**
  75688. * The mesh that is attached to the controller
  75689. */
  75690. get: function () {
  75691. return this._mesh;
  75692. },
  75693. enumerable: true,
  75694. configurable: true
  75695. });
  75696. /**
  75697. * Gets the ray of the controller in the direction the controller is pointing
  75698. * @param length the length the resulting ray should be
  75699. * @returns a ray in the direction the controller is pointing
  75700. */
  75701. PoseEnabledController.prototype.getForwardRay = function (length) {
  75702. if (length === void 0) { length = 100; }
  75703. if (!this.mesh) {
  75704. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  75705. }
  75706. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  75707. var origin = m.getTranslation();
  75708. var forward = new BABYLON.Vector3(0, 0, -1);
  75709. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  75710. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  75711. return new BABYLON.Ray(origin, direction, length);
  75712. };
  75713. /**
  75714. * Name of the child mesh that can be used to cast a ray from the controller
  75715. */
  75716. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  75717. return PoseEnabledController;
  75718. }(BABYLON.Gamepad));
  75719. BABYLON.PoseEnabledController = PoseEnabledController;
  75720. })(BABYLON || (BABYLON = {}));
  75721. //# sourceMappingURL=babylon.poseEnabledController.js.map
  75722. var BABYLON;
  75723. (function (BABYLON) {
  75724. /**
  75725. * Defines the WebVRController object that represents controllers tracked in 3D space
  75726. */
  75727. var WebVRController = /** @class */ (function (_super) {
  75728. __extends(WebVRController, _super);
  75729. /**
  75730. * Creates a new WebVRController from a gamepad
  75731. * @param vrGamepad the gamepad that the WebVRController should be created from
  75732. */
  75733. function WebVRController(vrGamepad) {
  75734. var _this = _super.call(this, vrGamepad) || this;
  75735. // Observables
  75736. /**
  75737. * Fired when the trigger state has changed
  75738. */
  75739. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  75740. /**
  75741. * Fired when the main button state has changed
  75742. */
  75743. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  75744. /**
  75745. * Fired when the secondary button state has changed
  75746. */
  75747. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  75748. /**
  75749. * Fired when the pad state has changed
  75750. */
  75751. _this.onPadStateChangedObservable = new BABYLON.Observable();
  75752. /**
  75753. * Fired when controllers stick values have changed
  75754. */
  75755. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  75756. /**
  75757. * X and Y axis corrisponding to the controllers joystick
  75758. */
  75759. _this.pad = { x: 0, y: 0 };
  75760. // avoid GC, store state in a tmp object
  75761. _this._changes = {
  75762. pressChanged: false,
  75763. touchChanged: false,
  75764. valueChanged: false,
  75765. changed: false
  75766. };
  75767. _this._buttons = new Array(vrGamepad.buttons.length);
  75768. _this.hand = vrGamepad.hand;
  75769. return _this;
  75770. }
  75771. /**
  75772. * Fired when a controller button's state has changed
  75773. * @param callback the callback containing the button that was modified
  75774. */
  75775. WebVRController.prototype.onButtonStateChange = function (callback) {
  75776. this._onButtonStateChange = callback;
  75777. };
  75778. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  75779. /**
  75780. * The default controller model for the controller
  75781. */
  75782. get: function () {
  75783. return this._defaultModel;
  75784. },
  75785. enumerable: true,
  75786. configurable: true
  75787. });
  75788. /**
  75789. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  75790. */
  75791. WebVRController.prototype.update = function () {
  75792. _super.prototype.update.call(this);
  75793. for (var index = 0; index < this._buttons.length; index++) {
  75794. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  75795. }
  75796. ;
  75797. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  75798. this.pad.x = this.leftStick.x;
  75799. this.pad.y = this.leftStick.y;
  75800. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  75801. }
  75802. };
  75803. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  75804. if (!newState) {
  75805. newState = {
  75806. pressed: false,
  75807. touched: false,
  75808. value: 0
  75809. };
  75810. }
  75811. if (!currentState) {
  75812. this._buttons[buttonIndex] = {
  75813. pressed: newState.pressed,
  75814. touched: newState.touched,
  75815. value: newState.value
  75816. };
  75817. return;
  75818. }
  75819. this._checkChanges(newState, currentState);
  75820. if (this._changes.changed) {
  75821. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  75822. this._handleButtonChange(buttonIndex, newState, this._changes);
  75823. }
  75824. this._buttons[buttonIndex].pressed = newState.pressed;
  75825. this._buttons[buttonIndex].touched = newState.touched;
  75826. // oculus triggers are never 0, thou not touched.
  75827. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  75828. };
  75829. WebVRController.prototype._checkChanges = function (newState, currentState) {
  75830. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  75831. this._changes.touchChanged = newState.touched !== currentState.touched;
  75832. this._changes.valueChanged = newState.value !== currentState.value;
  75833. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  75834. return this._changes;
  75835. };
  75836. /**
  75837. * Disposes of th webVRCOntroller
  75838. */
  75839. WebVRController.prototype.dispose = function () {
  75840. _super.prototype.dispose.call(this);
  75841. this.onTriggerStateChangedObservable.clear();
  75842. this.onMainButtonStateChangedObservable.clear();
  75843. this.onSecondaryButtonStateChangedObservable.clear();
  75844. this.onPadStateChangedObservable.clear();
  75845. this.onPadValuesChangedObservable.clear();
  75846. };
  75847. return WebVRController;
  75848. }(BABYLON.PoseEnabledController));
  75849. BABYLON.WebVRController = WebVRController;
  75850. })(BABYLON || (BABYLON = {}));
  75851. //# sourceMappingURL=babylon.webVRController.js.map
  75852. var BABYLON;
  75853. (function (BABYLON) {
  75854. /**
  75855. * Oculus Touch Controller
  75856. */
  75857. var OculusTouchController = /** @class */ (function (_super) {
  75858. __extends(OculusTouchController, _super);
  75859. /**
  75860. * Creates a new OculusTouchController from a gamepad
  75861. * @param vrGamepad the gamepad that the controller should be created from
  75862. */
  75863. function OculusTouchController(vrGamepad) {
  75864. var _this = _super.call(this, vrGamepad) || this;
  75865. /**
  75866. * Fired when the secondary trigger on this controller is modified
  75867. */
  75868. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  75869. /**
  75870. * Fired when the thumb rest on this controller is modified
  75871. */
  75872. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  75873. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  75874. return _this;
  75875. }
  75876. /**
  75877. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75878. * @param scene scene in which to add meshes
  75879. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75880. */
  75881. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75882. var _this = this;
  75883. var meshName;
  75884. // Hand
  75885. if (this.hand === 'left') {
  75886. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  75887. }
  75888. else { // Right is the default if no hand is specified
  75889. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  75890. }
  75891. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  75892. /*
  75893. Parent Mesh name: oculus_touch_left
  75894. - body
  75895. - trigger
  75896. - thumbstick
  75897. - grip
  75898. - button_y
  75899. - button_x
  75900. - button_enter
  75901. */
  75902. _this._defaultModel = newMeshes[1];
  75903. _this.attachToMesh(_this._defaultModel);
  75904. if (meshLoaded) {
  75905. meshLoaded(_this._defaultModel);
  75906. }
  75907. });
  75908. };
  75909. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  75910. /**
  75911. * Fired when the A button on this controller is modified
  75912. */
  75913. get: function () {
  75914. if (this.hand === 'right') {
  75915. return this.onMainButtonStateChangedObservable;
  75916. }
  75917. else {
  75918. throw new Error('No A button on left hand');
  75919. }
  75920. },
  75921. enumerable: true,
  75922. configurable: true
  75923. });
  75924. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  75925. /**
  75926. * Fired when the B button on this controller is modified
  75927. */
  75928. get: function () {
  75929. if (this.hand === 'right') {
  75930. return this.onSecondaryButtonStateChangedObservable;
  75931. }
  75932. else {
  75933. throw new Error('No B button on left hand');
  75934. }
  75935. },
  75936. enumerable: true,
  75937. configurable: true
  75938. });
  75939. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  75940. /**
  75941. * Fired when the X button on this controller is modified
  75942. */
  75943. get: function () {
  75944. if (this.hand === 'left') {
  75945. return this.onMainButtonStateChangedObservable;
  75946. }
  75947. else {
  75948. throw new Error('No X button on right hand');
  75949. }
  75950. },
  75951. enumerable: true,
  75952. configurable: true
  75953. });
  75954. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  75955. /**
  75956. * Fired when the Y button on this controller is modified
  75957. */
  75958. get: function () {
  75959. if (this.hand === 'left') {
  75960. return this.onSecondaryButtonStateChangedObservable;
  75961. }
  75962. else {
  75963. throw new Error('No Y button on right hand');
  75964. }
  75965. },
  75966. enumerable: true,
  75967. configurable: true
  75968. });
  75969. /**
  75970. * Called once for each button that changed state since the last frame
  75971. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  75972. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  75973. * 2) secondary trigger (same)
  75974. * 3) A (right) X (left), touch, pressed = value
  75975. * 4) B / Y
  75976. * 5) thumb rest
  75977. * @param buttonIdx Which button index changed
  75978. * @param state New state of the button
  75979. * @param changes Which properties on the state changed since last frame
  75980. */
  75981. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75982. var notifyObject = state; //{ state: state, changes: changes };
  75983. var triggerDirection = this.hand === 'right' ? -1 : 1;
  75984. switch (buttonIdx) {
  75985. case 0:
  75986. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  75987. return;
  75988. case 1: // index trigger
  75989. if (this._defaultModel) {
  75990. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  75991. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  75992. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  75993. }
  75994. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  75995. return;
  75996. case 2: // secondary trigger
  75997. if (this._defaultModel) {
  75998. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  75999. }
  76000. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  76001. return;
  76002. case 3:
  76003. if (this._defaultModel) {
  76004. if (notifyObject.pressed) {
  76005. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  76006. }
  76007. else {
  76008. (this._defaultModel.getChildren()[1]).position.y = 0;
  76009. }
  76010. }
  76011. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  76012. return;
  76013. case 4:
  76014. if (this._defaultModel) {
  76015. if (notifyObject.pressed) {
  76016. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  76017. }
  76018. else {
  76019. (this._defaultModel.getChildren()[2]).position.y = 0;
  76020. }
  76021. }
  76022. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  76023. return;
  76024. case 5:
  76025. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  76026. return;
  76027. }
  76028. };
  76029. /**
  76030. * Base Url for the controller model.
  76031. */
  76032. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  76033. /**
  76034. * File name for the left controller model.
  76035. */
  76036. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  76037. /**
  76038. * File name for the right controller model.
  76039. */
  76040. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  76041. return OculusTouchController;
  76042. }(BABYLON.WebVRController));
  76043. BABYLON.OculusTouchController = OculusTouchController;
  76044. })(BABYLON || (BABYLON = {}));
  76045. //# sourceMappingURL=babylon.oculusTouchController.js.map
  76046. var BABYLON;
  76047. (function (BABYLON) {
  76048. /**
  76049. * Vive Controller
  76050. */
  76051. var ViveController = /** @class */ (function (_super) {
  76052. __extends(ViveController, _super);
  76053. /**
  76054. * Creates a new ViveController from a gamepad
  76055. * @param vrGamepad the gamepad that the controller should be created from
  76056. */
  76057. function ViveController(vrGamepad) {
  76058. var _this = _super.call(this, vrGamepad) || this;
  76059. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  76060. _this._invertLeftStickY = true;
  76061. return _this;
  76062. }
  76063. /**
  76064. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76065. * @param scene scene in which to add meshes
  76066. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76067. */
  76068. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76069. var _this = this;
  76070. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  76071. /*
  76072. Parent Mesh name: ViveWand
  76073. - body
  76074. - r_gripper
  76075. - l_gripper
  76076. - menu_button
  76077. - system_button
  76078. - trackpad
  76079. - trigger
  76080. - LED
  76081. */
  76082. _this._defaultModel = newMeshes[1];
  76083. _this.attachToMesh(_this._defaultModel);
  76084. if (meshLoaded) {
  76085. meshLoaded(_this._defaultModel);
  76086. }
  76087. });
  76088. };
  76089. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  76090. /**
  76091. * Fired when the left button on this controller is modified
  76092. */
  76093. get: function () {
  76094. return this.onMainButtonStateChangedObservable;
  76095. },
  76096. enumerable: true,
  76097. configurable: true
  76098. });
  76099. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  76100. /**
  76101. * Fired when the right button on this controller is modified
  76102. */
  76103. get: function () {
  76104. return this.onMainButtonStateChangedObservable;
  76105. },
  76106. enumerable: true,
  76107. configurable: true
  76108. });
  76109. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  76110. /**
  76111. * Fired when the menu button on this controller is modified
  76112. */
  76113. get: function () {
  76114. return this.onSecondaryButtonStateChangedObservable;
  76115. },
  76116. enumerable: true,
  76117. configurable: true
  76118. });
  76119. /**
  76120. * Called once for each button that changed state since the last frame
  76121. * Vive mapping:
  76122. * 0: touchpad
  76123. * 1: trigger
  76124. * 2: left AND right buttons
  76125. * 3: menu button
  76126. * @param buttonIdx Which button index changed
  76127. * @param state New state of the button
  76128. * @param changes Which properties on the state changed since last frame
  76129. */
  76130. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76131. var notifyObject = state; //{ state: state, changes: changes };
  76132. switch (buttonIdx) {
  76133. case 0:
  76134. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  76135. return;
  76136. case 1: // index trigger
  76137. if (this._defaultModel) {
  76138. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  76139. }
  76140. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  76141. return;
  76142. case 2: // left AND right button
  76143. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  76144. return;
  76145. case 3:
  76146. if (this._defaultModel) {
  76147. if (notifyObject.pressed) {
  76148. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  76149. }
  76150. else {
  76151. (this._defaultModel.getChildren()[2]).position.y = 0;
  76152. }
  76153. }
  76154. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  76155. return;
  76156. }
  76157. };
  76158. /**
  76159. * Base Url for the controller model.
  76160. */
  76161. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  76162. /**
  76163. * File name for the controller model.
  76164. */
  76165. ViveController.MODEL_FILENAME = 'wand.babylon';
  76166. return ViveController;
  76167. }(BABYLON.WebVRController));
  76168. BABYLON.ViveController = ViveController;
  76169. })(BABYLON || (BABYLON = {}));
  76170. //# sourceMappingURL=babylon.viveController.js.map
  76171. var BABYLON;
  76172. (function (BABYLON) {
  76173. /**
  76174. * Generic Controller
  76175. */
  76176. var GenericController = /** @class */ (function (_super) {
  76177. __extends(GenericController, _super);
  76178. /**
  76179. * Creates a new GenericController from a gamepad
  76180. * @param vrGamepad the gamepad that the controller should be created from
  76181. */
  76182. function GenericController(vrGamepad) {
  76183. return _super.call(this, vrGamepad) || this;
  76184. }
  76185. /**
  76186. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76187. * @param scene scene in which to add meshes
  76188. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76189. */
  76190. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76191. var _this = this;
  76192. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  76193. _this._defaultModel = newMeshes[1];
  76194. _this.attachToMesh(_this._defaultModel);
  76195. if (meshLoaded) {
  76196. meshLoaded(_this._defaultModel);
  76197. }
  76198. });
  76199. };
  76200. /**
  76201. * Called once for each button that changed state since the last frame
  76202. * @param buttonIdx Which button index changed
  76203. * @param state New state of the button
  76204. * @param changes Which properties on the state changed since last frame
  76205. */
  76206. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76207. console.log("Button id: " + buttonIdx + "state: ");
  76208. console.dir(state);
  76209. };
  76210. /**
  76211. * Base Url for the controller model.
  76212. */
  76213. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76214. /**
  76215. * File name for the controller model.
  76216. */
  76217. GenericController.MODEL_FILENAME = 'generic.babylon';
  76218. return GenericController;
  76219. }(BABYLON.WebVRController));
  76220. BABYLON.GenericController = GenericController;
  76221. })(BABYLON || (BABYLON = {}));
  76222. //# sourceMappingURL=babylon.genericController.js.map
  76223. var BABYLON;
  76224. (function (BABYLON) {
  76225. /**
  76226. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  76227. */
  76228. var LoadedMeshInfo = /** @class */ (function () {
  76229. function LoadedMeshInfo() {
  76230. /**
  76231. * Map of the button meshes contained in the controller
  76232. */
  76233. this.buttonMeshes = {};
  76234. /**
  76235. * Map of the axis meshes contained in the controller
  76236. */
  76237. this.axisMeshes = {};
  76238. }
  76239. return LoadedMeshInfo;
  76240. }());
  76241. /**
  76242. * Defines the WindowsMotionController object that the state of the windows motion controller
  76243. */
  76244. var WindowsMotionController = /** @class */ (function (_super) {
  76245. __extends(WindowsMotionController, _super);
  76246. /**
  76247. * Creates a new WindowsMotionController from a gamepad
  76248. * @param vrGamepad the gamepad that the controller should be created from
  76249. */
  76250. function WindowsMotionController(vrGamepad) {
  76251. var _this = _super.call(this, vrGamepad) || this;
  76252. _this._mapping = {
  76253. // Semantic button names
  76254. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  76255. // A mapping of the button name to glTF model node name
  76256. // that should be transformed by button value.
  76257. buttonMeshNames: {
  76258. 'trigger': 'SELECT',
  76259. 'menu': 'MENU',
  76260. 'grip': 'GRASP',
  76261. 'thumbstick': 'THUMBSTICK_PRESS',
  76262. 'trackpad': 'TOUCHPAD_PRESS'
  76263. },
  76264. // This mapping is used to translate from the Motion Controller to Babylon semantics
  76265. buttonObservableNames: {
  76266. 'trigger': 'onTriggerStateChangedObservable',
  76267. 'menu': 'onSecondaryButtonStateChangedObservable',
  76268. 'grip': 'onMainButtonStateChangedObservable',
  76269. 'thumbstick': 'onPadStateChangedObservable',
  76270. 'trackpad': 'onTrackpadChangedObservable'
  76271. },
  76272. // A mapping of the axis name to glTF model node name
  76273. // that should be transformed by axis value.
  76274. // This array mirrors the browserGamepad.axes array, such that
  76275. // the mesh corresponding to axis 0 is in this array index 0.
  76276. axisMeshNames: [
  76277. 'THUMBSTICK_X',
  76278. 'THUMBSTICK_Y',
  76279. 'TOUCHPAD_TOUCH_X',
  76280. 'TOUCHPAD_TOUCH_Y'
  76281. ],
  76282. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  76283. };
  76284. /**
  76285. * Fired when the trackpad on this controller is clicked
  76286. */
  76287. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  76288. /**
  76289. * Fired when the trackpad on this controller is modified
  76290. */
  76291. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  76292. /**
  76293. * The current x and y values of this controller's trackpad
  76294. */
  76295. _this.trackpad = { x: 0, y: 0 };
  76296. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  76297. _this._loadedMeshInfo = null;
  76298. return _this;
  76299. }
  76300. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  76301. /**
  76302. * Fired when the trigger on this controller is modified
  76303. */
  76304. get: function () {
  76305. return this.onTriggerStateChangedObservable;
  76306. },
  76307. enumerable: true,
  76308. configurable: true
  76309. });
  76310. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  76311. /**
  76312. * Fired when the menu button on this controller is modified
  76313. */
  76314. get: function () {
  76315. return this.onSecondaryButtonStateChangedObservable;
  76316. },
  76317. enumerable: true,
  76318. configurable: true
  76319. });
  76320. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  76321. /**
  76322. * Fired when the grip button on this controller is modified
  76323. */
  76324. get: function () {
  76325. return this.onMainButtonStateChangedObservable;
  76326. },
  76327. enumerable: true,
  76328. configurable: true
  76329. });
  76330. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  76331. /**
  76332. * Fired when the thumbstick button on this controller is modified
  76333. */
  76334. get: function () {
  76335. return this.onPadStateChangedObservable;
  76336. },
  76337. enumerable: true,
  76338. configurable: true
  76339. });
  76340. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  76341. /**
  76342. * Fired when the touchpad button on this controller is modified
  76343. */
  76344. get: function () {
  76345. return this.onTrackpadChangedObservable;
  76346. },
  76347. enumerable: true,
  76348. configurable: true
  76349. });
  76350. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  76351. /**
  76352. * Fired when the touchpad values on this controller are modified
  76353. */
  76354. get: function () {
  76355. return this.onTrackpadValuesChangedObservable;
  76356. },
  76357. enumerable: true,
  76358. configurable: true
  76359. });
  76360. WindowsMotionController.prototype._updateTrackpad = function () {
  76361. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  76362. this.trackpad.x = this.browserGamepad["axes"][2];
  76363. this.trackpad.y = this.browserGamepad["axes"][3];
  76364. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  76365. }
  76366. };
  76367. /**
  76368. * Called once per frame by the engine.
  76369. */
  76370. WindowsMotionController.prototype.update = function () {
  76371. _super.prototype.update.call(this);
  76372. if (this.browserGamepad.axes) {
  76373. this._updateTrackpad();
  76374. // Only need to animate axes if there is a loaded mesh
  76375. if (this._loadedMeshInfo) {
  76376. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  76377. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  76378. }
  76379. }
  76380. }
  76381. };
  76382. /**
  76383. * Called once for each button that changed state since the last frame
  76384. * @param buttonIdx Which button index changed
  76385. * @param state New state of the button
  76386. * @param changes Which properties on the state changed since last frame
  76387. */
  76388. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76389. var buttonName = this._mapping.buttons[buttonIdx];
  76390. if (!buttonName) {
  76391. return;
  76392. }
  76393. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  76394. this._updateTrackpad();
  76395. // Only emit events for buttons that we know how to map from index to name
  76396. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  76397. if (observable) {
  76398. observable.notifyObservers(state);
  76399. }
  76400. this._lerpButtonTransform(buttonName, state.value);
  76401. };
  76402. /**
  76403. * Moves the buttons on the controller mesh based on their current state
  76404. * @param buttonName the name of the button to move
  76405. * @param buttonValue the value of the button which determines the buttons new position
  76406. */
  76407. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  76408. // If there is no loaded mesh, there is nothing to transform.
  76409. if (!this._loadedMeshInfo) {
  76410. return;
  76411. }
  76412. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  76413. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76414. return;
  76415. }
  76416. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  76417. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  76418. };
  76419. /**
  76420. * Moves the axis on the controller mesh based on its current state
  76421. * @param axis the index of the axis
  76422. * @param axisValue the value of the axis which determines the meshes new position
  76423. * @hidden
  76424. */
  76425. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  76426. if (!this._loadedMeshInfo) {
  76427. return;
  76428. }
  76429. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  76430. if (!meshInfo) {
  76431. return;
  76432. }
  76433. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76434. return;
  76435. }
  76436. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  76437. var lerpValue = axisValue * 0.5 + 0.5;
  76438. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  76439. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  76440. };
  76441. /**
  76442. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76443. * @param scene scene in which to add meshes
  76444. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76445. */
  76446. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  76447. var _this = this;
  76448. if (forceDefault === void 0) { forceDefault = false; }
  76449. var path;
  76450. var filename;
  76451. // Checking if GLB loader is present
  76452. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  76453. // Determine the device specific folder based on the ID suffix
  76454. var device = 'default';
  76455. if (this.id && !forceDefault) {
  76456. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  76457. device = ((match && match[0]) || device);
  76458. }
  76459. // Hand
  76460. if (this.hand === 'left') {
  76461. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  76462. }
  76463. else { // Right is the default if no hand is specified
  76464. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  76465. }
  76466. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  76467. }
  76468. else {
  76469. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  76470. path = BABYLON.GenericController.MODEL_BASE_URL;
  76471. filename = BABYLON.GenericController.MODEL_FILENAME;
  76472. }
  76473. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  76474. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  76475. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  76476. if (!_this._loadedMeshInfo) {
  76477. return;
  76478. }
  76479. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  76480. _this.attachToMesh(_this._defaultModel);
  76481. if (meshLoaded) {
  76482. meshLoaded(_this._defaultModel);
  76483. }
  76484. }, null, function (scene, message) {
  76485. BABYLON.Tools.Log(message);
  76486. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  76487. if (!forceDefault) {
  76488. _this.initControllerMesh(scene, meshLoaded, true);
  76489. }
  76490. });
  76491. };
  76492. /**
  76493. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  76494. * can be transformed by button presses and axes values, based on this._mapping.
  76495. *
  76496. * @param scene scene in which the meshes exist
  76497. * @param meshes list of meshes that make up the controller model to process
  76498. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  76499. */
  76500. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  76501. var loadedMeshInfo = null;
  76502. // Create a new mesh to contain the glTF hierarchy
  76503. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  76504. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  76505. var childMesh = null;
  76506. for (var i = 0; i < meshes.length; i++) {
  76507. var mesh = meshes[i];
  76508. if (!mesh.parent) {
  76509. // Exclude controller meshes from picking results
  76510. mesh.isPickable = false;
  76511. // Handle root node, attach to the new parentMesh
  76512. childMesh = mesh;
  76513. break;
  76514. }
  76515. }
  76516. if (childMesh) {
  76517. childMesh.setParent(parentMesh);
  76518. // Create our mesh info. Note that this method will always return non-null.
  76519. loadedMeshInfo = this.createMeshInfo(parentMesh);
  76520. }
  76521. else {
  76522. BABYLON.Tools.Warn('Could not find root node in model file.');
  76523. }
  76524. return loadedMeshInfo;
  76525. };
  76526. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  76527. var loadedMeshInfo = new LoadedMeshInfo();
  76528. var i;
  76529. loadedMeshInfo.rootNode = rootNode;
  76530. // Reset the caches
  76531. loadedMeshInfo.buttonMeshes = {};
  76532. loadedMeshInfo.axisMeshes = {};
  76533. // Button Meshes
  76534. for (i = 0; i < this._mapping.buttons.length; i++) {
  76535. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  76536. if (!buttonMeshName) {
  76537. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  76538. continue;
  76539. }
  76540. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  76541. if (!buttonMesh) {
  76542. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  76543. continue;
  76544. }
  76545. var buttonMeshInfo = {
  76546. index: i,
  76547. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  76548. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  76549. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  76550. };
  76551. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  76552. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  76553. }
  76554. else {
  76555. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  76556. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  76557. '(VALUE: ' + !!buttonMeshInfo.value +
  76558. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  76559. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  76560. ')');
  76561. }
  76562. }
  76563. // Axis Meshes
  76564. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  76565. var axisMeshName = this._mapping.axisMeshNames[i];
  76566. if (!axisMeshName) {
  76567. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  76568. continue;
  76569. }
  76570. var axisMesh = getChildByName(rootNode, axisMeshName);
  76571. if (!axisMesh) {
  76572. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  76573. continue;
  76574. }
  76575. var axisMeshInfo = {
  76576. index: i,
  76577. value: getImmediateChildByName(axisMesh, 'VALUE'),
  76578. min: getImmediateChildByName(axisMesh, 'MIN'),
  76579. max: getImmediateChildByName(axisMesh, 'MAX')
  76580. };
  76581. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  76582. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  76583. }
  76584. else {
  76585. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  76586. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  76587. '(VALUE: ' + !!axisMeshInfo.value +
  76588. ', MIN: ' + !!axisMeshInfo.min +
  76589. ', MAX:' + !!axisMeshInfo.max +
  76590. ')');
  76591. }
  76592. }
  76593. // Pointing Ray
  76594. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  76595. if (!loadedMeshInfo.pointingPoseNode) {
  76596. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  76597. }
  76598. else {
  76599. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  76600. }
  76601. return loadedMeshInfo;
  76602. // Look through all children recursively. This will return null if no mesh exists with the given name.
  76603. function getChildByName(node, name) {
  76604. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  76605. }
  76606. // Look through only immediate children. This will return null if no mesh exists with the given name.
  76607. function getImmediateChildByName(node, name) {
  76608. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  76609. }
  76610. };
  76611. /**
  76612. * Gets the ray of the controller in the direction the controller is pointing
  76613. * @param length the length the resulting ray should be
  76614. * @returns a ray in the direction the controller is pointing
  76615. */
  76616. WindowsMotionController.prototype.getForwardRay = function (length) {
  76617. if (length === void 0) { length = 100; }
  76618. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  76619. return _super.prototype.getForwardRay.call(this, length);
  76620. }
  76621. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  76622. var origin = m.getTranslation();
  76623. var forward = new BABYLON.Vector3(0, 0, -1);
  76624. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  76625. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  76626. return new BABYLON.Ray(origin, direction, length);
  76627. };
  76628. /**
  76629. * Disposes of the controller
  76630. */
  76631. WindowsMotionController.prototype.dispose = function () {
  76632. _super.prototype.dispose.call(this);
  76633. this.onTrackpadChangedObservable.clear();
  76634. };
  76635. /**
  76636. * The base url used to load the left and right controller models
  76637. */
  76638. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  76639. /**
  76640. * The name of the left controller model file
  76641. */
  76642. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  76643. /**
  76644. * The name of the right controller model file
  76645. */
  76646. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  76647. /**
  76648. * The controller name prefix for this controller type
  76649. */
  76650. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  76651. /**
  76652. * The controller id pattern for this controller type
  76653. */
  76654. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  76655. return WindowsMotionController;
  76656. }(BABYLON.WebVRController));
  76657. BABYLON.WindowsMotionController = WindowsMotionController;
  76658. })(BABYLON || (BABYLON = {}));
  76659. //# sourceMappingURL=babylon.windowsMotionController.js.map
  76660. var BABYLON;
  76661. (function (BABYLON) {
  76662. /**
  76663. * Gear VR Controller
  76664. */
  76665. var GearVRController = /** @class */ (function (_super) {
  76666. __extends(GearVRController, _super);
  76667. /**
  76668. * Creates a new GearVRController from a gamepad
  76669. * @param vrGamepad the gamepad that the controller should be created from
  76670. */
  76671. function GearVRController(vrGamepad) {
  76672. var _this = _super.call(this, vrGamepad) || this;
  76673. _this._maxRotationDistFromHeadset = Math.PI / 5;
  76674. _this._draggedRoomRotation = 0;
  76675. _this._tmpVector = new BABYLON.Vector3();
  76676. _this._buttonIndexToObservableNameMap = [
  76677. 'onTrackpadChangedObservable',
  76678. 'onTriggerStateChangedObservable' // Trigger
  76679. ];
  76680. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  76681. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  76682. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  76683. return _this;
  76684. }
  76685. /**
  76686. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  76687. * @param poseData raw pose fromthe device
  76688. */
  76689. GearVRController.prototype.updateFromDevice = function (poseData) {
  76690. _super.prototype.updateFromDevice.call(this, poseData);
  76691. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  76692. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  76693. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  76694. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  76695. // Find the radian distance away that the headset is from the controllers rotation
  76696. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  76697. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  76698. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  76699. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  76700. this._draggedRoomRotation += rotationAmount;
  76701. // Rotate controller around headset
  76702. var sin = Math.sin(-rotationAmount);
  76703. var cos = Math.cos(-rotationAmount);
  76704. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  76705. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  76706. }
  76707. }
  76708. }
  76709. };
  76710. /**
  76711. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76712. * @param scene scene in which to add meshes
  76713. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76714. */
  76715. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76716. var _this = this;
  76717. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  76718. // Offset the controller so it will rotate around the users wrist
  76719. var mesh = new BABYLON.Mesh("", scene);
  76720. newMeshes[1].parent = mesh;
  76721. newMeshes[1].position.z = -0.15;
  76722. _this._defaultModel = mesh;
  76723. _this.attachToMesh(_this._defaultModel);
  76724. if (meshLoaded) {
  76725. meshLoaded(_this._defaultModel);
  76726. }
  76727. });
  76728. };
  76729. /**
  76730. * Called once for each button that changed state since the last frame
  76731. * @param buttonIdx Which button index changed
  76732. * @param state New state of the button
  76733. * @param changes Which properties on the state changed since last frame
  76734. */
  76735. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76736. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  76737. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  76738. // Only emit events for buttons that we know how to map from index to observable
  76739. var observable = this[observableName];
  76740. if (observable) {
  76741. observable.notifyObservers(state);
  76742. }
  76743. }
  76744. };
  76745. /**
  76746. * Base Url for the controller model.
  76747. */
  76748. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76749. /**
  76750. * File name for the controller model.
  76751. */
  76752. GearVRController.MODEL_FILENAME = 'generic.babylon';
  76753. /**
  76754. * Gamepad Id prefix used to identify this controller.
  76755. */
  76756. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  76757. return GearVRController;
  76758. }(BABYLON.WebVRController));
  76759. BABYLON.GearVRController = GearVRController;
  76760. })(BABYLON || (BABYLON = {}));
  76761. //# sourceMappingURL=babylon.gearVRController.js.map
  76762. var BABYLON;
  76763. (function (BABYLON) {
  76764. /**
  76765. * Google Daydream controller
  76766. */
  76767. var DaydreamController = /** @class */ (function (_super) {
  76768. __extends(DaydreamController, _super);
  76769. /**
  76770. * Creates a new DaydreamController from a gamepad
  76771. * @param vrGamepad the gamepad that the controller should be created from
  76772. */
  76773. function DaydreamController(vrGamepad) {
  76774. var _this = _super.call(this, vrGamepad) || this;
  76775. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  76776. return _this;
  76777. }
  76778. /**
  76779. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76780. * @param scene scene in which to add meshes
  76781. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76782. */
  76783. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76784. var _this = this;
  76785. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  76786. _this._defaultModel = newMeshes[1];
  76787. _this.attachToMesh(_this._defaultModel);
  76788. if (meshLoaded) {
  76789. meshLoaded(_this._defaultModel);
  76790. }
  76791. });
  76792. };
  76793. /**
  76794. * Called once for each button that changed state since the last frame
  76795. * @param buttonIdx Which button index changed
  76796. * @param state New state of the button
  76797. * @param changes Which properties on the state changed since last frame
  76798. */
  76799. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76800. // Daydream controller only has 1 GamepadButton (on the trackpad).
  76801. if (buttonIdx === 0) {
  76802. var observable = this.onTriggerStateChangedObservable;
  76803. if (observable) {
  76804. observable.notifyObservers(state);
  76805. }
  76806. }
  76807. else {
  76808. // If the app or home buttons are ever made available
  76809. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  76810. }
  76811. };
  76812. /**
  76813. * Base Url for the controller model.
  76814. */
  76815. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76816. /**
  76817. * File name for the controller model.
  76818. */
  76819. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  76820. /**
  76821. * Gamepad Id prefix used to identify Daydream Controller.
  76822. */
  76823. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  76824. return DaydreamController;
  76825. }(BABYLON.WebVRController));
  76826. BABYLON.DaydreamController = DaydreamController;
  76827. })(BABYLON || (BABYLON = {}));
  76828. //# sourceMappingURL=babylon.daydreamController.js.map
  76829. var BABYLON;
  76830. (function (BABYLON) {
  76831. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  76832. get: function () {
  76833. if (!this._gamepadManager) {
  76834. this._gamepadManager = new BABYLON.GamepadManager(this);
  76835. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  76836. if (!component) {
  76837. component = new GamepadSystemSceneComponent(this);
  76838. this._addComponent(component);
  76839. }
  76840. }
  76841. return this._gamepadManager;
  76842. },
  76843. enumerable: true,
  76844. configurable: true
  76845. });
  76846. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  76847. this.add(new BABYLON.FreeCameraGamepadInput());
  76848. return this;
  76849. };
  76850. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  76851. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  76852. return this;
  76853. };
  76854. /**
  76855. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  76856. */
  76857. var GamepadSystemSceneComponent = /** @class */ (function () {
  76858. /**
  76859. * Creates a new instance of the component for the given scene
  76860. * @param scene Defines the scene to register the component in
  76861. */
  76862. function GamepadSystemSceneComponent(scene) {
  76863. /**
  76864. * The component name helpfull to identify the component in the list of scene components.
  76865. */
  76866. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  76867. this.scene = scene;
  76868. }
  76869. /**
  76870. * Registers the component in a given scene
  76871. */
  76872. GamepadSystemSceneComponent.prototype.register = function () {
  76873. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  76874. };
  76875. /**
  76876. * Rebuilds the elements related to this component in case of
  76877. * context lost for instance.
  76878. */
  76879. GamepadSystemSceneComponent.prototype.rebuild = function () {
  76880. // Nothing to do for gamepads
  76881. };
  76882. /**
  76883. * Disposes the component and the associated ressources
  76884. */
  76885. GamepadSystemSceneComponent.prototype.dispose = function () {
  76886. var gamepadManager = this.scene._gamepadManager;
  76887. if (gamepadManager) {
  76888. gamepadManager.dispose();
  76889. this.scene._gamepadManager = null;
  76890. }
  76891. };
  76892. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  76893. var gamepadManager = this.scene._gamepadManager;
  76894. if (gamepadManager && gamepadManager._isMonitoring) {
  76895. gamepadManager._checkGamepadsStatus();
  76896. }
  76897. };
  76898. return GamepadSystemSceneComponent;
  76899. }());
  76900. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  76901. })(BABYLON || (BABYLON = {}));
  76902. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  76903. var BABYLON;
  76904. (function (BABYLON) {
  76905. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  76906. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  76907. });
  76908. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  76909. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  76910. });
  76911. var FollowCamera = /** @class */ (function (_super) {
  76912. __extends(FollowCamera, _super);
  76913. function FollowCamera(name, position, scene, lockedTarget) {
  76914. if (lockedTarget === void 0) { lockedTarget = null; }
  76915. var _this = _super.call(this, name, position, scene) || this;
  76916. _this.radius = 12;
  76917. _this.rotationOffset = 0;
  76918. _this.heightOffset = 4;
  76919. _this.cameraAcceleration = 0.05;
  76920. _this.maxCameraSpeed = 20;
  76921. _this.lockedTarget = lockedTarget;
  76922. return _this;
  76923. }
  76924. FollowCamera.prototype.getRadians = function (degrees) {
  76925. return degrees * Math.PI / 180;
  76926. };
  76927. FollowCamera.prototype.follow = function (cameraTarget) {
  76928. if (!cameraTarget)
  76929. return;
  76930. var yRotation;
  76931. if (cameraTarget.rotationQuaternion) {
  76932. var rotMatrix = new BABYLON.Matrix();
  76933. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  76934. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  76935. }
  76936. else {
  76937. yRotation = cameraTarget.rotation.y;
  76938. }
  76939. var radians = this.getRadians(this.rotationOffset) + yRotation;
  76940. var targetPosition = cameraTarget.getAbsolutePosition();
  76941. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  76942. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  76943. var dx = targetX - this.position.x;
  76944. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  76945. var dz = (targetZ) - this.position.z;
  76946. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  76947. var vy = dy * this.cameraAcceleration;
  76948. var vz = dz * this.cameraAcceleration * 2;
  76949. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  76950. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76951. }
  76952. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  76953. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76954. }
  76955. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  76956. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76957. }
  76958. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  76959. this.setTarget(targetPosition);
  76960. };
  76961. /** @hidden */
  76962. FollowCamera.prototype._checkInputs = function () {
  76963. _super.prototype._checkInputs.call(this);
  76964. if (this.lockedTarget) {
  76965. this.follow(this.lockedTarget);
  76966. }
  76967. };
  76968. FollowCamera.prototype.getClassName = function () {
  76969. return "FollowCamera";
  76970. };
  76971. __decorate([
  76972. BABYLON.serialize()
  76973. ], FollowCamera.prototype, "radius", void 0);
  76974. __decorate([
  76975. BABYLON.serialize()
  76976. ], FollowCamera.prototype, "rotationOffset", void 0);
  76977. __decorate([
  76978. BABYLON.serialize()
  76979. ], FollowCamera.prototype, "heightOffset", void 0);
  76980. __decorate([
  76981. BABYLON.serialize()
  76982. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  76983. __decorate([
  76984. BABYLON.serialize()
  76985. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  76986. __decorate([
  76987. BABYLON.serializeAsMeshReference("lockedTargetId")
  76988. ], FollowCamera.prototype, "lockedTarget", void 0);
  76989. return FollowCamera;
  76990. }(BABYLON.TargetCamera));
  76991. BABYLON.FollowCamera = FollowCamera;
  76992. var ArcFollowCamera = /** @class */ (function (_super) {
  76993. __extends(ArcFollowCamera, _super);
  76994. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  76995. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  76996. _this.alpha = alpha;
  76997. _this.beta = beta;
  76998. _this.radius = radius;
  76999. _this.target = target;
  77000. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  77001. _this.follow();
  77002. return _this;
  77003. }
  77004. ArcFollowCamera.prototype.follow = function () {
  77005. if (!this.target) {
  77006. return;
  77007. }
  77008. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  77009. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  77010. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  77011. var targetPosition = this.target.getAbsolutePosition();
  77012. this.position = targetPosition.add(this._cartesianCoordinates);
  77013. this.setTarget(targetPosition);
  77014. };
  77015. /** @hidden */
  77016. ArcFollowCamera.prototype._checkInputs = function () {
  77017. _super.prototype._checkInputs.call(this);
  77018. this.follow();
  77019. };
  77020. ArcFollowCamera.prototype.getClassName = function () {
  77021. return "ArcFollowCamera";
  77022. };
  77023. return ArcFollowCamera;
  77024. }(BABYLON.TargetCamera));
  77025. BABYLON.ArcFollowCamera = ArcFollowCamera;
  77026. })(BABYLON || (BABYLON = {}));
  77027. //# sourceMappingURL=babylon.followCamera.js.map
  77028. var BABYLON;
  77029. (function (BABYLON) {
  77030. // We're mainly based on the logic defined into the FreeCamera code
  77031. var UniversalCamera = /** @class */ (function (_super) {
  77032. __extends(UniversalCamera, _super);
  77033. //-- end properties for backward compatibility for inputs
  77034. function UniversalCamera(name, position, scene) {
  77035. var _this = _super.call(this, name, position, scene) || this;
  77036. _this.inputs.addGamepad();
  77037. return _this;
  77038. }
  77039. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  77040. //-- Begin properties for backward compatibility for inputs
  77041. get: function () {
  77042. var gamepad = this.inputs.attached["gamepad"];
  77043. if (gamepad)
  77044. return gamepad.gamepadAngularSensibility;
  77045. return 0;
  77046. },
  77047. set: function (value) {
  77048. var gamepad = this.inputs.attached["gamepad"];
  77049. if (gamepad)
  77050. gamepad.gamepadAngularSensibility = value;
  77051. },
  77052. enumerable: true,
  77053. configurable: true
  77054. });
  77055. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  77056. get: function () {
  77057. var gamepad = this.inputs.attached["gamepad"];
  77058. if (gamepad)
  77059. return gamepad.gamepadMoveSensibility;
  77060. return 0;
  77061. },
  77062. set: function (value) {
  77063. var gamepad = this.inputs.attached["gamepad"];
  77064. if (gamepad)
  77065. gamepad.gamepadMoveSensibility = value;
  77066. },
  77067. enumerable: true,
  77068. configurable: true
  77069. });
  77070. UniversalCamera.prototype.getClassName = function () {
  77071. return "UniversalCamera";
  77072. };
  77073. return UniversalCamera;
  77074. }(BABYLON.TouchCamera));
  77075. BABYLON.UniversalCamera = UniversalCamera;
  77076. })(BABYLON || (BABYLON = {}));
  77077. //# sourceMappingURL=babylon.universalCamera.js.map
  77078. var BABYLON;
  77079. (function (BABYLON) {
  77080. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  77081. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  77082. });
  77083. // We're mainly based on the logic defined into the FreeCamera code
  77084. var GamepadCamera = /** @class */ (function (_super) {
  77085. __extends(GamepadCamera, _super);
  77086. //-- end properties for backward compatibility for inputs
  77087. function GamepadCamera(name, position, scene) {
  77088. return _super.call(this, name, position, scene) || this;
  77089. }
  77090. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  77091. //-- Begin properties for backward compatibility for inputs
  77092. get: function () {
  77093. var gamepad = this.inputs.attached["gamepad"];
  77094. if (gamepad)
  77095. return gamepad.gamepadAngularSensibility;
  77096. return 0;
  77097. },
  77098. set: function (value) {
  77099. var gamepad = this.inputs.attached["gamepad"];
  77100. if (gamepad)
  77101. gamepad.gamepadAngularSensibility = value;
  77102. },
  77103. enumerable: true,
  77104. configurable: true
  77105. });
  77106. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  77107. get: function () {
  77108. var gamepad = this.inputs.attached["gamepad"];
  77109. if (gamepad)
  77110. return gamepad.gamepadMoveSensibility;
  77111. return 0;
  77112. },
  77113. set: function (value) {
  77114. var gamepad = this.inputs.attached["gamepad"];
  77115. if (gamepad)
  77116. gamepad.gamepadMoveSensibility = value;
  77117. },
  77118. enumerable: true,
  77119. configurable: true
  77120. });
  77121. GamepadCamera.prototype.getClassName = function () {
  77122. return "GamepadCamera";
  77123. };
  77124. return GamepadCamera;
  77125. }(BABYLON.UniversalCamera));
  77126. BABYLON.GamepadCamera = GamepadCamera;
  77127. })(BABYLON || (BABYLON = {}));
  77128. //# sourceMappingURL=babylon.gamepadCamera.js.map
  77129. var BABYLON;
  77130. (function (BABYLON) {
  77131. var PostProcessRenderPipelineManager = /** @class */ (function () {
  77132. function PostProcessRenderPipelineManager() {
  77133. this._renderPipelines = {};
  77134. }
  77135. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  77136. this._renderPipelines[renderPipeline._name] = renderPipeline;
  77137. };
  77138. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  77139. if (unique === void 0) { unique = false; }
  77140. var renderPipeline = this._renderPipelines[renderPipelineName];
  77141. if (!renderPipeline) {
  77142. return;
  77143. }
  77144. renderPipeline._attachCameras(cameras, unique);
  77145. };
  77146. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  77147. var renderPipeline = this._renderPipelines[renderPipelineName];
  77148. if (!renderPipeline) {
  77149. return;
  77150. }
  77151. renderPipeline._detachCameras(cameras);
  77152. };
  77153. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77154. var renderPipeline = this._renderPipelines[renderPipelineName];
  77155. if (!renderPipeline) {
  77156. return;
  77157. }
  77158. renderPipeline._enableEffect(renderEffectName, cameras);
  77159. };
  77160. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77161. var renderPipeline = this._renderPipelines[renderPipelineName];
  77162. if (!renderPipeline) {
  77163. return;
  77164. }
  77165. renderPipeline._disableEffect(renderEffectName, cameras);
  77166. };
  77167. PostProcessRenderPipelineManager.prototype.update = function () {
  77168. for (var renderPipelineName in this._renderPipelines) {
  77169. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77170. var pipeline = this._renderPipelines[renderPipelineName];
  77171. if (!pipeline.isSupported) {
  77172. pipeline.dispose();
  77173. delete this._renderPipelines[renderPipelineName];
  77174. }
  77175. else {
  77176. pipeline._update();
  77177. }
  77178. }
  77179. }
  77180. };
  77181. /** @hidden */
  77182. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  77183. for (var renderPipelineName in this._renderPipelines) {
  77184. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77185. var pipeline = this._renderPipelines[renderPipelineName];
  77186. pipeline._rebuild();
  77187. }
  77188. }
  77189. };
  77190. PostProcessRenderPipelineManager.prototype.dispose = function () {
  77191. for (var renderPipelineName in this._renderPipelines) {
  77192. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77193. var pipeline = this._renderPipelines[renderPipelineName];
  77194. pipeline.dispose();
  77195. }
  77196. }
  77197. };
  77198. return PostProcessRenderPipelineManager;
  77199. }());
  77200. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  77201. })(BABYLON || (BABYLON = {}));
  77202. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  77203. var BABYLON;
  77204. (function (BABYLON) {
  77205. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  77206. get: function () {
  77207. if (!this._postProcessRenderPipelineManager) {
  77208. // Register the G Buffer component to the scene.
  77209. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  77210. if (!component) {
  77211. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  77212. this._addComponent(component);
  77213. }
  77214. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  77215. }
  77216. return this._postProcessRenderPipelineManager;
  77217. },
  77218. enumerable: true,
  77219. configurable: true
  77220. });
  77221. /**
  77222. * Defines the Render Pipeline scene component responsible to rendering pipelines
  77223. */
  77224. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  77225. /**
  77226. * Creates a new instance of the component for the given scene
  77227. * @param scene Defines the scene to register the component in
  77228. */
  77229. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  77230. /**
  77231. * The component name helpfull to identify the component in the list of scene components.
  77232. */
  77233. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  77234. this.scene = scene;
  77235. }
  77236. /**
  77237. * Registers the component in a given scene
  77238. */
  77239. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  77240. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  77241. };
  77242. /**
  77243. * Rebuilds the elements related to this component in case of
  77244. * context lost for instance.
  77245. */
  77246. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  77247. if (this.scene._postProcessRenderPipelineManager) {
  77248. this.scene._postProcessRenderPipelineManager._rebuild();
  77249. }
  77250. };
  77251. /**
  77252. * Disposes the component and the associated ressources
  77253. */
  77254. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  77255. if (this.scene._postProcessRenderPipelineManager) {
  77256. this.scene._postProcessRenderPipelineManager.dispose();
  77257. }
  77258. };
  77259. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77260. if (this.scene._postProcessRenderPipelineManager) {
  77261. this.scene._postProcessRenderPipelineManager.update();
  77262. }
  77263. };
  77264. return PostProcessRenderPipelineManagerSceneComponent;
  77265. }());
  77266. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  77267. })(BABYLON || (BABYLON = {}));
  77268. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  77269. var BABYLON;
  77270. (function (BABYLON) {
  77271. /**
  77272. * This represents a set of one or more post processes in Babylon.
  77273. * A post process can be used to apply a shader to a texture after it is rendered.
  77274. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  77275. */
  77276. var PostProcessRenderEffect = /** @class */ (function () {
  77277. /**
  77278. * Instantiates a post process render effect.
  77279. * A post process can be used to apply a shader to a texture after it is rendered.
  77280. * @param engine The engine the effect is tied to
  77281. * @param name The name of the effect
  77282. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  77283. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  77284. */
  77285. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  77286. this._name = name;
  77287. this._singleInstance = singleInstance || true;
  77288. this._getPostProcesses = getPostProcesses;
  77289. this._cameras = {};
  77290. this._indicesForCamera = {};
  77291. this._postProcesses = {};
  77292. }
  77293. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  77294. /**
  77295. * Checks if all the post processes in the effect are supported.
  77296. */
  77297. get: function () {
  77298. for (var index in this._postProcesses) {
  77299. if (this._postProcesses.hasOwnProperty(index)) {
  77300. var pps = this._postProcesses[index];
  77301. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  77302. if (!pps[ppIndex].isSupported) {
  77303. return false;
  77304. }
  77305. }
  77306. }
  77307. }
  77308. return true;
  77309. },
  77310. enumerable: true,
  77311. configurable: true
  77312. });
  77313. /**
  77314. * Updates the current state of the effect
  77315. * @hidden
  77316. */
  77317. PostProcessRenderEffect.prototype._update = function () {
  77318. };
  77319. /**
  77320. * Attaches the effect on cameras
  77321. * @param cameras The camera to attach to.
  77322. * @hidden
  77323. */
  77324. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  77325. var _this = this;
  77326. var cameraKey;
  77327. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77328. if (!cams) {
  77329. return;
  77330. }
  77331. for (var i = 0; i < cams.length; i++) {
  77332. var camera = cams[i];
  77333. var cameraName = camera.name;
  77334. if (this._singleInstance) {
  77335. cameraKey = 0;
  77336. }
  77337. else {
  77338. cameraKey = cameraName;
  77339. }
  77340. if (!this._postProcesses[cameraKey]) {
  77341. var postProcess = this._getPostProcesses();
  77342. if (postProcess) {
  77343. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  77344. }
  77345. }
  77346. if (!this._indicesForCamera[cameraName]) {
  77347. this._indicesForCamera[cameraName] = [];
  77348. }
  77349. this._postProcesses[cameraKey].forEach(function (postProcess) {
  77350. var index = camera.attachPostProcess(postProcess);
  77351. _this._indicesForCamera[cameraName].push(index);
  77352. });
  77353. if (!this._cameras[cameraName]) {
  77354. this._cameras[cameraName] = camera;
  77355. }
  77356. }
  77357. };
  77358. /**
  77359. * Detatches the effect on cameras
  77360. * @param cameras The camera to detatch from.
  77361. * @hidden
  77362. */
  77363. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  77364. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77365. if (!cams) {
  77366. return;
  77367. }
  77368. for (var i = 0; i < cams.length; i++) {
  77369. var camera = cams[i];
  77370. var cameraName = camera.name;
  77371. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77372. camera.detachPostProcess(postProcess);
  77373. });
  77374. if (this._cameras[cameraName]) {
  77375. //this._indicesForCamera.splice(index, 1);
  77376. this._cameras[cameraName] = null;
  77377. }
  77378. }
  77379. };
  77380. /**
  77381. * Enables the effect on given cameras
  77382. * @param cameras The camera to enable.
  77383. * @hidden
  77384. */
  77385. PostProcessRenderEffect.prototype._enable = function (cameras) {
  77386. var _this = this;
  77387. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77388. if (!cams) {
  77389. return;
  77390. }
  77391. for (var i = 0; i < cams.length; i++) {
  77392. var camera = cams[i];
  77393. var cameraName = camera.name;
  77394. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  77395. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  77396. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77397. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  77398. });
  77399. }
  77400. }
  77401. }
  77402. };
  77403. /**
  77404. * Disables the effect on the given cameras
  77405. * @param cameras The camera to disable.
  77406. * @hidden
  77407. */
  77408. PostProcessRenderEffect.prototype._disable = function (cameras) {
  77409. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77410. if (!cams) {
  77411. return;
  77412. }
  77413. for (var i = 0; i < cams.length; i++) {
  77414. var camera = cams[i];
  77415. var cameraName = camera.name;
  77416. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77417. camera.detachPostProcess(postProcess);
  77418. });
  77419. }
  77420. };
  77421. /**
  77422. * Gets a list of the post processes contained in the effect.
  77423. * @param camera The camera to get the post processes on.
  77424. * @returns The list of the post processes in the effect.
  77425. */
  77426. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  77427. if (this._singleInstance) {
  77428. return this._postProcesses[0];
  77429. }
  77430. else {
  77431. if (!camera) {
  77432. return null;
  77433. }
  77434. return this._postProcesses[camera.name];
  77435. }
  77436. };
  77437. return PostProcessRenderEffect;
  77438. }());
  77439. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  77440. })(BABYLON || (BABYLON = {}));
  77441. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  77442. var BABYLON;
  77443. (function (BABYLON) {
  77444. var PostProcessRenderPipeline = /** @class */ (function () {
  77445. function PostProcessRenderPipeline(engine, name) {
  77446. this.engine = engine;
  77447. this._name = name;
  77448. this._renderEffects = {};
  77449. this._renderEffectsForIsolatedPass = new Array();
  77450. this._cameras = [];
  77451. }
  77452. PostProcessRenderPipeline.prototype.getClassName = function () {
  77453. return "PostProcessRenderPipeline";
  77454. };
  77455. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  77456. get: function () {
  77457. for (var renderEffectName in this._renderEffects) {
  77458. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77459. if (!this._renderEffects[renderEffectName].isSupported) {
  77460. return false;
  77461. }
  77462. }
  77463. }
  77464. return true;
  77465. },
  77466. enumerable: true,
  77467. configurable: true
  77468. });
  77469. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  77470. this._renderEffects[renderEffect._name] = renderEffect;
  77471. };
  77472. // private
  77473. /** @hidden */
  77474. PostProcessRenderPipeline.prototype._rebuild = function () {
  77475. };
  77476. /** @hidden */
  77477. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  77478. var renderEffects = this._renderEffects[renderEffectName];
  77479. if (!renderEffects) {
  77480. return;
  77481. }
  77482. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77483. };
  77484. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  77485. var renderEffects = this._renderEffects[renderEffectName];
  77486. if (!renderEffects) {
  77487. return;
  77488. }
  77489. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77490. };
  77491. /** @hidden */
  77492. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  77493. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77494. if (!cams) {
  77495. return;
  77496. }
  77497. var indicesToDelete = [];
  77498. var i;
  77499. for (i = 0; i < cams.length; i++) {
  77500. var camera = cams[i];
  77501. var cameraName = camera.name;
  77502. if (this._cameras.indexOf(camera) === -1) {
  77503. this._cameras[cameraName] = camera;
  77504. }
  77505. else if (unique) {
  77506. indicesToDelete.push(i);
  77507. }
  77508. }
  77509. for (i = 0; i < indicesToDelete.length; i++) {
  77510. cameras.splice(indicesToDelete[i], 1);
  77511. }
  77512. for (var renderEffectName in this._renderEffects) {
  77513. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77514. this._renderEffects[renderEffectName]._attachCameras(cams);
  77515. }
  77516. }
  77517. };
  77518. /** @hidden */
  77519. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  77520. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77521. if (!cams) {
  77522. return;
  77523. }
  77524. for (var renderEffectName in this._renderEffects) {
  77525. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77526. this._renderEffects[renderEffectName]._detachCameras(cams);
  77527. }
  77528. }
  77529. for (var i = 0; i < cams.length; i++) {
  77530. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  77531. }
  77532. };
  77533. /** @hidden */
  77534. PostProcessRenderPipeline.prototype._update = function () {
  77535. for (var renderEffectName in this._renderEffects) {
  77536. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77537. this._renderEffects[renderEffectName]._update();
  77538. }
  77539. }
  77540. for (var i = 0; i < this._cameras.length; i++) {
  77541. var cameraName = this._cameras[i].name;
  77542. if (this._renderEffectsForIsolatedPass[cameraName]) {
  77543. this._renderEffectsForIsolatedPass[cameraName]._update();
  77544. }
  77545. }
  77546. };
  77547. /** @hidden */
  77548. PostProcessRenderPipeline.prototype._reset = function () {
  77549. this._renderEffects = {};
  77550. this._renderEffectsForIsolatedPass = new Array();
  77551. };
  77552. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  77553. // 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)
  77554. var effectKeys = Object.keys(this._renderEffects);
  77555. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  77556. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  77557. if (postProcesses) {
  77558. postProcesses[0].samples = sampleCount;
  77559. return true;
  77560. }
  77561. }
  77562. return false;
  77563. };
  77564. PostProcessRenderPipeline.prototype.dispose = function () {
  77565. // Must be implemented by children
  77566. };
  77567. __decorate([
  77568. BABYLON.serialize()
  77569. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  77570. return PostProcessRenderPipeline;
  77571. }());
  77572. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  77573. })(BABYLON || (BABYLON = {}));
  77574. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  77575. var BABYLON;
  77576. (function (BABYLON) {
  77577. /**
  77578. * This represents a depth renderer in Babylon.
  77579. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  77580. */
  77581. var DepthRenderer = /** @class */ (function () {
  77582. /**
  77583. * Instantiates a depth renderer
  77584. * @param scene The scene the renderer belongs to
  77585. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  77586. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  77587. */
  77588. function DepthRenderer(scene, type, camera) {
  77589. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  77590. if (camera === void 0) { camera = null; }
  77591. var _this = this;
  77592. /**
  77593. * Specifiess that the depth renderer will only be used within
  77594. * the camera it is created for.
  77595. * This can help forcing its rendering during the camera processing.
  77596. */
  77597. this.useOnlyInActiveCamera = false;
  77598. this._scene = scene;
  77599. // Register the G Buffer component to the scene.
  77600. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  77601. if (!component) {
  77602. component = new BABYLON.DepthRendererSceneComponent(scene);
  77603. scene._addComponent(component);
  77604. }
  77605. this._camera = camera;
  77606. var engine = scene.getEngine();
  77607. // Render target
  77608. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  77609. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77610. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77611. this._depthMap.refreshRate = 1;
  77612. this._depthMap.renderParticles = false;
  77613. this._depthMap.renderList = null;
  77614. // Camera to get depth map from to support multiple concurrent cameras
  77615. this._depthMap.activeCamera = this._camera;
  77616. this._depthMap.ignoreCameraViewport = true;
  77617. this._depthMap.useCameraPostProcesses = false;
  77618. // set default depth value to 1.0 (far away)
  77619. this._depthMap.onClearObservable.add(function (engine) {
  77620. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  77621. });
  77622. // Custom render function
  77623. var renderSubMesh = function (subMesh) {
  77624. var mesh = subMesh.getRenderingMesh();
  77625. var scene = _this._scene;
  77626. var engine = scene.getEngine();
  77627. var material = subMesh.getMaterial();
  77628. if (!material) {
  77629. return;
  77630. }
  77631. // Culling and reverse (right handed system)
  77632. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77633. // Managing instances
  77634. var batch = mesh._getInstancesRenderList(subMesh._id);
  77635. if (batch.mustReturn) {
  77636. return;
  77637. }
  77638. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77639. var camera = _this._camera || scene.activeCamera;
  77640. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  77641. engine.enableEffect(_this._effect);
  77642. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77643. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77644. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  77645. // Alpha test
  77646. if (material && material.needAlphaTesting()) {
  77647. var alphaTexture = material.getAlphaTestTexture();
  77648. if (alphaTexture) {
  77649. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77650. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77651. }
  77652. }
  77653. // Bones
  77654. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77655. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77656. }
  77657. // Draw
  77658. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77659. }
  77660. };
  77661. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77662. var index;
  77663. if (depthOnlySubMeshes.length) {
  77664. engine.setColorWrite(false);
  77665. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77666. renderSubMesh(depthOnlySubMeshes.data[index]);
  77667. }
  77668. engine.setColorWrite(true);
  77669. }
  77670. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77671. renderSubMesh(opaqueSubMeshes.data[index]);
  77672. }
  77673. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77674. renderSubMesh(alphaTestSubMeshes.data[index]);
  77675. }
  77676. };
  77677. }
  77678. /**
  77679. * Creates the depth rendering effect and checks if the effect is ready.
  77680. * @param subMesh The submesh to be used to render the depth map of
  77681. * @param useInstances If multiple world instances should be used
  77682. * @returns if the depth renderer is ready to render the depth map
  77683. */
  77684. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  77685. var material = subMesh.getMaterial();
  77686. if (material.disableDepthWrite) {
  77687. return false;
  77688. }
  77689. var defines = [];
  77690. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77691. var mesh = subMesh.getMesh();
  77692. // Alpha test
  77693. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  77694. defines.push("#define ALPHATEST");
  77695. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77696. attribs.push(BABYLON.VertexBuffer.UVKind);
  77697. defines.push("#define UV1");
  77698. }
  77699. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77700. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77701. defines.push("#define UV2");
  77702. }
  77703. }
  77704. // Bones
  77705. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77706. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77707. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77708. if (mesh.numBoneInfluencers > 4) {
  77709. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77710. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77711. }
  77712. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77713. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77714. }
  77715. else {
  77716. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77717. }
  77718. // Instances
  77719. if (useInstances) {
  77720. defines.push("#define INSTANCES");
  77721. attribs.push("world0");
  77722. attribs.push("world1");
  77723. attribs.push("world2");
  77724. attribs.push("world3");
  77725. }
  77726. // Get correct effect
  77727. var join = defines.join("\n");
  77728. if (this._cachedDefines !== join) {
  77729. this._cachedDefines = join;
  77730. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  77731. }
  77732. return this._effect.isReady();
  77733. };
  77734. /**
  77735. * Gets the texture which the depth map will be written to.
  77736. * @returns The depth map texture
  77737. */
  77738. DepthRenderer.prototype.getDepthMap = function () {
  77739. return this._depthMap;
  77740. };
  77741. /**
  77742. * Disposes of the depth renderer.
  77743. */
  77744. DepthRenderer.prototype.dispose = function () {
  77745. this._depthMap.dispose();
  77746. };
  77747. return DepthRenderer;
  77748. }());
  77749. BABYLON.DepthRenderer = DepthRenderer;
  77750. })(BABYLON || (BABYLON = {}));
  77751. //# sourceMappingURL=babylon.depthRenderer.js.map
  77752. var BABYLON;
  77753. (function (BABYLON) {
  77754. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  77755. camera = camera || this.activeCamera;
  77756. if (!camera) {
  77757. throw "No camera available to enable depth renderer";
  77758. }
  77759. if (!this._depthRenderer) {
  77760. this._depthRenderer = {};
  77761. }
  77762. if (!this._depthRenderer[camera.id]) {
  77763. var textureType = 0;
  77764. if (this.getEngine().getCaps().textureHalfFloatRender) {
  77765. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77766. }
  77767. else if (this.getEngine().getCaps().textureFloatRender) {
  77768. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77769. }
  77770. else {
  77771. throw "Depth renderer does not support int texture type";
  77772. }
  77773. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  77774. }
  77775. return this._depthRenderer[camera.id];
  77776. };
  77777. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  77778. camera = camera || this.activeCamera;
  77779. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  77780. return;
  77781. }
  77782. this._depthRenderer[camera.id].dispose();
  77783. delete this._depthRenderer[camera.id];
  77784. };
  77785. /**
  77786. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  77787. * in several rendering techniques.
  77788. */
  77789. var DepthRendererSceneComponent = /** @class */ (function () {
  77790. /**
  77791. * Creates a new instance of the component for the given scene
  77792. * @param scene Defines the scene to register the component in
  77793. */
  77794. function DepthRendererSceneComponent(scene) {
  77795. /**
  77796. * The component name helpfull to identify the component in the list of scene components.
  77797. */
  77798. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  77799. this.scene = scene;
  77800. }
  77801. /**
  77802. * Registers the component in a given scene
  77803. */
  77804. DepthRendererSceneComponent.prototype.register = function () {
  77805. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  77806. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  77807. };
  77808. /**
  77809. * Rebuilds the elements related to this component in case of
  77810. * context lost for instance.
  77811. */
  77812. DepthRendererSceneComponent.prototype.rebuild = function () {
  77813. // Nothing to do for this component
  77814. };
  77815. /**
  77816. * Disposes the component and the associated ressources
  77817. */
  77818. DepthRendererSceneComponent.prototype.dispose = function () {
  77819. for (var key in this.scene._depthRenderer) {
  77820. this.scene._depthRenderer[key].dispose();
  77821. }
  77822. };
  77823. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77824. if (this.scene._depthRenderer) {
  77825. for (var key in this.scene._depthRenderer) {
  77826. var depthRenderer = this.scene._depthRenderer[key];
  77827. if (!depthRenderer.useOnlyInActiveCamera) {
  77828. renderTargets.push(depthRenderer.getDepthMap());
  77829. }
  77830. }
  77831. }
  77832. };
  77833. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  77834. if (this.scene._depthRenderer) {
  77835. for (var key in this.scene._depthRenderer) {
  77836. var depthRenderer = this.scene._depthRenderer[key];
  77837. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  77838. renderTargets.push(depthRenderer.getDepthMap());
  77839. }
  77840. }
  77841. }
  77842. };
  77843. return DepthRendererSceneComponent;
  77844. }());
  77845. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  77846. })(BABYLON || (BABYLON = {}));
  77847. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  77848. var BABYLON;
  77849. (function (BABYLON) {
  77850. /**
  77851. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  77852. */
  77853. var GeometryBufferRenderer = /** @class */ (function () {
  77854. /**
  77855. * Creates a new G Buffer for the scene
  77856. * @param scene The scene the buffer belongs to
  77857. * @param ratio How big is the buffer related to the main canvas.
  77858. */
  77859. function GeometryBufferRenderer(scene, ratio) {
  77860. if (ratio === void 0) { ratio = 1; }
  77861. this._enablePosition = false;
  77862. this._scene = scene;
  77863. this._ratio = ratio;
  77864. // Register the G Buffer component to the scene.
  77865. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  77866. if (!component) {
  77867. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  77868. scene._addComponent(component);
  77869. }
  77870. // Render target
  77871. this._createRenderTargets();
  77872. }
  77873. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  77874. /**
  77875. * Set the render list (meshes to be rendered) used in the G buffer.
  77876. */
  77877. set: function (meshes) {
  77878. this._multiRenderTarget.renderList = meshes;
  77879. },
  77880. enumerable: true,
  77881. configurable: true
  77882. });
  77883. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  77884. /**
  77885. * Gets wether or not G buffer are supported by the running hardware.
  77886. * This requires draw buffer supports
  77887. */
  77888. get: function () {
  77889. return this._multiRenderTarget.isSupported;
  77890. },
  77891. enumerable: true,
  77892. configurable: true
  77893. });
  77894. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  77895. /**
  77896. * Gets wether or not position are enabled for the G buffer.
  77897. */
  77898. get: function () {
  77899. return this._enablePosition;
  77900. },
  77901. /**
  77902. * Sets wether or not position are enabled for the G buffer.
  77903. */
  77904. set: function (enable) {
  77905. this._enablePosition = enable;
  77906. this.dispose();
  77907. this._createRenderTargets();
  77908. },
  77909. enumerable: true,
  77910. configurable: true
  77911. });
  77912. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  77913. /**
  77914. * Gets the scene associated with the buffer.
  77915. */
  77916. get: function () {
  77917. return this._scene;
  77918. },
  77919. enumerable: true,
  77920. configurable: true
  77921. });
  77922. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  77923. /**
  77924. * Gets the ratio used by the buffer during its creation.
  77925. * How big is the buffer related to the main canvas.
  77926. */
  77927. get: function () {
  77928. return this._ratio;
  77929. },
  77930. enumerable: true,
  77931. configurable: true
  77932. });
  77933. /**
  77934. * Checks wether everything is ready to render a submesh to the G buffer.
  77935. * @param subMesh the submesh to check readiness for
  77936. * @param useInstances is the mesh drawn using instance or not
  77937. * @returns true if ready otherwise false
  77938. */
  77939. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  77940. var material = subMesh.getMaterial();
  77941. if (material && material.disableDepthWrite) {
  77942. return false;
  77943. }
  77944. var defines = [];
  77945. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77946. var mesh = subMesh.getMesh();
  77947. // Alpha test
  77948. if (material && material.needAlphaTesting()) {
  77949. defines.push("#define ALPHATEST");
  77950. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77951. attribs.push(BABYLON.VertexBuffer.UVKind);
  77952. defines.push("#define UV1");
  77953. }
  77954. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77955. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77956. defines.push("#define UV2");
  77957. }
  77958. }
  77959. // Buffers
  77960. if (this._enablePosition) {
  77961. defines.push("#define POSITION");
  77962. }
  77963. // Bones
  77964. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77965. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77966. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77967. if (mesh.numBoneInfluencers > 4) {
  77968. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77969. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77970. }
  77971. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77972. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77973. }
  77974. else {
  77975. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77976. }
  77977. // Instances
  77978. if (useInstances) {
  77979. defines.push("#define INSTANCES");
  77980. attribs.push("world0");
  77981. attribs.push("world1");
  77982. attribs.push("world2");
  77983. attribs.push("world3");
  77984. }
  77985. // Get correct effect
  77986. var join = defines.join("\n");
  77987. if (this._cachedDefines !== join) {
  77988. this._cachedDefines = join;
  77989. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77990. }
  77991. return this._effect.isReady();
  77992. };
  77993. /**
  77994. * Gets the current underlying G Buffer.
  77995. * @returns the buffer
  77996. */
  77997. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77998. return this._multiRenderTarget;
  77999. };
  78000. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  78001. /**
  78002. * Gets the number of samples used to render the buffer (anti aliasing).
  78003. */
  78004. get: function () {
  78005. return this._multiRenderTarget.samples;
  78006. },
  78007. /**
  78008. * Sets the number of samples used to render the buffer (anti aliasing).
  78009. */
  78010. set: function (value) {
  78011. this._multiRenderTarget.samples = value;
  78012. },
  78013. enumerable: true,
  78014. configurable: true
  78015. });
  78016. /**
  78017. * Disposes the renderer and frees up associated resources.
  78018. */
  78019. GeometryBufferRenderer.prototype.dispose = function () {
  78020. this.getGBuffer().dispose();
  78021. };
  78022. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  78023. var _this = this;
  78024. var engine = this._scene.getEngine();
  78025. var count = this._enablePosition ? 3 : 2;
  78026. 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 });
  78027. if (!this.isSupported) {
  78028. return;
  78029. }
  78030. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78031. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78032. this._multiRenderTarget.refreshRate = 1;
  78033. this._multiRenderTarget.renderParticles = false;
  78034. this._multiRenderTarget.renderList = null;
  78035. // set default depth value to 1.0 (far away)
  78036. this._multiRenderTarget.onClearObservable.add(function (engine) {
  78037. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  78038. });
  78039. // Custom render function
  78040. var renderSubMesh = function (subMesh) {
  78041. var mesh = subMesh.getRenderingMesh();
  78042. var scene = _this._scene;
  78043. var engine = scene.getEngine();
  78044. var material = subMesh.getMaterial();
  78045. if (!material) {
  78046. return;
  78047. }
  78048. // Culling
  78049. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78050. // Managing instances
  78051. var batch = mesh._getInstancesRenderList(subMesh._id);
  78052. if (batch.mustReturn) {
  78053. return;
  78054. }
  78055. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78056. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  78057. engine.enableEffect(_this._effect);
  78058. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78059. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78060. _this._effect.setMatrix("view", scene.getViewMatrix());
  78061. // Alpha test
  78062. if (material && material.needAlphaTesting()) {
  78063. var alphaTexture = material.getAlphaTestTexture();
  78064. if (alphaTexture) {
  78065. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78066. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78067. }
  78068. }
  78069. // Bones
  78070. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78071. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78072. }
  78073. // Draw
  78074. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78075. }
  78076. };
  78077. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78078. var index;
  78079. if (depthOnlySubMeshes.length) {
  78080. engine.setColorWrite(false);
  78081. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78082. renderSubMesh(depthOnlySubMeshes.data[index]);
  78083. }
  78084. engine.setColorWrite(true);
  78085. }
  78086. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78087. renderSubMesh(opaqueSubMeshes.data[index]);
  78088. }
  78089. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78090. renderSubMesh(alphaTestSubMeshes.data[index]);
  78091. }
  78092. };
  78093. };
  78094. return GeometryBufferRenderer;
  78095. }());
  78096. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  78097. })(BABYLON || (BABYLON = {}));
  78098. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  78099. var BABYLON;
  78100. (function (BABYLON) {
  78101. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  78102. get: function () {
  78103. this._geometryBufferRenderer;
  78104. },
  78105. set: function (value) {
  78106. if (value && value.isSupported) {
  78107. this._geometryBufferRenderer = value;
  78108. }
  78109. ;
  78110. },
  78111. enumerable: true,
  78112. configurable: true
  78113. });
  78114. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  78115. if (ratio === void 0) { ratio = 1; }
  78116. if (this._geometryBufferRenderer) {
  78117. return this._geometryBufferRenderer;
  78118. }
  78119. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  78120. if (!this._geometryBufferRenderer.isSupported) {
  78121. this._geometryBufferRenderer = null;
  78122. }
  78123. return this._geometryBufferRenderer;
  78124. };
  78125. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  78126. if (!this._geometryBufferRenderer) {
  78127. return;
  78128. }
  78129. this._geometryBufferRenderer.dispose();
  78130. this._geometryBufferRenderer = null;
  78131. };
  78132. /**
  78133. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer usefull
  78134. * in several rendering techniques.
  78135. */
  78136. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  78137. /**
  78138. * Creates a new instance of the component for the given scene
  78139. * @param scene Defines the scene to register the component in
  78140. */
  78141. function GeometryBufferRendererSceneComponent(scene) {
  78142. /**
  78143. * The component name helpfull to identify the component in the list of scene components.
  78144. */
  78145. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  78146. this.scene = scene;
  78147. }
  78148. /**
  78149. * Registers the component in a given scene
  78150. */
  78151. GeometryBufferRendererSceneComponent.prototype.register = function () {
  78152. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  78153. };
  78154. /**
  78155. * Rebuilds the elements related to this component in case of
  78156. * context lost for instance.
  78157. */
  78158. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  78159. // Nothing to do for this component
  78160. };
  78161. /**
  78162. * Disposes the component and the associated ressources
  78163. */
  78164. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  78165. // Nothing to do for this component
  78166. };
  78167. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  78168. if (this.scene._geometryBufferRenderer) {
  78169. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  78170. }
  78171. };
  78172. return GeometryBufferRendererSceneComponent;
  78173. }());
  78174. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  78175. })(BABYLON || (BABYLON = {}));
  78176. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  78177. var BABYLON;
  78178. (function (BABYLON) {
  78179. var SSAORenderingPipeline = /** @class */ (function (_super) {
  78180. __extends(SSAORenderingPipeline, _super);
  78181. /**
  78182. * @constructor
  78183. * @param {string} name - The rendering pipeline name
  78184. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78185. * @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 }
  78186. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78187. */
  78188. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  78189. var _this = _super.call(this, scene.getEngine(), name) || this;
  78190. // Members
  78191. /**
  78192. * The PassPostProcess id in the pipeline that contains the original scene color
  78193. */
  78194. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78195. /**
  78196. * The SSAO PostProcess id in the pipeline
  78197. */
  78198. _this.SSAORenderEffect = "SSAORenderEffect";
  78199. /**
  78200. * The horizontal blur PostProcess id in the pipeline
  78201. */
  78202. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78203. /**
  78204. * The vertical blur PostProcess id in the pipeline
  78205. */
  78206. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  78207. /**
  78208. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  78209. */
  78210. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  78211. /**
  78212. * The output strength of the SSAO post-process. Default value is 1.0.
  78213. */
  78214. _this.totalStrength = 1.0;
  78215. /**
  78216. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  78217. */
  78218. _this.radius = 0.0001;
  78219. /**
  78220. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  78221. * Must not be equal to fallOff and superior to fallOff.
  78222. * Default value is 0.975
  78223. */
  78224. _this.area = 0.0075;
  78225. /**
  78226. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  78227. * Must not be equal to area and inferior to area.
  78228. * Default value is 0.0
  78229. */
  78230. _this.fallOff = 0.000001;
  78231. /**
  78232. * The base color of the SSAO post-process
  78233. * The final result is "base + ssao" between [0, 1]
  78234. */
  78235. _this.base = 0.5;
  78236. _this._firstUpdate = true;
  78237. _this._scene = scene;
  78238. // Set up assets
  78239. _this._createRandomTexture();
  78240. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  78241. var ssaoRatio = ratio.ssaoRatio || ratio;
  78242. var combineRatio = ratio.combineRatio || ratio;
  78243. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  78244. _this._createSSAOPostProcess(ssaoRatio);
  78245. _this._createBlurPostProcess(ssaoRatio);
  78246. _this._createSSAOCombinePostProcess(combineRatio);
  78247. // Set up pipeline
  78248. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  78249. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  78250. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  78251. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  78252. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  78253. // Finish
  78254. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78255. if (cameras)
  78256. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78257. return _this;
  78258. }
  78259. // Public Methods
  78260. /**
  78261. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78262. */
  78263. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  78264. if (disableDepthRender === void 0) { disableDepthRender = false; }
  78265. for (var i = 0; i < this._scene.cameras.length; i++) {
  78266. var camera = this._scene.cameras[i];
  78267. this._originalColorPostProcess.dispose(camera);
  78268. this._ssaoPostProcess.dispose(camera);
  78269. this._blurHPostProcess.dispose(camera);
  78270. this._blurVPostProcess.dispose(camera);
  78271. this._ssaoCombinePostProcess.dispose(camera);
  78272. }
  78273. this._randomTexture.dispose();
  78274. if (disableDepthRender)
  78275. this._scene.disableDepthRenderer();
  78276. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78277. _super.prototype.dispose.call(this);
  78278. };
  78279. // Private Methods
  78280. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  78281. var _this = this;
  78282. var size = 16;
  78283. 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);
  78284. 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);
  78285. this._blurHPostProcess.onActivateObservable.add(function () {
  78286. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  78287. _this._blurHPostProcess.kernel = size * dw;
  78288. });
  78289. this._blurVPostProcess.onActivateObservable.add(function () {
  78290. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  78291. _this._blurVPostProcess.kernel = size * dw;
  78292. });
  78293. };
  78294. /** @hidden */
  78295. SSAORenderingPipeline.prototype._rebuild = function () {
  78296. this._firstUpdate = true;
  78297. _super.prototype._rebuild.call(this);
  78298. };
  78299. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78300. var _this = this;
  78301. var numSamples = 16;
  78302. var sampleSphere = [
  78303. 0.5381, 0.1856, -0.4319,
  78304. 0.1379, 0.2486, 0.4430,
  78305. 0.3371, 0.5679, -0.0057,
  78306. -0.6999, -0.0451, -0.0019,
  78307. 0.0689, -0.1598, -0.8547,
  78308. 0.0560, 0.0069, -0.1843,
  78309. -0.0146, 0.1402, 0.0762,
  78310. 0.0100, -0.1924, -0.0344,
  78311. -0.3577, -0.5301, -0.4358,
  78312. -0.3169, 0.1063, 0.0158,
  78313. 0.0103, -0.5869, 0.0046,
  78314. -0.0897, -0.4940, 0.3287,
  78315. 0.7119, -0.0154, -0.0918,
  78316. -0.0533, 0.0596, -0.5411,
  78317. 0.0352, -0.0631, 0.5460,
  78318. -0.4776, 0.2847, -0.0271
  78319. ];
  78320. var samplesFactor = 1.0 / numSamples;
  78321. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  78322. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78323. "area", "fallOff", "base", "range", "viewport"
  78324. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78325. this._ssaoPostProcess.onApply = function (effect) {
  78326. if (_this._firstUpdate) {
  78327. effect.setArray3("sampleSphere", sampleSphere);
  78328. effect.setFloat("samplesFactor", samplesFactor);
  78329. effect.setFloat("randTextureTiles", 4.0);
  78330. }
  78331. effect.setFloat("totalStrength", _this.totalStrength);
  78332. effect.setFloat("radius", _this.radius);
  78333. effect.setFloat("area", _this.area);
  78334. effect.setFloat("fallOff", _this.fallOff);
  78335. effect.setFloat("base", _this.base);
  78336. effect.setTexture("textureSampler", _this._depthTexture);
  78337. effect.setTexture("randomSampler", _this._randomTexture);
  78338. };
  78339. };
  78340. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78341. var _this = this;
  78342. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78343. this._ssaoCombinePostProcess.onApply = function (effect) {
  78344. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  78345. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78346. };
  78347. };
  78348. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  78349. var size = 512;
  78350. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78351. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78352. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78353. var context = this._randomTexture.getContext();
  78354. var rand = function (min, max) {
  78355. return Math.random() * (max - min) + min;
  78356. };
  78357. var randVector = BABYLON.Vector3.Zero();
  78358. for (var x = 0; x < size; x++) {
  78359. for (var y = 0; y < size; y++) {
  78360. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  78361. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  78362. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  78363. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  78364. context.fillRect(x, y, 1, 1);
  78365. }
  78366. }
  78367. this._randomTexture.update(false);
  78368. };
  78369. __decorate([
  78370. BABYLON.serialize()
  78371. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  78372. __decorate([
  78373. BABYLON.serialize()
  78374. ], SSAORenderingPipeline.prototype, "radius", void 0);
  78375. __decorate([
  78376. BABYLON.serialize()
  78377. ], SSAORenderingPipeline.prototype, "area", void 0);
  78378. __decorate([
  78379. BABYLON.serialize()
  78380. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  78381. __decorate([
  78382. BABYLON.serialize()
  78383. ], SSAORenderingPipeline.prototype, "base", void 0);
  78384. return SSAORenderingPipeline;
  78385. }(BABYLON.PostProcessRenderPipeline));
  78386. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  78387. })(BABYLON || (BABYLON = {}));
  78388. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  78389. var BABYLON;
  78390. (function (BABYLON) {
  78391. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  78392. __extends(SSAO2RenderingPipeline, _super);
  78393. /**
  78394. * @constructor
  78395. * @param {string} name - The rendering pipeline name
  78396. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78397. * @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 }
  78398. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78399. */
  78400. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  78401. var _this = _super.call(this, scene.getEngine(), name) || this;
  78402. // Members
  78403. /**
  78404. * The PassPostProcess id in the pipeline that contains the original scene color
  78405. */
  78406. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78407. /**
  78408. * The SSAO PostProcess id in the pipeline
  78409. */
  78410. _this.SSAORenderEffect = "SSAORenderEffect";
  78411. /**
  78412. * The horizontal blur PostProcess id in the pipeline
  78413. */
  78414. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78415. /**
  78416. * The vertical blur PostProcess id in the pipeline
  78417. */
  78418. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  78419. /**
  78420. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  78421. */
  78422. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  78423. /**
  78424. * The output strength of the SSAO post-process. Default value is 1.0.
  78425. */
  78426. _this.totalStrength = 1.0;
  78427. /**
  78428. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  78429. */
  78430. _this.maxZ = 100.0;
  78431. /**
  78432. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  78433. */
  78434. _this.minZAspect = 0.2;
  78435. _this._samples = 8;
  78436. _this._textureSamples = 1;
  78437. /**
  78438. * Are we using bilateral blur ?
  78439. */
  78440. _this._expensiveBlur = true;
  78441. /**
  78442. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  78443. */
  78444. _this.radius = 2.0;
  78445. /**
  78446. * The base color of the SSAO post-process
  78447. * The final result is "base + ssao" between [0, 1]
  78448. */
  78449. _this.base = 0;
  78450. _this._firstUpdate = true;
  78451. _this._bits = new Uint32Array(1);
  78452. _this._scene = scene;
  78453. _this._ratio = ratio;
  78454. if (!_this.isSupported) {
  78455. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  78456. return _this;
  78457. }
  78458. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  78459. var blurRatio = _this._ratio.blurRatio || ratio;
  78460. // Set up assets
  78461. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  78462. _this._createRandomTexture();
  78463. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  78464. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  78465. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  78466. _this._originalColorPostProcess.samples = _this.textureSamples;
  78467. _this._createSSAOPostProcess(1.0);
  78468. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  78469. _this._createSSAOCombinePostProcess(blurRatio);
  78470. // Set up pipeline
  78471. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  78472. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  78473. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  78474. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  78475. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  78476. // Finish
  78477. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78478. if (cameras)
  78479. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78480. return _this;
  78481. }
  78482. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  78483. get: function () {
  78484. return this._samples;
  78485. },
  78486. /**
  78487. * Number of samples used for the SSAO calculations. Default value is 8
  78488. */
  78489. set: function (n) {
  78490. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  78491. this._samples = n;
  78492. this._sampleSphere = this._generateHemisphere();
  78493. this._firstUpdate = true;
  78494. },
  78495. enumerable: true,
  78496. configurable: true
  78497. });
  78498. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  78499. get: function () {
  78500. return this._textureSamples;
  78501. },
  78502. /**
  78503. * Number of samples to use for antialiasing
  78504. */
  78505. set: function (n) {
  78506. this._textureSamples = n;
  78507. this._originalColorPostProcess.samples = n;
  78508. this._blurHPostProcess.samples = n;
  78509. this._blurVPostProcess.samples = n;
  78510. this._ssaoPostProcess.samples = n;
  78511. this._ssaoCombinePostProcess.samples = n;
  78512. },
  78513. enumerable: true,
  78514. configurable: true
  78515. });
  78516. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  78517. get: function () {
  78518. return this._expensiveBlur;
  78519. },
  78520. set: function (b) {
  78521. 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"]);
  78522. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  78523. this._expensiveBlur = b;
  78524. this._firstUpdate = true;
  78525. },
  78526. enumerable: true,
  78527. configurable: true
  78528. });
  78529. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  78530. /**
  78531. * Support test.
  78532. */
  78533. get: function () {
  78534. var engine = BABYLON.Engine.LastCreatedEngine;
  78535. if (!engine) {
  78536. return false;
  78537. }
  78538. return engine.getCaps().drawBuffersExtension;
  78539. },
  78540. enumerable: true,
  78541. configurable: true
  78542. });
  78543. // Public Methods
  78544. /**
  78545. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78546. */
  78547. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  78548. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  78549. for (var i = 0; i < this._scene.cameras.length; i++) {
  78550. var camera = this._scene.cameras[i];
  78551. this._originalColorPostProcess.dispose(camera);
  78552. this._ssaoPostProcess.dispose(camera);
  78553. this._blurHPostProcess.dispose(camera);
  78554. this._blurVPostProcess.dispose(camera);
  78555. this._ssaoCombinePostProcess.dispose(camera);
  78556. }
  78557. this._randomTexture.dispose();
  78558. if (disableGeometryBufferRenderer)
  78559. this._scene.disableGeometryBufferRenderer();
  78560. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78561. _super.prototype.dispose.call(this);
  78562. };
  78563. // Private Methods
  78564. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  78565. var _this = this;
  78566. this._samplerOffsets = [];
  78567. var expensive = this.expensiveBlur;
  78568. for (var i = -8; i < 8; i++) {
  78569. this._samplerOffsets.push(i * 2 + 0.5);
  78570. }
  78571. 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");
  78572. this._blurHPostProcess.onApply = function (effect) {
  78573. if (!_this._scene.activeCamera) {
  78574. return;
  78575. }
  78576. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  78577. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78578. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78579. effect.setFloat("radius", _this.radius);
  78580. effect.setTexture("depthSampler", _this._depthTexture);
  78581. if (_this._firstUpdate) {
  78582. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78583. }
  78584. };
  78585. 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");
  78586. this._blurVPostProcess.onApply = function (effect) {
  78587. if (!_this._scene.activeCamera) {
  78588. return;
  78589. }
  78590. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  78591. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78592. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78593. effect.setFloat("radius", _this.radius);
  78594. effect.setTexture("depthSampler", _this._depthTexture);
  78595. if (_this._firstUpdate) {
  78596. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78597. _this._firstUpdate = false;
  78598. }
  78599. };
  78600. this._blurHPostProcess.samples = this.textureSamples;
  78601. this._blurVPostProcess.samples = this.textureSamples;
  78602. };
  78603. /** @hidden */
  78604. SSAO2RenderingPipeline.prototype._rebuild = function () {
  78605. this._firstUpdate = true;
  78606. _super.prototype._rebuild.call(this);
  78607. };
  78608. //Van der Corput radical inverse
  78609. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  78610. this._bits[0] = i;
  78611. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  78612. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  78613. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  78614. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  78615. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  78616. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  78617. };
  78618. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  78619. return [i / n, this._radicalInverse_VdC(i)];
  78620. };
  78621. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  78622. var phi = v * 2.0 * Math.PI;
  78623. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  78624. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  78625. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  78626. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  78627. };
  78628. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  78629. var numSamples = this.samples;
  78630. var result = [];
  78631. var vector;
  78632. var i = 0;
  78633. while (i < numSamples) {
  78634. if (numSamples < 16) {
  78635. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  78636. }
  78637. else {
  78638. var rand = this._hammersley(i, numSamples);
  78639. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  78640. }
  78641. result.push(vector.x, vector.y, vector.z);
  78642. i++;
  78643. }
  78644. return result;
  78645. };
  78646. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78647. var _this = this;
  78648. var numSamples = this.samples;
  78649. this._sampleSphere = this._generateHemisphere();
  78650. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  78651. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78652. "base", "range", "projection", "near", "far", "texelSize",
  78653. "xViewport", "yViewport", "maxZ", "minZAspect"
  78654. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78655. this._ssaoPostProcess.onApply = function (effect) {
  78656. if (_this._firstUpdate) {
  78657. effect.setArray3("sampleSphere", _this._sampleSphere);
  78658. effect.setFloat("randTextureTiles", 32.0);
  78659. }
  78660. if (!_this._scene.activeCamera) {
  78661. return;
  78662. }
  78663. effect.setFloat("samplesFactor", 1 / _this.samples);
  78664. effect.setFloat("totalStrength", _this.totalStrength);
  78665. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  78666. effect.setFloat("radius", _this.radius);
  78667. effect.setFloat("maxZ", _this.maxZ);
  78668. effect.setFloat("minZAspect", _this.minZAspect);
  78669. effect.setFloat("base", _this.base);
  78670. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78671. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78672. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  78673. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  78674. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  78675. effect.setTexture("textureSampler", _this._depthTexture);
  78676. effect.setTexture("normalSampler", _this._normalTexture);
  78677. effect.setTexture("randomSampler", _this._randomTexture);
  78678. };
  78679. this._ssaoPostProcess.samples = this.textureSamples;
  78680. };
  78681. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78682. var _this = this;
  78683. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78684. this._ssaoCombinePostProcess.onApply = function (effect) {
  78685. var viewport = _this._scene.activeCamera.viewport;
  78686. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  78687. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78688. };
  78689. this._ssaoCombinePostProcess.samples = this.textureSamples;
  78690. };
  78691. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  78692. var size = 128;
  78693. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78694. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78695. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78696. var context = this._randomTexture.getContext();
  78697. var rand = function (min, max) {
  78698. return Math.random() * (max - min) + min;
  78699. };
  78700. var randVector = BABYLON.Vector3.Zero();
  78701. for (var x = 0; x < size; x++) {
  78702. for (var y = 0; y < size; y++) {
  78703. randVector.x = rand(0.0, 1.0);
  78704. randVector.y = rand(0.0, 1.0);
  78705. randVector.z = 0.0;
  78706. randVector.normalize();
  78707. randVector.scaleInPlace(255);
  78708. randVector.x = Math.floor(randVector.x);
  78709. randVector.y = Math.floor(randVector.y);
  78710. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  78711. context.fillRect(x, y, 1, 1);
  78712. }
  78713. }
  78714. this._randomTexture.update(false);
  78715. };
  78716. /**
  78717. * Serialize the rendering pipeline (Used when exporting)
  78718. * @returns the serialized object
  78719. */
  78720. SSAO2RenderingPipeline.prototype.serialize = function () {
  78721. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78722. serializationObject.customType = "SSAO2RenderingPipeline";
  78723. return serializationObject;
  78724. };
  78725. /**
  78726. * Parse the serialized pipeline
  78727. * @param source Source pipeline.
  78728. * @param scene The scene to load the pipeline to.
  78729. * @param rootUrl The URL of the serialized pipeline.
  78730. * @returns An instantiated pipeline from the serialized object.
  78731. */
  78732. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  78733. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  78734. };
  78735. __decorate([
  78736. BABYLON.serialize()
  78737. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  78738. __decorate([
  78739. BABYLON.serialize()
  78740. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  78741. __decorate([
  78742. BABYLON.serialize()
  78743. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  78744. __decorate([
  78745. BABYLON.serialize("samples")
  78746. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  78747. __decorate([
  78748. BABYLON.serialize("textureSamples")
  78749. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  78750. __decorate([
  78751. BABYLON.serialize()
  78752. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  78753. __decorate([
  78754. BABYLON.serialize("expensiveBlur")
  78755. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  78756. __decorate([
  78757. BABYLON.serialize()
  78758. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  78759. __decorate([
  78760. BABYLON.serialize()
  78761. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  78762. return SSAO2RenderingPipeline;
  78763. }(BABYLON.PostProcessRenderPipeline));
  78764. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  78765. })(BABYLON || (BABYLON = {}));
  78766. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  78767. // BABYLON.JS Chromatic Aberration GLSL Shader
  78768. // Author: Olivier Guyot
  78769. // Separates very slightly R, G and B colors on the edges of the screen
  78770. // Inspired by Francois Tarlier & Martins Upitis
  78771. var BABYLON;
  78772. (function (BABYLON) {
  78773. var LensRenderingPipeline = /** @class */ (function (_super) {
  78774. __extends(LensRenderingPipeline, _super);
  78775. /**
  78776. * @constructor
  78777. *
  78778. * Effect parameters are as follow:
  78779. * {
  78780. * chromatic_aberration: number; // from 0 to x (1 for realism)
  78781. * edge_blur: number; // from 0 to x (1 for realism)
  78782. * distortion: number; // from 0 to x (1 for realism)
  78783. * grain_amount: number; // from 0 to 1
  78784. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  78785. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  78786. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  78787. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  78788. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  78789. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  78790. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  78791. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  78792. * }
  78793. * Note: if an effect parameter is unset, effect is disabled
  78794. *
  78795. * @param {string} name - The rendering pipeline name
  78796. * @param {object} parameters - An object containing all parameters (see above)
  78797. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78798. * @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)
  78799. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78800. */
  78801. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  78802. if (ratio === void 0) { ratio = 1.0; }
  78803. var _this = _super.call(this, scene.getEngine(), name) || this;
  78804. // Lens effects can be of the following:
  78805. // - chromatic aberration (slight shift of RGB colors)
  78806. // - blur on the edge of the lens
  78807. // - lens distortion
  78808. // - depth-of-field blur & highlights enhancing
  78809. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  78810. // - grain effect (noise or custom texture)
  78811. // Two additional texture samplers are needed:
  78812. // - depth map (for depth-of-field)
  78813. // - grain texture
  78814. /**
  78815. * The chromatic aberration PostProcess id in the pipeline
  78816. */
  78817. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  78818. /**
  78819. * The highlights enhancing PostProcess id in the pipeline
  78820. */
  78821. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  78822. /**
  78823. * The depth-of-field PostProcess id in the pipeline
  78824. */
  78825. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  78826. _this._scene = scene;
  78827. // Fetch texture samplers
  78828. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  78829. if (parameters.grain_texture) {
  78830. _this._grainTexture = parameters.grain_texture;
  78831. }
  78832. else {
  78833. _this._createGrainTexture();
  78834. }
  78835. // save parameters
  78836. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  78837. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  78838. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  78839. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  78840. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  78841. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  78842. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  78843. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  78844. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  78845. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  78846. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  78847. // Create effects
  78848. _this._createChromaticAberrationPostProcess(ratio);
  78849. _this._createHighlightsPostProcess(ratio);
  78850. _this._createDepthOfFieldPostProcess(ratio / 4);
  78851. // Set up pipeline
  78852. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  78853. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  78854. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  78855. if (_this._highlightsGain === -1) {
  78856. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  78857. }
  78858. // Finish
  78859. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78860. if (cameras) {
  78861. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78862. }
  78863. return _this;
  78864. }
  78865. // public methods (self explanatory)
  78866. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  78867. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  78868. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  78869. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  78870. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  78871. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  78872. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  78873. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  78874. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  78875. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  78876. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  78877. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  78878. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  78879. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  78880. };
  78881. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  78882. this._highlightsPostProcess.updateEffect();
  78883. };
  78884. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  78885. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  78886. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  78887. this._highlightsGain = amount;
  78888. };
  78889. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  78890. if (this._highlightsGain === -1) {
  78891. this._highlightsGain = 1.0;
  78892. }
  78893. this._highlightsThreshold = amount;
  78894. };
  78895. LensRenderingPipeline.prototype.disableHighlights = function () {
  78896. this._highlightsGain = -1;
  78897. };
  78898. /**
  78899. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  78900. */
  78901. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  78902. if (disableDepthRender === void 0) { disableDepthRender = false; }
  78903. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78904. this._chromaticAberrationPostProcess = null;
  78905. this._highlightsPostProcess = null;
  78906. this._depthOfFieldPostProcess = null;
  78907. this._grainTexture.dispose();
  78908. if (disableDepthRender)
  78909. this._scene.disableDepthRenderer();
  78910. };
  78911. // colors shifting and distortion
  78912. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  78913. var _this = this;
  78914. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  78915. [], // samplers
  78916. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78917. this._chromaticAberrationPostProcess.onApply = function (effect) {
  78918. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  78919. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78920. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78921. effect.setFloat('radialIntensity', 1);
  78922. effect.setFloat2('direction', 17, 17);
  78923. effect.setFloat2('centerPosition', 0.5, 0.5);
  78924. };
  78925. };
  78926. // highlights enhancing
  78927. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  78928. var _this = this;
  78929. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  78930. [], // samplers
  78931. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  78932. this._highlightsPostProcess.onApply = function (effect) {
  78933. effect.setFloat('gain', _this._highlightsGain);
  78934. effect.setFloat('threshold', _this._highlightsThreshold);
  78935. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  78936. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78937. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78938. };
  78939. };
  78940. // colors shifting and distortion
  78941. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  78942. var _this = this;
  78943. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  78944. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  78945. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  78946. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78947. this._depthOfFieldPostProcess.onApply = function (effect) {
  78948. effect.setTexture("depthSampler", _this._depthTexture);
  78949. effect.setTexture("grainSampler", _this._grainTexture);
  78950. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  78951. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  78952. effect.setFloat('grain_amount', _this._grainAmount);
  78953. effect.setBool('blur_noise', _this._blurNoise);
  78954. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78955. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78956. effect.setFloat('distortion', _this._distortion);
  78957. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  78958. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  78959. effect.setFloat('aperture', _this._dofAperture);
  78960. effect.setFloat('darken', _this._dofDarken);
  78961. effect.setFloat('edge_blur', _this._edgeBlur);
  78962. effect.setBool('highlights', (_this._highlightsGain !== -1));
  78963. if (_this._scene.activeCamera) {
  78964. effect.setFloat('near', _this._scene.activeCamera.minZ);
  78965. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  78966. }
  78967. };
  78968. };
  78969. // creates a black and white random noise texture, 512x512
  78970. LensRenderingPipeline.prototype._createGrainTexture = function () {
  78971. var size = 512;
  78972. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78973. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78974. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78975. var context = this._grainTexture.getContext();
  78976. var rand = function (min, max) {
  78977. return Math.random() * (max - min) + min;
  78978. };
  78979. var value;
  78980. for (var x = 0; x < size; x++) {
  78981. for (var y = 0; y < size; y++) {
  78982. value = Math.floor(rand(0.42, 0.58) * 255);
  78983. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  78984. context.fillRect(x, y, 1, 1);
  78985. }
  78986. }
  78987. this._grainTexture.update(false);
  78988. };
  78989. return LensRenderingPipeline;
  78990. }(BABYLON.PostProcessRenderPipeline));
  78991. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  78992. })(BABYLON || (BABYLON = {}));
  78993. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  78994. var BABYLON;
  78995. (function (BABYLON) {
  78996. var StandardRenderingPipeline = /** @class */ (function (_super) {
  78997. __extends(StandardRenderingPipeline, _super);
  78998. /**
  78999. * @constructor
  79000. * @param {string} name - The rendering pipeline name
  79001. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  79002. * @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)
  79003. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  79004. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  79005. */
  79006. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  79007. if (originalPostProcess === void 0) { originalPostProcess = null; }
  79008. var _this = _super.call(this, scene.getEngine(), name) || this;
  79009. /**
  79010. * Post-process used to down scale an image x4
  79011. */
  79012. _this.downSampleX4PostProcess = null;
  79013. /**
  79014. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  79015. */
  79016. _this.brightPassPostProcess = null;
  79017. /**
  79018. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  79019. */
  79020. _this.blurHPostProcesses = [];
  79021. /**
  79022. * Post-process array storing all the vertical blur post-processes used by the pipeline
  79023. */
  79024. _this.blurVPostProcesses = [];
  79025. /**
  79026. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  79027. */
  79028. _this.textureAdderPostProcess = null;
  79029. /**
  79030. * Post-process used to create volumetric lighting effect
  79031. */
  79032. _this.volumetricLightPostProcess = null;
  79033. /**
  79034. * Post-process used to smooth the previous volumetric light post-process on the X axis
  79035. */
  79036. _this.volumetricLightSmoothXPostProcess = null;
  79037. /**
  79038. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  79039. */
  79040. _this.volumetricLightSmoothYPostProcess = null;
  79041. /**
  79042. * Post-process used to merge the volumetric light effect and the real scene color
  79043. */
  79044. _this.volumetricLightMergePostProces = null;
  79045. /**
  79046. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  79047. */
  79048. _this.volumetricLightFinalPostProcess = null;
  79049. /**
  79050. * Base post-process used to calculate the average luminance of the final image for HDR
  79051. */
  79052. _this.luminancePostProcess = null;
  79053. /**
  79054. * Post-processes used to create down sample post-processes in order to get
  79055. * the average luminance of the final image for HDR
  79056. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  79057. */
  79058. _this.luminanceDownSamplePostProcesses = [];
  79059. /**
  79060. * Post-process used to create a HDR effect (light adaptation)
  79061. */
  79062. _this.hdrPostProcess = null;
  79063. /**
  79064. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  79065. */
  79066. _this.textureAdderFinalPostProcess = null;
  79067. /**
  79068. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  79069. */
  79070. _this.lensFlareFinalPostProcess = null;
  79071. /**
  79072. * Post-process used to merge the final HDR post-process and the real scene color
  79073. */
  79074. _this.hdrFinalPostProcess = null;
  79075. /**
  79076. * Post-process used to create a lens flare effect
  79077. */
  79078. _this.lensFlarePostProcess = null;
  79079. /**
  79080. * Post-process that merges the result of the lens flare post-process and the real scene color
  79081. */
  79082. _this.lensFlareComposePostProcess = null;
  79083. /**
  79084. * Post-process used to create a motion blur effect
  79085. */
  79086. _this.motionBlurPostProcess = null;
  79087. /**
  79088. * Post-process used to create a depth of field effect
  79089. */
  79090. _this.depthOfFieldPostProcess = null;
  79091. /**
  79092. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  79093. */
  79094. _this.fxaaPostProcess = null;
  79095. // Values
  79096. /**
  79097. * Represents the brightness threshold in order to configure the illuminated surfaces
  79098. */
  79099. _this.brightThreshold = 1.0;
  79100. /**
  79101. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  79102. */
  79103. _this.blurWidth = 512.0;
  79104. /**
  79105. * Sets if the blur for highlighted surfaces must be only horizontal
  79106. */
  79107. _this.horizontalBlur = false;
  79108. /**
  79109. * Sets the overall exposure used by the pipeline
  79110. */
  79111. _this.exposure = 1.0;
  79112. /**
  79113. * Texture used typically to simulate "dirty" on camera lens
  79114. */
  79115. _this.lensTexture = null;
  79116. /**
  79117. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  79118. */
  79119. _this.volumetricLightCoefficient = 0.2;
  79120. /**
  79121. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  79122. */
  79123. _this.volumetricLightPower = 4.0;
  79124. /**
  79125. * Used the set the blur intensity to smooth the volumetric lights
  79126. */
  79127. _this.volumetricLightBlurScale = 64.0;
  79128. /**
  79129. * Light (spot or directional) used to generate the volumetric lights rays
  79130. * The source light must have a shadow generate so the pipeline can get its
  79131. * depth map
  79132. */
  79133. _this.sourceLight = null;
  79134. /**
  79135. * For eye adaptation, represents the minimum luminance the eye can see
  79136. */
  79137. _this.hdrMinimumLuminance = 1.0;
  79138. /**
  79139. * For eye adaptation, represents the decrease luminance speed
  79140. */
  79141. _this.hdrDecreaseRate = 0.5;
  79142. /**
  79143. * For eye adaptation, represents the increase luminance speed
  79144. */
  79145. _this.hdrIncreaseRate = 0.5;
  79146. /**
  79147. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  79148. */
  79149. _this.lensColorTexture = null;
  79150. /**
  79151. * The overall strengh for the lens flare effect
  79152. */
  79153. _this.lensFlareStrength = 20.0;
  79154. /**
  79155. * Dispersion coefficient for lens flare ghosts
  79156. */
  79157. _this.lensFlareGhostDispersal = 1.4;
  79158. /**
  79159. * Main lens flare halo width
  79160. */
  79161. _this.lensFlareHaloWidth = 0.7;
  79162. /**
  79163. * Based on the lens distortion effect, defines how much the lens flare result
  79164. * is distorted
  79165. */
  79166. _this.lensFlareDistortionStrength = 16.0;
  79167. /**
  79168. * Lens star texture must be used to simulate rays on the flares and is available
  79169. * in the documentation
  79170. */
  79171. _this.lensStarTexture = null;
  79172. /**
  79173. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  79174. * flare effect by taking account of the dirt texture
  79175. */
  79176. _this.lensFlareDirtTexture = null;
  79177. /**
  79178. * Represents the focal length for the depth of field effect
  79179. */
  79180. _this.depthOfFieldDistance = 10.0;
  79181. /**
  79182. * Represents the blur intensity for the blurred part of the depth of field effect
  79183. */
  79184. _this.depthOfFieldBlurWidth = 64.0;
  79185. /**
  79186. * For motion blur, defines how much the image is blurred by the movement
  79187. */
  79188. _this.motionStrength = 1.0;
  79189. /**
  79190. * List of animations for the pipeline (IAnimatable implementation)
  79191. */
  79192. _this.animations = [];
  79193. _this._currentDepthOfFieldSource = null;
  79194. _this._hdrCurrentLuminance = 1.0;
  79195. // Getters and setters
  79196. _this._bloomEnabled = false;
  79197. _this._depthOfFieldEnabled = false;
  79198. _this._vlsEnabled = false;
  79199. _this._lensFlareEnabled = false;
  79200. _this._hdrEnabled = false;
  79201. _this._motionBlurEnabled = false;
  79202. _this._fxaaEnabled = false;
  79203. _this._motionBlurSamples = 64.0;
  79204. _this._volumetricLightStepsCount = 50.0;
  79205. _this._samples = 1;
  79206. _this._cameras = cameras || [];
  79207. // Initialize
  79208. _this._scene = scene;
  79209. _this._basePostProcess = originalPostProcess;
  79210. _this._ratio = ratio;
  79211. // Misc
  79212. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79213. // Finish
  79214. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79215. _this._buildPipeline();
  79216. return _this;
  79217. }
  79218. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  79219. /**
  79220. * Specifies if the bloom pipeline is enabled
  79221. */
  79222. get: function () {
  79223. return this._bloomEnabled;
  79224. },
  79225. set: function (enabled) {
  79226. if (this._bloomEnabled === enabled) {
  79227. return;
  79228. }
  79229. this._bloomEnabled = enabled;
  79230. this._buildPipeline();
  79231. },
  79232. enumerable: true,
  79233. configurable: true
  79234. });
  79235. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  79236. /**
  79237. * Specifies if the depth of field pipeline is enabed
  79238. */
  79239. get: function () {
  79240. return this._depthOfFieldEnabled;
  79241. },
  79242. set: function (enabled) {
  79243. if (this._depthOfFieldEnabled === enabled) {
  79244. return;
  79245. }
  79246. this._depthOfFieldEnabled = enabled;
  79247. this._buildPipeline();
  79248. },
  79249. enumerable: true,
  79250. configurable: true
  79251. });
  79252. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  79253. /**
  79254. * Specifies if the lens flare pipeline is enabed
  79255. */
  79256. get: function () {
  79257. return this._lensFlareEnabled;
  79258. },
  79259. set: function (enabled) {
  79260. if (this._lensFlareEnabled === enabled) {
  79261. return;
  79262. }
  79263. this._lensFlareEnabled = enabled;
  79264. this._buildPipeline();
  79265. },
  79266. enumerable: true,
  79267. configurable: true
  79268. });
  79269. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  79270. /**
  79271. * Specifies if the HDR pipeline is enabled
  79272. */
  79273. get: function () {
  79274. return this._hdrEnabled;
  79275. },
  79276. set: function (enabled) {
  79277. if (this._hdrEnabled === enabled) {
  79278. return;
  79279. }
  79280. this._hdrEnabled = enabled;
  79281. this._buildPipeline();
  79282. },
  79283. enumerable: true,
  79284. configurable: true
  79285. });
  79286. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  79287. /**
  79288. * Specifies if the volumetric lights scattering effect is enabled
  79289. */
  79290. get: function () {
  79291. return this._vlsEnabled;
  79292. },
  79293. set: function (enabled) {
  79294. if (this._vlsEnabled === enabled) {
  79295. return;
  79296. }
  79297. if (enabled) {
  79298. var geometry = this._scene.enableGeometryBufferRenderer();
  79299. if (!geometry) {
  79300. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  79301. return;
  79302. }
  79303. }
  79304. this._vlsEnabled = enabled;
  79305. this._buildPipeline();
  79306. },
  79307. enumerable: true,
  79308. configurable: true
  79309. });
  79310. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  79311. /**
  79312. * Specifies if the motion blur effect is enabled
  79313. */
  79314. get: function () {
  79315. return this._motionBlurEnabled;
  79316. },
  79317. set: function (enabled) {
  79318. if (this._motionBlurEnabled === enabled) {
  79319. return;
  79320. }
  79321. this._motionBlurEnabled = enabled;
  79322. this._buildPipeline();
  79323. },
  79324. enumerable: true,
  79325. configurable: true
  79326. });
  79327. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  79328. /**
  79329. * Specifies if anti-aliasing is enabled
  79330. */
  79331. get: function () {
  79332. return this._fxaaEnabled;
  79333. },
  79334. set: function (enabled) {
  79335. if (this._fxaaEnabled === enabled) {
  79336. return;
  79337. }
  79338. this._fxaaEnabled = enabled;
  79339. this._buildPipeline();
  79340. },
  79341. enumerable: true,
  79342. configurable: true
  79343. });
  79344. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  79345. /**
  79346. * Specifies the number of steps used to calculate the volumetric lights
  79347. * Typically in interval [50, 200]
  79348. */
  79349. get: function () {
  79350. return this._volumetricLightStepsCount;
  79351. },
  79352. set: function (count) {
  79353. if (this.volumetricLightPostProcess) {
  79354. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  79355. }
  79356. this._volumetricLightStepsCount = count;
  79357. },
  79358. enumerable: true,
  79359. configurable: true
  79360. });
  79361. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  79362. /**
  79363. * Specifies the number of samples used for the motion blur effect
  79364. * Typically in interval [16, 64]
  79365. */
  79366. get: function () {
  79367. return this._motionBlurSamples;
  79368. },
  79369. set: function (samples) {
  79370. if (this.motionBlurPostProcess) {
  79371. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  79372. }
  79373. this._motionBlurSamples = samples;
  79374. },
  79375. enumerable: true,
  79376. configurable: true
  79377. });
  79378. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  79379. /**
  79380. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  79381. */
  79382. get: function () {
  79383. return this._samples;
  79384. },
  79385. set: function (sampleCount) {
  79386. if (this._samples === sampleCount) {
  79387. return;
  79388. }
  79389. this._samples = sampleCount;
  79390. this._buildPipeline();
  79391. },
  79392. enumerable: true,
  79393. configurable: true
  79394. });
  79395. StandardRenderingPipeline.prototype._buildPipeline = function () {
  79396. var _this = this;
  79397. var ratio = this._ratio;
  79398. var scene = this._scene;
  79399. this._disposePostProcesses();
  79400. this._reset();
  79401. // Create pass post-process
  79402. if (!this._basePostProcess) {
  79403. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  79404. this.originalPostProcess.onApply = function (effect) {
  79405. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  79406. };
  79407. }
  79408. else {
  79409. this.originalPostProcess = this._basePostProcess;
  79410. }
  79411. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  79412. this._currentDepthOfFieldSource = this.originalPostProcess;
  79413. if (this._bloomEnabled) {
  79414. // Create down sample X4 post-process
  79415. this._createDownSampleX4PostProcess(scene, ratio / 2);
  79416. // Create bright pass post-process
  79417. this._createBrightPassPostProcess(scene, ratio / 2);
  79418. // Create gaussian blur post-processes (down sampling blurs)
  79419. this._createBlurPostProcesses(scene, ratio / 4, 1);
  79420. // Create texture adder post-process
  79421. this._createTextureAdderPostProcess(scene, ratio);
  79422. // Create depth-of-field source post-process
  79423. 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);
  79424. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  79425. }
  79426. if (this._vlsEnabled) {
  79427. // Create volumetric light
  79428. this._createVolumetricLightPostProcess(scene, ratio);
  79429. // Create volumetric light final post-process
  79430. 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);
  79431. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  79432. }
  79433. if (this._lensFlareEnabled) {
  79434. // Create lens flare post-process
  79435. this._createLensFlarePostProcess(scene, ratio);
  79436. // Create depth-of-field source post-process post lens-flare and disable it now
  79437. 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);
  79438. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  79439. }
  79440. if (this._hdrEnabled) {
  79441. // Create luminance
  79442. this._createLuminancePostProcesses(scene, this._floatTextureType);
  79443. // Create HDR
  79444. this._createHdrPostProcess(scene, ratio);
  79445. // Create depth-of-field source post-process post hdr and disable it now
  79446. 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);
  79447. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  79448. }
  79449. if (this._depthOfFieldEnabled) {
  79450. // Create gaussian blur used by depth-of-field
  79451. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  79452. // Create depth-of-field post-process
  79453. this._createDepthOfFieldPostProcess(scene, ratio);
  79454. }
  79455. if (this._motionBlurEnabled) {
  79456. // Create motion blur post-process
  79457. this._createMotionBlurPostProcess(scene, ratio);
  79458. }
  79459. if (this._fxaaEnabled) {
  79460. // Create fxaa post-process
  79461. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79462. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  79463. }
  79464. if (this._cameras !== null) {
  79465. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  79466. }
  79467. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  79468. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  79469. }
  79470. };
  79471. // Down Sample X4 Post-Processs
  79472. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  79473. var _this = this;
  79474. var downSampleX4Offsets = new Array(32);
  79475. 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);
  79476. this.downSampleX4PostProcess.onApply = function (effect) {
  79477. var id = 0;
  79478. var width = _this.downSampleX4PostProcess.width;
  79479. var height = _this.downSampleX4PostProcess.height;
  79480. for (var i = -2; i < 2; i++) {
  79481. for (var j = -2; j < 2; j++) {
  79482. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  79483. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  79484. id += 2;
  79485. }
  79486. }
  79487. effect.setArray2("dsOffsets", downSampleX4Offsets);
  79488. };
  79489. // Add to pipeline
  79490. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  79491. };
  79492. // Brightpass Post-Process
  79493. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  79494. var _this = this;
  79495. var brightOffsets = new Array(8);
  79496. 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);
  79497. this.brightPassPostProcess.onApply = function (effect) {
  79498. var sU = (1.0 / _this.brightPassPostProcess.width);
  79499. var sV = (1.0 / _this.brightPassPostProcess.height);
  79500. brightOffsets[0] = -0.5 * sU;
  79501. brightOffsets[1] = 0.5 * sV;
  79502. brightOffsets[2] = 0.5 * sU;
  79503. brightOffsets[3] = 0.5 * sV;
  79504. brightOffsets[4] = -0.5 * sU;
  79505. brightOffsets[5] = -0.5 * sV;
  79506. brightOffsets[6] = 0.5 * sU;
  79507. brightOffsets[7] = -0.5 * sV;
  79508. effect.setArray2("dsOffsets", brightOffsets);
  79509. effect.setFloat("brightThreshold", _this.brightThreshold);
  79510. };
  79511. // Add to pipeline
  79512. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  79513. };
  79514. // Create blur H&V post-processes
  79515. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  79516. var _this = this;
  79517. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  79518. var engine = scene.getEngine();
  79519. 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);
  79520. 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);
  79521. blurX.onActivateObservable.add(function () {
  79522. var dw = blurX.width / engine.getRenderWidth();
  79523. blurX.kernel = _this[blurWidthKey] * dw;
  79524. });
  79525. blurY.onActivateObservable.add(function () {
  79526. var dw = blurY.height / engine.getRenderHeight();
  79527. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  79528. });
  79529. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  79530. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  79531. this.blurHPostProcesses.push(blurX);
  79532. this.blurVPostProcesses.push(blurY);
  79533. };
  79534. // Create texture adder post-process
  79535. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  79536. var _this = this;
  79537. 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);
  79538. this.textureAdderPostProcess.onApply = function (effect) {
  79539. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  79540. effect.setTexture("lensSampler", _this.lensTexture);
  79541. effect.setFloat("exposure", _this.exposure);
  79542. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  79543. };
  79544. // Add to pipeline
  79545. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  79546. };
  79547. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  79548. var _this = this;
  79549. var geometryRenderer = scene.enableGeometryBufferRenderer();
  79550. geometryRenderer.enablePosition = true;
  79551. var geometry = geometryRenderer.getGBuffer();
  79552. // Base post-process
  79553. 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));
  79554. var depthValues = BABYLON.Vector2.Zero();
  79555. this.volumetricLightPostProcess.onApply = function (effect) {
  79556. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  79557. var generator = _this.sourceLight.getShadowGenerator();
  79558. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  79559. effect.setTexture("positionSampler", geometry.textures[2]);
  79560. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  79561. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  79562. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  79563. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  79564. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  79565. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  79566. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  79567. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  79568. effect.setVector2("depthValues", depthValues);
  79569. }
  79570. };
  79571. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  79572. // Smooth
  79573. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  79574. // Merge
  79575. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  79576. this.volumetricLightMergePostProces.onApply = function (effect) {
  79577. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  79578. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  79579. };
  79580. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  79581. };
  79582. // Create luminance
  79583. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  79584. var _this = this;
  79585. // Create luminance
  79586. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  79587. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  79588. var offsets = [];
  79589. this.luminancePostProcess.onApply = function (effect) {
  79590. var sU = (1.0 / _this.luminancePostProcess.width);
  79591. var sV = (1.0 / _this.luminancePostProcess.height);
  79592. offsets[0] = -0.5 * sU;
  79593. offsets[1] = 0.5 * sV;
  79594. offsets[2] = 0.5 * sU;
  79595. offsets[3] = 0.5 * sV;
  79596. offsets[4] = -0.5 * sU;
  79597. offsets[5] = -0.5 * sV;
  79598. offsets[6] = 0.5 * sU;
  79599. offsets[7] = -0.5 * sV;
  79600. effect.setArray2("lumOffsets", offsets);
  79601. };
  79602. // Add to pipeline
  79603. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  79604. // Create down sample luminance
  79605. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  79606. var size = Math.pow(3, i);
  79607. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  79608. if (i === 0) {
  79609. defines += "#define FINAL_DOWN_SAMPLER";
  79610. }
  79611. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  79612. this.luminanceDownSamplePostProcesses.push(postProcess);
  79613. }
  79614. // Create callbacks and add effects
  79615. var lastLuminance = this.luminancePostProcess;
  79616. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  79617. var downSampleOffsets = new Array(18);
  79618. pp.onApply = function (effect) {
  79619. if (!lastLuminance) {
  79620. return;
  79621. }
  79622. var id = 0;
  79623. for (var x = -1; x < 2; x++) {
  79624. for (var y = -1; y < 2; y++) {
  79625. downSampleOffsets[id] = x / lastLuminance.width;
  79626. downSampleOffsets[id + 1] = y / lastLuminance.height;
  79627. id += 2;
  79628. }
  79629. }
  79630. effect.setArray2("dsOffsets", downSampleOffsets);
  79631. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  79632. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  79633. lastLuminance = _this.luminancePostProcess;
  79634. }
  79635. else {
  79636. lastLuminance = pp;
  79637. }
  79638. };
  79639. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  79640. pp.onAfterRender = function (effect) {
  79641. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  79642. 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);
  79643. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  79644. };
  79645. }
  79646. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  79647. });
  79648. };
  79649. // Create HDR post-process
  79650. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  79651. var _this = this;
  79652. 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);
  79653. var outputLiminance = 1;
  79654. var time = 0;
  79655. var lastTime = 0;
  79656. this.hdrPostProcess.onApply = function (effect) {
  79657. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  79658. time += scene.getEngine().getDeltaTime();
  79659. if (outputLiminance < 0) {
  79660. outputLiminance = _this._hdrCurrentLuminance;
  79661. }
  79662. else {
  79663. var dt = (lastTime - time) / 1000.0;
  79664. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  79665. outputLiminance += _this.hdrDecreaseRate * dt;
  79666. }
  79667. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  79668. outputLiminance -= _this.hdrIncreaseRate * dt;
  79669. }
  79670. else {
  79671. outputLiminance = _this._hdrCurrentLuminance;
  79672. }
  79673. }
  79674. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  79675. effect.setFloat("averageLuminance", outputLiminance);
  79676. lastTime = time;
  79677. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  79678. };
  79679. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  79680. };
  79681. // Create lens flare post-process
  79682. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  79683. var _this = this;
  79684. 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);
  79685. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  79686. this._createBlurPostProcesses(scene, ratio / 4, 2);
  79687. 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);
  79688. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  79689. var resolution = new BABYLON.Vector2(0, 0);
  79690. // Lens flare
  79691. this.lensFlarePostProcess.onApply = function (effect) {
  79692. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  79693. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  79694. effect.setFloat("strength", _this.lensFlareStrength);
  79695. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  79696. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  79697. // Shift
  79698. resolution.x = _this.lensFlarePostProcess.width;
  79699. resolution.y = _this.lensFlarePostProcess.height;
  79700. effect.setVector2("resolution", resolution);
  79701. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  79702. };
  79703. // Compose
  79704. 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);
  79705. 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);
  79706. this.lensFlareComposePostProcess.onApply = function (effect) {
  79707. if (!_this._scene.activeCamera) {
  79708. return;
  79709. }
  79710. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  79711. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  79712. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  79713. // Lens start rotation matrix
  79714. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  79715. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  79716. 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));
  79717. camRot *= 4.0;
  79718. 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);
  79719. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  79720. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  79721. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  79722. };
  79723. };
  79724. // Create depth-of-field post-process
  79725. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  79726. var _this = this;
  79727. 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);
  79728. this.depthOfFieldPostProcess.onApply = function (effect) {
  79729. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  79730. effect.setTexture("depthSampler", _this._getDepthTexture());
  79731. effect.setFloat("distance", _this.depthOfFieldDistance);
  79732. };
  79733. // Add to pipeline
  79734. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  79735. };
  79736. // Create motion blur post-process
  79737. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  79738. var _this = this;
  79739. 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);
  79740. var motionScale = 0;
  79741. var prevViewProjection = BABYLON.Matrix.Identity();
  79742. var invViewProjection = BABYLON.Matrix.Identity();
  79743. var viewProjection = BABYLON.Matrix.Identity();
  79744. var screenSize = BABYLON.Vector2.Zero();
  79745. this.motionBlurPostProcess.onApply = function (effect) {
  79746. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  79747. viewProjection.invertToRef(invViewProjection);
  79748. effect.setMatrix("inverseViewProjection", invViewProjection);
  79749. effect.setMatrix("prevViewProjection", prevViewProjection);
  79750. prevViewProjection = viewProjection;
  79751. screenSize.x = _this.motionBlurPostProcess.width;
  79752. screenSize.y = _this.motionBlurPostProcess.height;
  79753. effect.setVector2("screenSize", screenSize);
  79754. motionScale = scene.getEngine().getFps() / 60.0;
  79755. effect.setFloat("motionScale", motionScale);
  79756. effect.setFloat("motionStrength", _this.motionStrength);
  79757. effect.setTexture("depthSampler", _this._getDepthTexture());
  79758. };
  79759. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  79760. };
  79761. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  79762. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  79763. var renderer = this._scene.enableGeometryBufferRenderer();
  79764. return renderer.getGBuffer().textures[0];
  79765. }
  79766. return this._scene.enableDepthRenderer().getDepthMap();
  79767. };
  79768. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  79769. for (var i = 0; i < this._cameras.length; i++) {
  79770. var camera = this._cameras[i];
  79771. if (this.originalPostProcess) {
  79772. this.originalPostProcess.dispose(camera);
  79773. }
  79774. if (this.downSampleX4PostProcess) {
  79775. this.downSampleX4PostProcess.dispose(camera);
  79776. }
  79777. if (this.brightPassPostProcess) {
  79778. this.brightPassPostProcess.dispose(camera);
  79779. }
  79780. if (this.textureAdderPostProcess) {
  79781. this.textureAdderPostProcess.dispose(camera);
  79782. }
  79783. if (this.textureAdderFinalPostProcess) {
  79784. this.textureAdderFinalPostProcess.dispose(camera);
  79785. }
  79786. if (this.volumetricLightPostProcess) {
  79787. this.volumetricLightPostProcess.dispose(camera);
  79788. }
  79789. if (this.volumetricLightSmoothXPostProcess) {
  79790. this.volumetricLightSmoothXPostProcess.dispose(camera);
  79791. }
  79792. if (this.volumetricLightSmoothYPostProcess) {
  79793. this.volumetricLightSmoothYPostProcess.dispose(camera);
  79794. }
  79795. if (this.volumetricLightMergePostProces) {
  79796. this.volumetricLightMergePostProces.dispose(camera);
  79797. }
  79798. if (this.volumetricLightFinalPostProcess) {
  79799. this.volumetricLightFinalPostProcess.dispose(camera);
  79800. }
  79801. if (this.lensFlarePostProcess) {
  79802. this.lensFlarePostProcess.dispose(camera);
  79803. }
  79804. if (this.lensFlareComposePostProcess) {
  79805. this.lensFlareComposePostProcess.dispose(camera);
  79806. }
  79807. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  79808. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  79809. }
  79810. if (this.luminancePostProcess) {
  79811. this.luminancePostProcess.dispose(camera);
  79812. }
  79813. if (this.hdrPostProcess) {
  79814. this.hdrPostProcess.dispose(camera);
  79815. }
  79816. if (this.hdrFinalPostProcess) {
  79817. this.hdrFinalPostProcess.dispose(camera);
  79818. }
  79819. if (this.depthOfFieldPostProcess) {
  79820. this.depthOfFieldPostProcess.dispose(camera);
  79821. }
  79822. if (this.motionBlurPostProcess) {
  79823. this.motionBlurPostProcess.dispose(camera);
  79824. }
  79825. if (this.fxaaPostProcess) {
  79826. this.fxaaPostProcess.dispose(camera);
  79827. }
  79828. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  79829. this.blurHPostProcesses[j].dispose(camera);
  79830. }
  79831. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  79832. this.blurVPostProcesses[j].dispose(camera);
  79833. }
  79834. }
  79835. this.originalPostProcess = null;
  79836. this.downSampleX4PostProcess = null;
  79837. this.brightPassPostProcess = null;
  79838. this.textureAdderPostProcess = null;
  79839. this.textureAdderFinalPostProcess = null;
  79840. this.volumetricLightPostProcess = null;
  79841. this.volumetricLightSmoothXPostProcess = null;
  79842. this.volumetricLightSmoothYPostProcess = null;
  79843. this.volumetricLightMergePostProces = null;
  79844. this.volumetricLightFinalPostProcess = null;
  79845. this.lensFlarePostProcess = null;
  79846. this.lensFlareComposePostProcess = null;
  79847. this.luminancePostProcess = null;
  79848. this.hdrPostProcess = null;
  79849. this.hdrFinalPostProcess = null;
  79850. this.depthOfFieldPostProcess = null;
  79851. this.motionBlurPostProcess = null;
  79852. this.fxaaPostProcess = null;
  79853. this.luminanceDownSamplePostProcesses = [];
  79854. this.blurHPostProcesses = [];
  79855. this.blurVPostProcesses = [];
  79856. };
  79857. /**
  79858. * Dispose of the pipeline and stop all post processes
  79859. */
  79860. StandardRenderingPipeline.prototype.dispose = function () {
  79861. this._disposePostProcesses();
  79862. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  79863. _super.prototype.dispose.call(this);
  79864. };
  79865. /**
  79866. * Serialize the rendering pipeline (Used when exporting)
  79867. * @returns the serialized object
  79868. */
  79869. StandardRenderingPipeline.prototype.serialize = function () {
  79870. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79871. if (this.sourceLight) {
  79872. serializationObject.sourceLightId = this.sourceLight.id;
  79873. }
  79874. serializationObject.customType = "StandardRenderingPipeline";
  79875. return serializationObject;
  79876. };
  79877. /**
  79878. * Parse the serialized pipeline
  79879. * @param source Source pipeline.
  79880. * @param scene The scene to load the pipeline to.
  79881. * @param rootUrl The URL of the serialized pipeline.
  79882. * @returns An instantiated pipeline from the serialized object.
  79883. */
  79884. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  79885. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  79886. if (source.sourceLightId) {
  79887. p.sourceLight = scene.getLightByID(source.sourceLightId);
  79888. }
  79889. return p;
  79890. };
  79891. // Luminance steps
  79892. StandardRenderingPipeline.LuminanceSteps = 6;
  79893. __decorate([
  79894. BABYLON.serialize()
  79895. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  79896. __decorate([
  79897. BABYLON.serialize()
  79898. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  79899. __decorate([
  79900. BABYLON.serialize()
  79901. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  79902. __decorate([
  79903. BABYLON.serialize()
  79904. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  79905. __decorate([
  79906. BABYLON.serializeAsTexture("lensTexture")
  79907. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  79908. __decorate([
  79909. BABYLON.serialize()
  79910. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  79911. __decorate([
  79912. BABYLON.serialize()
  79913. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  79914. __decorate([
  79915. BABYLON.serialize()
  79916. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  79917. __decorate([
  79918. BABYLON.serialize()
  79919. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  79920. __decorate([
  79921. BABYLON.serialize()
  79922. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  79923. __decorate([
  79924. BABYLON.serialize()
  79925. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  79926. __decorate([
  79927. BABYLON.serializeAsTexture("lensColorTexture")
  79928. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  79929. __decorate([
  79930. BABYLON.serialize()
  79931. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  79932. __decorate([
  79933. BABYLON.serialize()
  79934. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  79935. __decorate([
  79936. BABYLON.serialize()
  79937. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  79938. __decorate([
  79939. BABYLON.serialize()
  79940. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  79941. __decorate([
  79942. BABYLON.serializeAsTexture("lensStarTexture")
  79943. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  79944. __decorate([
  79945. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  79946. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  79947. __decorate([
  79948. BABYLON.serialize()
  79949. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  79950. __decorate([
  79951. BABYLON.serialize()
  79952. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  79953. __decorate([
  79954. BABYLON.serialize()
  79955. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  79956. __decorate([
  79957. BABYLON.serialize()
  79958. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  79959. __decorate([
  79960. BABYLON.serialize()
  79961. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  79962. __decorate([
  79963. BABYLON.serialize()
  79964. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  79965. __decorate([
  79966. BABYLON.serialize()
  79967. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  79968. __decorate([
  79969. BABYLON.serialize()
  79970. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  79971. __decorate([
  79972. BABYLON.serialize()
  79973. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  79974. __decorate([
  79975. BABYLON.serialize()
  79976. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  79977. __decorate([
  79978. BABYLON.serialize()
  79979. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  79980. __decorate([
  79981. BABYLON.serialize()
  79982. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  79983. __decorate([
  79984. BABYLON.serialize()
  79985. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  79986. __decorate([
  79987. BABYLON.serialize()
  79988. ], StandardRenderingPipeline.prototype, "samples", null);
  79989. return StandardRenderingPipeline;
  79990. }(BABYLON.PostProcessRenderPipeline));
  79991. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  79992. })(BABYLON || (BABYLON = {}));
  79993. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  79994. var BABYLON;
  79995. (function (BABYLON) {
  79996. var FxaaPostProcess = /** @class */ (function (_super) {
  79997. __extends(FxaaPostProcess, _super);
  79998. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79999. if (camera === void 0) { camera = null; }
  80000. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80001. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  80002. var defines = _this._getDefines();
  80003. _this.updateEffect(defines);
  80004. _this.onApplyObservable.add(function (effect) {
  80005. var texelSize = _this.texelSize;
  80006. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  80007. });
  80008. return _this;
  80009. }
  80010. FxaaPostProcess.prototype._getDefines = function () {
  80011. var engine = this.getEngine();
  80012. if (!engine) {
  80013. return null;
  80014. }
  80015. var glInfo = engine.getGlInfo();
  80016. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  80017. return "#define MALI 1\n";
  80018. }
  80019. return null;
  80020. };
  80021. return FxaaPostProcess;
  80022. }(BABYLON.PostProcess));
  80023. BABYLON.FxaaPostProcess = FxaaPostProcess;
  80024. })(BABYLON || (BABYLON = {}));
  80025. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  80026. var BABYLON;
  80027. (function (BABYLON) {
  80028. /**
  80029. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  80030. */
  80031. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  80032. __extends(ChromaticAberrationPostProcess, _super);
  80033. /**
  80034. * Creates a new instance ChromaticAberrationPostProcess
  80035. * @param name The name of the effect.
  80036. * @param screenWidth The width of the screen to apply the effect on.
  80037. * @param screenHeight The height of the screen to apply the effect on.
  80038. * @param options The required width/height ratio to downsize to before computing the render pass.
  80039. * @param camera The camera to apply the render pass to.
  80040. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80041. * @param engine The engine which the post process will be applied. (default: current engine)
  80042. * @param reusable If the post process can be reused on the same frame. (default: false)
  80043. * @param textureType Type of textures used when performing the post process. (default: 0)
  80044. * @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)
  80045. */
  80046. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80047. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80048. if (blockCompilation === void 0) { blockCompilation = false; }
  80049. 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;
  80050. /**
  80051. * The amount of seperation of rgb channels (default: 30)
  80052. */
  80053. _this.aberrationAmount = 30;
  80054. /**
  80055. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  80056. */
  80057. _this.radialIntensity = 0;
  80058. /**
  80059. * 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))
  80060. */
  80061. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  80062. /**
  80063. * 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))
  80064. */
  80065. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  80066. _this.onApplyObservable.add(function (effect) {
  80067. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  80068. effect.setFloat('screen_width', screenWidth);
  80069. effect.setFloat('screen_height', screenHeight);
  80070. effect.setFloat('radialIntensity', _this.radialIntensity);
  80071. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  80072. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  80073. });
  80074. return _this;
  80075. }
  80076. return ChromaticAberrationPostProcess;
  80077. }(BABYLON.PostProcess));
  80078. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  80079. })(BABYLON || (BABYLON = {}));
  80080. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  80081. var BABYLON;
  80082. (function (BABYLON) {
  80083. /**
  80084. * The GrainPostProcess adds noise to the image at mid luminance levels
  80085. */
  80086. var GrainPostProcess = /** @class */ (function (_super) {
  80087. __extends(GrainPostProcess, _super);
  80088. /**
  80089. * Creates a new instance of @see GrainPostProcess
  80090. * @param name The name of the effect.
  80091. * @param options The required width/height ratio to downsize to before computing the render pass.
  80092. * @param camera The camera to apply the render pass to.
  80093. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80094. * @param engine The engine which the post process will be applied. (default: current engine)
  80095. * @param reusable If the post process can be reused on the same frame. (default: false)
  80096. * @param textureType Type of textures used when performing the post process. (default: 0)
  80097. * @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)
  80098. */
  80099. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80100. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80101. if (blockCompilation === void 0) { blockCompilation = false; }
  80102. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80103. /**
  80104. * The intensity of the grain added (default: 30)
  80105. */
  80106. _this.intensity = 30;
  80107. /**
  80108. * If the grain should be randomized on every frame
  80109. */
  80110. _this.animated = false;
  80111. _this.onApplyObservable.add(function (effect) {
  80112. effect.setFloat('intensity', _this.intensity);
  80113. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  80114. });
  80115. return _this;
  80116. }
  80117. return GrainPostProcess;
  80118. }(BABYLON.PostProcess));
  80119. BABYLON.GrainPostProcess = GrainPostProcess;
  80120. })(BABYLON || (BABYLON = {}));
  80121. //# sourceMappingURL=babylon.grainPostProcess.js.map
  80122. var BABYLON;
  80123. (function (BABYLON) {
  80124. /**
  80125. * The SharpenPostProcess applies a sharpen kernel to every pixel
  80126. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  80127. */
  80128. var SharpenPostProcess = /** @class */ (function (_super) {
  80129. __extends(SharpenPostProcess, _super);
  80130. /**
  80131. * Creates a new instance ConvolutionPostProcess
  80132. * @param name The name of the effect.
  80133. * @param options The required width/height ratio to downsize to before computing the render pass.
  80134. * @param camera The camera to apply the render pass to.
  80135. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80136. * @param engine The engine which the post process will be applied. (default: current engine)
  80137. * @param reusable If the post process can be reused on the same frame. (default: false)
  80138. * @param textureType Type of textures used when performing the post process. (default: 0)
  80139. * @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)
  80140. */
  80141. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80142. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80143. if (blockCompilation === void 0) { blockCompilation = false; }
  80144. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80145. /**
  80146. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  80147. */
  80148. _this.colorAmount = 1.0;
  80149. /**
  80150. * How much sharpness should be applied (default: 0.3)
  80151. */
  80152. _this.edgeAmount = 0.3;
  80153. _this.onApply = function (effect) {
  80154. effect.setFloat2("screenSize", _this.width, _this.height);
  80155. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  80156. };
  80157. return _this;
  80158. }
  80159. return SharpenPostProcess;
  80160. }(BABYLON.PostProcess));
  80161. BABYLON.SharpenPostProcess = SharpenPostProcess;
  80162. })(BABYLON || (BABYLON = {}));
  80163. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  80164. var BABYLON;
  80165. (function (BABYLON) {
  80166. /**
  80167. * The Blur Post Process which blurs an image based on a kernel and direction.
  80168. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  80169. */
  80170. var BlurPostProcess = /** @class */ (function (_super) {
  80171. __extends(BlurPostProcess, _super);
  80172. /**
  80173. * Creates a new instance BlurPostProcess
  80174. * @param name The name of the effect.
  80175. * @param direction The direction in which to blur the image.
  80176. * @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.
  80177. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  80178. * @param camera The camera to apply the render pass to.
  80179. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80180. * @param engine The engine which the post process will be applied. (default: current engine)
  80181. * @param reusable If the post process can be reused on the same frame. (default: false)
  80182. * @param textureType Type of textures used when performing the post process. (default: 0)
  80183. * @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)
  80184. */
  80185. function BlurPostProcess(name,
  80186. /** The direction in which to blur the image. */
  80187. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  80188. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80189. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80190. if (defines === void 0) { defines = ""; }
  80191. if (blockCompilation === void 0) { blockCompilation = false; }
  80192. 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;
  80193. _this.direction = direction;
  80194. _this.blockCompilation = blockCompilation;
  80195. _this._packedFloat = false;
  80196. _this._staticDefines = "";
  80197. _this._staticDefines = defines;
  80198. _this.onApplyObservable.add(function (effect) {
  80199. if (_this._outputTexture) {
  80200. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  80201. }
  80202. else {
  80203. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  80204. }
  80205. });
  80206. _this.kernel = kernel;
  80207. return _this;
  80208. }
  80209. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  80210. /**
  80211. * Gets the length in pixels of the blur sample region
  80212. */
  80213. get: function () {
  80214. return this._idealKernel;
  80215. },
  80216. /**
  80217. * Sets the length in pixels of the blur sample region
  80218. */
  80219. set: function (v) {
  80220. if (this._idealKernel === v) {
  80221. return;
  80222. }
  80223. v = Math.max(v, 1);
  80224. this._idealKernel = v;
  80225. this._kernel = this._nearestBestKernel(v);
  80226. if (!this.blockCompilation) {
  80227. this._updateParameters();
  80228. }
  80229. },
  80230. enumerable: true,
  80231. configurable: true
  80232. });
  80233. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  80234. /**
  80235. * Gets wether or not the blur is unpacking/repacking floats
  80236. */
  80237. get: function () {
  80238. return this._packedFloat;
  80239. },
  80240. /**
  80241. * Sets wether or not the blur needs to unpack/repack floats
  80242. */
  80243. set: function (v) {
  80244. if (this._packedFloat === v) {
  80245. return;
  80246. }
  80247. this._packedFloat = v;
  80248. if (!this.blockCompilation) {
  80249. this._updateParameters();
  80250. }
  80251. },
  80252. enumerable: true,
  80253. configurable: true
  80254. });
  80255. /**
  80256. * Updates the effect with the current post process compile time values and recompiles the shader.
  80257. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80258. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80259. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80260. * @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
  80261. * @param onCompiled Called when the shader has been compiled.
  80262. * @param onError Called if there is an error when compiling a shader.
  80263. */
  80264. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80265. if (defines === void 0) { defines = null; }
  80266. if (uniforms === void 0) { uniforms = null; }
  80267. if (samplers === void 0) { samplers = null; }
  80268. this._updateParameters(onCompiled, onError);
  80269. };
  80270. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  80271. // Generate sampling offsets and weights
  80272. var N = this._kernel;
  80273. var centerIndex = (N - 1) / 2;
  80274. // Generate Gaussian sampling weights over kernel
  80275. var offsets = [];
  80276. var weights = [];
  80277. var totalWeight = 0;
  80278. for (var i = 0; i < N; i++) {
  80279. var u = i / (N - 1);
  80280. var w = this._gaussianWeight(u * 2.0 - 1);
  80281. offsets[i] = (i - centerIndex);
  80282. weights[i] = w;
  80283. totalWeight += w;
  80284. }
  80285. // Normalize weights
  80286. for (var i = 0; i < weights.length; i++) {
  80287. weights[i] /= totalWeight;
  80288. }
  80289. // Optimize: combine samples to take advantage of hardware linear sampling
  80290. // Walk from left to center, combining pairs (symmetrically)
  80291. var linearSamplingWeights = [];
  80292. var linearSamplingOffsets = [];
  80293. var linearSamplingMap = [];
  80294. for (var i = 0; i <= centerIndex; i += 2) {
  80295. var j = Math.min(i + 1, Math.floor(centerIndex));
  80296. var singleCenterSample = i === j;
  80297. if (singleCenterSample) {
  80298. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80299. }
  80300. else {
  80301. var sharedCell = j === centerIndex;
  80302. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  80303. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  80304. if (offsetLinear === 0) {
  80305. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80306. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  80307. }
  80308. else {
  80309. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  80310. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  80311. }
  80312. }
  80313. }
  80314. for (var i = 0; i < linearSamplingMap.length; i++) {
  80315. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  80316. linearSamplingWeights[i] = linearSamplingMap[i].w;
  80317. }
  80318. // Replace with optimized
  80319. offsets = linearSamplingOffsets;
  80320. weights = linearSamplingWeights;
  80321. // Generate shaders
  80322. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  80323. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  80324. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  80325. var defines = "";
  80326. defines += this._staticDefines;
  80327. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  80328. if (this._staticDefines.indexOf("DOF") != -1) {
  80329. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  80330. varyingCount--;
  80331. }
  80332. for (var i = 0; i < varyingCount; i++) {
  80333. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  80334. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  80335. }
  80336. var depCount = 0;
  80337. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  80338. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  80339. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  80340. depCount++;
  80341. }
  80342. if (this.packedFloat) {
  80343. defines += "#define PACKEDFLOAT 1";
  80344. }
  80345. this.blockCompilation = false;
  80346. _super.prototype.updateEffect.call(this, defines, null, null, {
  80347. varyingCount: varyingCount,
  80348. depCount: depCount
  80349. }, onCompiled, onError);
  80350. };
  80351. /**
  80352. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  80353. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  80354. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  80355. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  80356. * The gaps between physical kernels are compensated for in the weighting of the samples
  80357. * @param idealKernel Ideal blur kernel.
  80358. * @return Nearest best kernel.
  80359. */
  80360. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  80361. var v = Math.round(idealKernel);
  80362. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  80363. var k = _a[_i];
  80364. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  80365. return Math.max(k, 3);
  80366. }
  80367. }
  80368. return Math.max(v, 3);
  80369. };
  80370. /**
  80371. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  80372. * @param x The point on the Gaussian distribution to sample.
  80373. * @return the value of the Gaussian function at x.
  80374. */
  80375. BlurPostProcess.prototype._gaussianWeight = function (x) {
  80376. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  80377. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  80378. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  80379. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  80380. // truncated at around 1.3% of peak strength.
  80381. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  80382. var sigma = (1 / 3);
  80383. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  80384. var exponent = -((x * x) / (2.0 * sigma * sigma));
  80385. var weight = (1.0 / denominator) * Math.exp(exponent);
  80386. return weight;
  80387. };
  80388. /**
  80389. * Generates a string that can be used as a floating point number in GLSL.
  80390. * @param x Value to print.
  80391. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  80392. * @return GLSL float string.
  80393. */
  80394. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  80395. if (decimalFigures === void 0) { decimalFigures = 8; }
  80396. return x.toFixed(decimalFigures).replace(/0+$/, '');
  80397. };
  80398. return BlurPostProcess;
  80399. }(BABYLON.PostProcess));
  80400. BABYLON.BlurPostProcess = BlurPostProcess;
  80401. })(BABYLON || (BABYLON = {}));
  80402. //# sourceMappingURL=babylon.blurPostProcess.js.map
  80403. var BABYLON;
  80404. (function (BABYLON) {
  80405. /**
  80406. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  80407. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  80408. * based on samples that have a large difference in distance than the center pixel.
  80409. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  80410. */
  80411. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  80412. __extends(DepthOfFieldBlurPostProcess, _super);
  80413. /**
  80414. * Creates a new instance CircleOfConfusionPostProcess
  80415. * @param name The name of the effect.
  80416. * @param scene The scene the effect belongs to.
  80417. * @param direction The direction the blur should be applied.
  80418. * @param kernel The size of the kernel used to blur.
  80419. * @param options The required width/height ratio to downsize to before computing the render pass.
  80420. * @param camera The camera to apply the render pass to.
  80421. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  80422. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  80423. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80424. * @param engine The engine which the post process will be applied. (default: current engine)
  80425. * @param reusable If the post process can be reused on the same frame. (default: false)
  80426. * @param textureType Type of textures used when performing the post process. (default: 0)
  80427. * @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)
  80428. */
  80429. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  80430. if (imageToBlur === void 0) { imageToBlur = null; }
  80431. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80432. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80433. if (blockCompilation === void 0) { blockCompilation = false; }
  80434. 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;
  80435. _this.direction = direction;
  80436. _this.onApplyObservable.add(function (effect) {
  80437. if (imageToBlur != null) {
  80438. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  80439. }
  80440. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  80441. if (scene.activeCamera) {
  80442. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  80443. }
  80444. });
  80445. return _this;
  80446. }
  80447. return DepthOfFieldBlurPostProcess;
  80448. }(BABYLON.BlurPostProcess));
  80449. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  80450. })(BABYLON || (BABYLON = {}));
  80451. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  80452. var BABYLON;
  80453. (function (BABYLON) {
  80454. /**
  80455. * Options to be set when merging outputs from the default pipeline.
  80456. */
  80457. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  80458. function DepthOfFieldMergePostProcessOptions() {
  80459. }
  80460. return DepthOfFieldMergePostProcessOptions;
  80461. }());
  80462. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  80463. /**
  80464. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  80465. */
  80466. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  80467. __extends(DepthOfFieldMergePostProcess, _super);
  80468. /**
  80469. * Creates a new instance of DepthOfFieldMergePostProcess
  80470. * @param name The name of the effect.
  80471. * @param originalFromInput Post process which's input will be used for the merge.
  80472. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  80473. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  80474. * @param options The required width/height ratio to downsize to before computing the render pass.
  80475. * @param camera The camera to apply the render pass to.
  80476. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80477. * @param engine The engine which the post process will be applied. (default: current engine)
  80478. * @param reusable If the post process can be reused on the same frame. (default: false)
  80479. * @param textureType Type of textures used when performing the post process. (default: 0)
  80480. * @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)
  80481. */
  80482. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80483. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80484. if (blockCompilation === void 0) { blockCompilation = false; }
  80485. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  80486. _this.blurSteps = blurSteps;
  80487. _this.onApplyObservable.add(function (effect) {
  80488. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  80489. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  80490. blurSteps.forEach(function (step, index) {
  80491. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  80492. });
  80493. });
  80494. if (!blockCompilation) {
  80495. _this.updateEffect();
  80496. }
  80497. return _this;
  80498. }
  80499. /**
  80500. * Updates the effect with the current post process compile time values and recompiles the shader.
  80501. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80502. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80503. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80504. * @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
  80505. * @param onCompiled Called when the shader has been compiled.
  80506. * @param onError Called if there is an error when compiling a shader.
  80507. */
  80508. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80509. if (defines === void 0) { defines = null; }
  80510. if (uniforms === void 0) { uniforms = null; }
  80511. if (samplers === void 0) { samplers = null; }
  80512. if (!defines) {
  80513. defines = "";
  80514. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  80515. }
  80516. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  80517. };
  80518. return DepthOfFieldMergePostProcess;
  80519. }(BABYLON.PostProcess));
  80520. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  80521. })(BABYLON || (BABYLON = {}));
  80522. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  80523. var BABYLON;
  80524. (function (BABYLON) {
  80525. /**
  80526. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  80527. */
  80528. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  80529. __extends(CircleOfConfusionPostProcess, _super);
  80530. /**
  80531. * Creates a new instance CircleOfConfusionPostProcess
  80532. * @param name The name of the effect.
  80533. * @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.
  80534. * @param options The required width/height ratio to downsize to before computing the render pass.
  80535. * @param camera The camera to apply the render pass to.
  80536. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80537. * @param engine The engine which the post process will be applied. (default: current engine)
  80538. * @param reusable If the post process can be reused on the same frame. (default: false)
  80539. * @param textureType Type of textures used when performing the post process. (default: 0)
  80540. * @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)
  80541. */
  80542. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80543. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80544. if (blockCompilation === void 0) { blockCompilation = false; }
  80545. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80546. /**
  80547. * 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.
  80548. */
  80549. _this.lensSize = 50;
  80550. /**
  80551. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  80552. */
  80553. _this.fStop = 1.4;
  80554. /**
  80555. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  80556. */
  80557. _this.focusDistance = 2000;
  80558. /**
  80559. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  80560. */
  80561. _this.focalLength = 50;
  80562. _this._depthTexture = null;
  80563. _this._depthTexture = depthTexture;
  80564. _this.onApplyObservable.add(function (effect) {
  80565. if (!_this._depthTexture) {
  80566. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  80567. return;
  80568. }
  80569. effect.setTexture("depthSampler", _this._depthTexture);
  80570. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  80571. var aperture = _this.lensSize / _this.fStop;
  80572. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  80573. effect.setFloat('focusDistance', _this.focusDistance);
  80574. effect.setFloat('cocPrecalculation', cocPrecalculation);
  80575. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  80576. });
  80577. return _this;
  80578. }
  80579. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  80580. /**
  80581. * 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.
  80582. */
  80583. set: function (value) {
  80584. this._depthTexture = value;
  80585. },
  80586. enumerable: true,
  80587. configurable: true
  80588. });
  80589. return CircleOfConfusionPostProcess;
  80590. }(BABYLON.PostProcess));
  80591. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  80592. })(BABYLON || (BABYLON = {}));
  80593. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  80594. var BABYLON;
  80595. (function (BABYLON) {
  80596. /**
  80597. * Specifies the level of max blur that should be applied when using the depth of field effect
  80598. */
  80599. var DepthOfFieldEffectBlurLevel;
  80600. (function (DepthOfFieldEffectBlurLevel) {
  80601. /**
  80602. * Subtle blur
  80603. */
  80604. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  80605. /**
  80606. * Medium blur
  80607. */
  80608. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  80609. /**
  80610. * Large blur
  80611. */
  80612. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  80613. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  80614. ;
  80615. /**
  80616. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  80617. */
  80618. var DepthOfFieldEffect = /** @class */ (function (_super) {
  80619. __extends(DepthOfFieldEffect, _super);
  80620. /**
  80621. * Creates a new instance DepthOfFieldEffect
  80622. * @param scene The scene the effect belongs to.
  80623. * @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.
  80624. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  80625. * @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)
  80626. */
  80627. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  80628. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  80629. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  80630. if (blockCompilation === void 0) { blockCompilation = false; }
  80631. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  80632. return _this._effects;
  80633. }, true) || this;
  80634. /**
  80635. * @hidden Internal post processes in depth of field effect
  80636. */
  80637. _this._effects = [];
  80638. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  80639. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80640. // 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)
  80641. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  80642. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  80643. _this._depthOfFieldBlurY = [];
  80644. _this._depthOfFieldBlurX = [];
  80645. var blurCount = 1;
  80646. var kernelSize = 15;
  80647. switch (blurLevel) {
  80648. case DepthOfFieldEffectBlurLevel.High: {
  80649. blurCount = 3;
  80650. kernelSize = 51;
  80651. break;
  80652. }
  80653. case DepthOfFieldEffectBlurLevel.Medium: {
  80654. blurCount = 2;
  80655. kernelSize = 31;
  80656. break;
  80657. }
  80658. default: {
  80659. kernelSize = 15;
  80660. blurCount = 1;
  80661. break;
  80662. }
  80663. }
  80664. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  80665. var ratio = 1.0;
  80666. for (var i = 0; i < blurCount; i++) {
  80667. 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);
  80668. blurY.autoClear = false;
  80669. ratio = 0.75 / Math.pow(2, i);
  80670. 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);
  80671. blurX.autoClear = false;
  80672. _this._depthOfFieldBlurY.push(blurY);
  80673. _this._depthOfFieldBlurX.push(blurX);
  80674. }
  80675. // Set all post processes on the effect.
  80676. _this._effects = [_this._circleOfConfusion];
  80677. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  80678. _this._effects.push(_this._depthOfFieldBlurY[i]);
  80679. _this._effects.push(_this._depthOfFieldBlurX[i]);
  80680. }
  80681. // Merge blurred images with original image based on circleOfConfusion
  80682. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80683. _this._dofMerge.autoClear = false;
  80684. _this._effects.push(_this._dofMerge);
  80685. return _this;
  80686. }
  80687. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  80688. get: function () {
  80689. return this._circleOfConfusion.focalLength;
  80690. },
  80691. /**
  80692. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  80693. */
  80694. set: function (value) {
  80695. this._circleOfConfusion.focalLength = value;
  80696. },
  80697. enumerable: true,
  80698. configurable: true
  80699. });
  80700. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  80701. get: function () {
  80702. return this._circleOfConfusion.fStop;
  80703. },
  80704. /**
  80705. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  80706. */
  80707. set: function (value) {
  80708. this._circleOfConfusion.fStop = value;
  80709. },
  80710. enumerable: true,
  80711. configurable: true
  80712. });
  80713. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  80714. get: function () {
  80715. return this._circleOfConfusion.focusDistance;
  80716. },
  80717. /**
  80718. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  80719. */
  80720. set: function (value) {
  80721. this._circleOfConfusion.focusDistance = value;
  80722. },
  80723. enumerable: true,
  80724. configurable: true
  80725. });
  80726. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  80727. get: function () {
  80728. return this._circleOfConfusion.lensSize;
  80729. },
  80730. /**
  80731. * 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.
  80732. */
  80733. set: function (value) {
  80734. this._circleOfConfusion.lensSize = value;
  80735. },
  80736. enumerable: true,
  80737. configurable: true
  80738. });
  80739. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  80740. /**
  80741. * 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.
  80742. */
  80743. set: function (value) {
  80744. this._circleOfConfusion.depthTexture = value;
  80745. },
  80746. enumerable: true,
  80747. configurable: true
  80748. });
  80749. /**
  80750. * Disposes each of the internal effects for a given camera.
  80751. * @param camera The camera to dispose the effect on.
  80752. */
  80753. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  80754. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80755. this._effects[effectIndex].dispose(camera);
  80756. }
  80757. };
  80758. /**
  80759. * @hidden Internal
  80760. */
  80761. DepthOfFieldEffect.prototype._updateEffects = function () {
  80762. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80763. this._effects[effectIndex].updateEffect();
  80764. }
  80765. };
  80766. /**
  80767. * Internal
  80768. * @returns if all the contained post processes are ready.
  80769. * @hidden
  80770. */
  80771. DepthOfFieldEffect.prototype._isReady = function () {
  80772. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80773. if (!this._effects[effectIndex].isReady()) {
  80774. return false;
  80775. }
  80776. }
  80777. return true;
  80778. };
  80779. return DepthOfFieldEffect;
  80780. }(BABYLON.PostProcessRenderEffect));
  80781. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  80782. })(BABYLON || (BABYLON = {}));
  80783. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  80784. var BABYLON;
  80785. (function (BABYLON) {
  80786. /**
  80787. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  80788. */
  80789. var BloomMergePostProcess = /** @class */ (function (_super) {
  80790. __extends(BloomMergePostProcess, _super);
  80791. /**
  80792. * Creates a new instance of @see BloomMergePostProcess
  80793. * @param name The name of the effect.
  80794. * @param originalFromInput Post process which's input will be used for the merge.
  80795. * @param blurred Blurred highlights post process which's output will be used.
  80796. * @param weight Weight of the bloom to be added to the original input.
  80797. * @param options The required width/height ratio to downsize to before computing the render pass.
  80798. * @param camera The camera to apply the render pass to.
  80799. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80800. * @param engine The engine which the post process will be applied. (default: current engine)
  80801. * @param reusable If the post process can be reused on the same frame. (default: false)
  80802. * @param textureType Type of textures used when performing the post process. (default: 0)
  80803. * @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)
  80804. */
  80805. function BloomMergePostProcess(name, originalFromInput, blurred,
  80806. /** Weight of the bloom to be added to the original input. */
  80807. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80808. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80809. if (blockCompilation === void 0) { blockCompilation = false; }
  80810. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  80811. _this.weight = weight;
  80812. _this.onApplyObservable.add(function (effect) {
  80813. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  80814. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  80815. effect.setFloat("bloomWeight", _this.weight);
  80816. });
  80817. if (!blockCompilation) {
  80818. _this.updateEffect();
  80819. }
  80820. return _this;
  80821. }
  80822. return BloomMergePostProcess;
  80823. }(BABYLON.PostProcess));
  80824. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  80825. })(BABYLON || (BABYLON = {}));
  80826. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  80827. var BABYLON;
  80828. (function (BABYLON) {
  80829. /**
  80830. * 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.
  80831. */
  80832. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  80833. __extends(ExtractHighlightsPostProcess, _super);
  80834. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80835. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80836. if (blockCompilation === void 0) { blockCompilation = false; }
  80837. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80838. /**
  80839. * The luminance threshold, pixels below this value will be set to black.
  80840. */
  80841. _this.threshold = 0.9;
  80842. /** @hidden */
  80843. _this._exposure = 1;
  80844. /**
  80845. * Post process which has the input texture to be used when performing highlight extraction
  80846. * @hidden
  80847. */
  80848. _this._inputPostProcess = null;
  80849. _this.onApplyObservable.add(function (effect) {
  80850. if (_this._inputPostProcess) {
  80851. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  80852. }
  80853. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  80854. effect.setFloat('exposure', _this._exposure);
  80855. });
  80856. return _this;
  80857. }
  80858. return ExtractHighlightsPostProcess;
  80859. }(BABYLON.PostProcess));
  80860. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  80861. })(BABYLON || (BABYLON = {}));
  80862. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  80863. var BABYLON;
  80864. (function (BABYLON) {
  80865. /**
  80866. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  80867. */
  80868. var BloomEffect = /** @class */ (function (_super) {
  80869. __extends(BloomEffect, _super);
  80870. /**
  80871. * Creates a new instance of @see BloomEffect
  80872. * @param scene The scene the effect belongs to.
  80873. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  80874. * @param bloomKernel The size of the kernel to be used when applying the blur.
  80875. * @param bloomWeight The the strength of bloom.
  80876. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  80877. * @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)
  80878. */
  80879. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  80880. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  80881. if (blockCompilation === void 0) { blockCompilation = false; }
  80882. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  80883. return _this._effects;
  80884. }, true) || this;
  80885. _this.bloomScale = bloomScale;
  80886. /**
  80887. * @hidden Internal
  80888. */
  80889. _this._effects = [];
  80890. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80891. _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);
  80892. _this._blurX.alwaysForcePOT = true;
  80893. _this._blurX.autoClear = false;
  80894. _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);
  80895. _this._blurY.alwaysForcePOT = true;
  80896. _this._blurY.autoClear = false;
  80897. _this.kernel = bloomKernel;
  80898. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  80899. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80900. _this._merge.autoClear = false;
  80901. _this._effects.push(_this._merge);
  80902. return _this;
  80903. }
  80904. Object.defineProperty(BloomEffect.prototype, "threshold", {
  80905. /**
  80906. * The luminance threshold to find bright areas of the image to bloom.
  80907. */
  80908. get: function () {
  80909. return this._downscale.threshold;
  80910. },
  80911. set: function (value) {
  80912. this._downscale.threshold = value;
  80913. },
  80914. enumerable: true,
  80915. configurable: true
  80916. });
  80917. Object.defineProperty(BloomEffect.prototype, "weight", {
  80918. /**
  80919. * The strength of the bloom.
  80920. */
  80921. get: function () {
  80922. return this._merge.weight;
  80923. },
  80924. set: function (value) {
  80925. this._merge.weight = value;
  80926. },
  80927. enumerable: true,
  80928. configurable: true
  80929. });
  80930. Object.defineProperty(BloomEffect.prototype, "kernel", {
  80931. /**
  80932. * Specifies the size of the bloom blur kernel, relative to the final output size
  80933. */
  80934. get: function () {
  80935. return this._blurX.kernel / this.bloomScale;
  80936. },
  80937. set: function (value) {
  80938. this._blurX.kernel = value * this.bloomScale;
  80939. this._blurY.kernel = value * this.bloomScale;
  80940. },
  80941. enumerable: true,
  80942. configurable: true
  80943. });
  80944. /**
  80945. * Disposes each of the internal effects for a given camera.
  80946. * @param camera The camera to dispose the effect on.
  80947. */
  80948. BloomEffect.prototype.disposeEffects = function (camera) {
  80949. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80950. this._effects[effectIndex].dispose(camera);
  80951. }
  80952. };
  80953. /**
  80954. * @hidden Internal
  80955. */
  80956. BloomEffect.prototype._updateEffects = function () {
  80957. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80958. this._effects[effectIndex].updateEffect();
  80959. }
  80960. };
  80961. /**
  80962. * Internal
  80963. * @returns if all the contained post processes are ready.
  80964. * @hidden
  80965. */
  80966. BloomEffect.prototype._isReady = function () {
  80967. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80968. if (!this._effects[effectIndex].isReady()) {
  80969. return false;
  80970. }
  80971. }
  80972. return true;
  80973. };
  80974. return BloomEffect;
  80975. }(BABYLON.PostProcessRenderEffect));
  80976. BABYLON.BloomEffect = BloomEffect;
  80977. })(BABYLON || (BABYLON = {}));
  80978. //# sourceMappingURL=babylon.bloomEffect.js.map
  80979. var BABYLON;
  80980. (function (BABYLON) {
  80981. /**
  80982. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  80983. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  80984. */
  80985. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  80986. __extends(DefaultRenderingPipeline, _super);
  80987. /**
  80988. * @constructor
  80989. * @param {string} name - The rendering pipeline name (default: "")
  80990. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  80991. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  80992. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  80993. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  80994. */
  80995. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  80996. if (name === void 0) { name = ""; }
  80997. if (hdr === void 0) { hdr = true; }
  80998. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  80999. if (automaticBuild === void 0) { automaticBuild = true; }
  81000. var _this = _super.call(this, scene.getEngine(), name) || this;
  81001. _this._camerasToBeAttached = [];
  81002. /**
  81003. * ID of the sharpen post process,
  81004. */
  81005. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  81006. /**
  81007. * ID of the image processing post process;
  81008. */
  81009. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  81010. /**
  81011. * ID of the Fast Approximate Anti-Aliasing post process;
  81012. */
  81013. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  81014. /**
  81015. * ID of the chromatic aberration post process,
  81016. */
  81017. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  81018. /**
  81019. * ID of the grain post process
  81020. */
  81021. _this.GrainPostProcessId = "GrainPostProcessEffect";
  81022. /**
  81023. * Glow post process which adds a glow to emmisive areas of the image
  81024. */
  81025. _this._glowLayer = null;
  81026. /**
  81027. * Animations which can be used to tweak settings over a period of time
  81028. */
  81029. _this.animations = [];
  81030. _this._imageProcessingConfigurationObserver = null;
  81031. // Values
  81032. _this._sharpenEnabled = false;
  81033. _this._bloomEnabled = false;
  81034. _this._depthOfFieldEnabled = false;
  81035. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  81036. _this._fxaaEnabled = false;
  81037. _this._imageProcessingEnabled = true;
  81038. _this._bloomScale = 0.5;
  81039. _this._chromaticAberrationEnabled = false;
  81040. _this._grainEnabled = false;
  81041. _this._buildAllowed = true;
  81042. _this._resizeObserver = null;
  81043. _this._hardwareScaleLevel = 1.0;
  81044. _this._bloomKernel = 64;
  81045. /**
  81046. * Specifies the weight of the bloom in the final rendering
  81047. */
  81048. _this._bloomWeight = 0.15;
  81049. /**
  81050. * Specifies the luma threshold for the area that will be blurred by the bloom
  81051. */
  81052. _this._bloomThreshold = 0.9;
  81053. _this._samples = 1;
  81054. _this._hasCleared = false;
  81055. _this._prevPostProcess = null;
  81056. _this._prevPrevPostProcess = null;
  81057. _this._depthOfFieldSceneObserver = null;
  81058. _this._cameras = cameras || scene.cameras;
  81059. _this._cameras = _this._cameras.slice();
  81060. _this._camerasToBeAttached = _this._cameras.slice();
  81061. _this._buildAllowed = automaticBuild;
  81062. // Initialize
  81063. _this._scene = scene;
  81064. var caps = _this._scene.getEngine().getCaps();
  81065. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  81066. // Misc
  81067. if (_this._hdr) {
  81068. if (caps.textureHalfFloatRender) {
  81069. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81070. }
  81071. else if (caps.textureFloatRender) {
  81072. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81073. }
  81074. }
  81075. else {
  81076. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81077. }
  81078. // Attach
  81079. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81080. var engine = _this._scene.getEngine();
  81081. // Create post processes before hand so they can be modified before enabled.
  81082. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  81083. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81084. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  81085. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  81086. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  81087. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81088. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  81089. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81090. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  81091. _this._resizeObserver = engine.onResizeObservable.add(function () {
  81092. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  81093. _this.bloomKernel = _this.bloomKernel;
  81094. });
  81095. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  81096. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  81097. });
  81098. _this._buildPipeline();
  81099. return _this;
  81100. }
  81101. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  81102. get: function () {
  81103. return this._sharpenEnabled;
  81104. },
  81105. /**
  81106. * Enable or disable the sharpen process from the pipeline
  81107. */
  81108. set: function (enabled) {
  81109. if (this._sharpenEnabled === enabled) {
  81110. return;
  81111. }
  81112. this._sharpenEnabled = enabled;
  81113. this._buildPipeline();
  81114. },
  81115. enumerable: true,
  81116. configurable: true
  81117. });
  81118. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  81119. /**
  81120. * Specifies the size of the bloom blur kernel, relative to the final output size
  81121. */
  81122. get: function () {
  81123. return this._bloomKernel;
  81124. },
  81125. set: function (value) {
  81126. this._bloomKernel = value;
  81127. this.bloom.kernel = value / this._hardwareScaleLevel;
  81128. },
  81129. enumerable: true,
  81130. configurable: true
  81131. });
  81132. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  81133. get: function () {
  81134. return this._bloomWeight;
  81135. },
  81136. /**
  81137. * The strength of the bloom.
  81138. */
  81139. set: function (value) {
  81140. if (this._bloomWeight === value) {
  81141. return;
  81142. }
  81143. this.bloom.weight = value;
  81144. this._bloomWeight = value;
  81145. },
  81146. enumerable: true,
  81147. configurable: true
  81148. });
  81149. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  81150. get: function () {
  81151. return this._bloomThreshold;
  81152. },
  81153. /**
  81154. * The strength of the bloom.
  81155. */
  81156. set: function (value) {
  81157. if (this._bloomThreshold === value) {
  81158. return;
  81159. }
  81160. this.bloom.threshold = value;
  81161. this._bloomThreshold = value;
  81162. },
  81163. enumerable: true,
  81164. configurable: true
  81165. });
  81166. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  81167. get: function () {
  81168. return this._bloomScale;
  81169. },
  81170. /**
  81171. * The scale of the bloom, lower value will provide better performance.
  81172. */
  81173. set: function (value) {
  81174. if (this._bloomScale === value) {
  81175. return;
  81176. }
  81177. this._bloomScale = value;
  81178. // recreate bloom and dispose old as this setting is not dynamic
  81179. this._rebuildBloom();
  81180. this._buildPipeline();
  81181. },
  81182. enumerable: true,
  81183. configurable: true
  81184. });
  81185. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  81186. get: function () {
  81187. return this._bloomEnabled;
  81188. },
  81189. /**
  81190. * Enable or disable the bloom from the pipeline
  81191. */
  81192. set: function (enabled) {
  81193. if (this._bloomEnabled === enabled) {
  81194. return;
  81195. }
  81196. this._bloomEnabled = enabled;
  81197. this._buildPipeline();
  81198. },
  81199. enumerable: true,
  81200. configurable: true
  81201. });
  81202. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  81203. // recreate bloom and dispose old as this setting is not dynamic
  81204. var oldBloom = this.bloom;
  81205. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  81206. this.bloom.threshold = oldBloom.threshold;
  81207. for (var i = 0; i < this._cameras.length; i++) {
  81208. oldBloom.disposeEffects(this._cameras[i]);
  81209. }
  81210. };
  81211. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  81212. /**
  81213. * If the depth of field is enabled.
  81214. */
  81215. get: function () {
  81216. return this._depthOfFieldEnabled;
  81217. },
  81218. set: function (enabled) {
  81219. if (this._depthOfFieldEnabled === enabled) {
  81220. return;
  81221. }
  81222. this._depthOfFieldEnabled = enabled;
  81223. this._buildPipeline();
  81224. },
  81225. enumerable: true,
  81226. configurable: true
  81227. });
  81228. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  81229. /**
  81230. * Blur level of the depth of field effect. (Higher blur will effect performance)
  81231. */
  81232. get: function () {
  81233. return this._depthOfFieldBlurLevel;
  81234. },
  81235. set: function (value) {
  81236. if (this._depthOfFieldBlurLevel === value) {
  81237. return;
  81238. }
  81239. this._depthOfFieldBlurLevel = value;
  81240. // recreate dof and dispose old as this setting is not dynamic
  81241. var oldDof = this.depthOfField;
  81242. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  81243. this.depthOfField.focalLength = oldDof.focalLength;
  81244. this.depthOfField.focusDistance = oldDof.focusDistance;
  81245. this.depthOfField.fStop = oldDof.fStop;
  81246. this.depthOfField.lensSize = oldDof.lensSize;
  81247. for (var i = 0; i < this._cameras.length; i++) {
  81248. oldDof.disposeEffects(this._cameras[i]);
  81249. }
  81250. this._buildPipeline();
  81251. },
  81252. enumerable: true,
  81253. configurable: true
  81254. });
  81255. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  81256. get: function () {
  81257. return this._fxaaEnabled;
  81258. },
  81259. /**
  81260. * If the anti aliasing is enabled.
  81261. */
  81262. set: function (enabled) {
  81263. if (this._fxaaEnabled === enabled) {
  81264. return;
  81265. }
  81266. this._fxaaEnabled = enabled;
  81267. this._buildPipeline();
  81268. },
  81269. enumerable: true,
  81270. configurable: true
  81271. });
  81272. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  81273. get: function () {
  81274. return this._samples;
  81275. },
  81276. /**
  81277. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  81278. */
  81279. set: function (sampleCount) {
  81280. if (this._samples === sampleCount) {
  81281. return;
  81282. }
  81283. this._samples = sampleCount;
  81284. this._buildPipeline();
  81285. },
  81286. enumerable: true,
  81287. configurable: true
  81288. });
  81289. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  81290. get: function () {
  81291. return this._imageProcessingEnabled;
  81292. },
  81293. /**
  81294. * If image processing is enabled.
  81295. */
  81296. set: function (enabled) {
  81297. if (this._imageProcessingEnabled === enabled) {
  81298. return;
  81299. }
  81300. this._imageProcessingEnabled = enabled;
  81301. this._buildPipeline();
  81302. },
  81303. enumerable: true,
  81304. configurable: true
  81305. });
  81306. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  81307. get: function () {
  81308. return this._glowLayer == null;
  81309. },
  81310. /**
  81311. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  81312. */
  81313. set: function (enabled) {
  81314. if (enabled && !this._glowLayer) {
  81315. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  81316. }
  81317. else if (!enabled && this._glowLayer) {
  81318. this._glowLayer.dispose();
  81319. this._glowLayer = null;
  81320. }
  81321. },
  81322. enumerable: true,
  81323. configurable: true
  81324. });
  81325. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  81326. get: function () {
  81327. return this._chromaticAberrationEnabled;
  81328. },
  81329. /**
  81330. * Enable or disable the chromaticAberration process from the pipeline
  81331. */
  81332. set: function (enabled) {
  81333. if (this._chromaticAberrationEnabled === enabled) {
  81334. return;
  81335. }
  81336. this._chromaticAberrationEnabled = enabled;
  81337. this._buildPipeline();
  81338. },
  81339. enumerable: true,
  81340. configurable: true
  81341. });
  81342. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  81343. get: function () {
  81344. return this._grainEnabled;
  81345. },
  81346. /**
  81347. * Enable or disable the grain process from the pipeline
  81348. */
  81349. set: function (enabled) {
  81350. if (this._grainEnabled === enabled) {
  81351. return;
  81352. }
  81353. this._grainEnabled = enabled;
  81354. this._buildPipeline();
  81355. },
  81356. enumerable: true,
  81357. configurable: true
  81358. });
  81359. /**
  81360. * Force the compilation of the entire pipeline.
  81361. */
  81362. DefaultRenderingPipeline.prototype.prepare = function () {
  81363. var previousState = this._buildAllowed;
  81364. this._buildAllowed = true;
  81365. this._buildPipeline();
  81366. this._buildAllowed = previousState;
  81367. };
  81368. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  81369. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  81370. if (this._hasCleared) {
  81371. postProcess.autoClear = false;
  81372. }
  81373. else {
  81374. postProcess.autoClear = true;
  81375. this._scene.autoClear = false;
  81376. this._hasCleared = true;
  81377. }
  81378. if (!skipTextureSharing) {
  81379. if (this._prevPrevPostProcess) {
  81380. postProcess.shareOutputWith(this._prevPrevPostProcess);
  81381. }
  81382. else {
  81383. postProcess.useOwnOutput();
  81384. }
  81385. if (this._prevPostProcess) {
  81386. this._prevPrevPostProcess = this._prevPostProcess;
  81387. }
  81388. this._prevPostProcess = postProcess;
  81389. }
  81390. };
  81391. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  81392. var _this = this;
  81393. if (!this._buildAllowed) {
  81394. return;
  81395. }
  81396. this._scene.autoClear = true;
  81397. var engine = this._scene.getEngine();
  81398. this._disposePostProcesses();
  81399. if (this._cameras !== null) {
  81400. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81401. // get back cameras to be used to reattach pipeline
  81402. this._cameras = this._camerasToBeAttached.slice();
  81403. }
  81404. this._reset();
  81405. this._prevPostProcess = null;
  81406. this._prevPrevPostProcess = null;
  81407. this._hasCleared = false;
  81408. if (this.depthOfFieldEnabled) {
  81409. // Multi camera suport
  81410. if (this._cameras.length > 1) {
  81411. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  81412. var camera = _a[_i];
  81413. var depthRenderer = this._scene.enableDepthRenderer(camera);
  81414. depthRenderer.useOnlyInActiveCamera = true;
  81415. }
  81416. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  81417. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  81418. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  81419. }
  81420. });
  81421. }
  81422. else {
  81423. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81424. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  81425. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  81426. }
  81427. if (!this.depthOfField._isReady()) {
  81428. this.depthOfField._updateEffects();
  81429. }
  81430. this.addEffect(this.depthOfField);
  81431. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  81432. }
  81433. else {
  81434. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81435. }
  81436. if (this.bloomEnabled) {
  81437. if (!this.bloom._isReady()) {
  81438. this.bloom._updateEffects();
  81439. }
  81440. this.addEffect(this.bloom);
  81441. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  81442. }
  81443. if (this._imageProcessingEnabled) {
  81444. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  81445. if (this._hdr) {
  81446. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  81447. this._setAutoClearAndTextureSharing(this.imageProcessing);
  81448. }
  81449. else {
  81450. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  81451. }
  81452. }
  81453. if (this.sharpenEnabled) {
  81454. if (!this.sharpen.isReady()) {
  81455. this.sharpen.updateEffect();
  81456. }
  81457. this.addEffect(this._sharpenEffect);
  81458. this._setAutoClearAndTextureSharing(this.sharpen);
  81459. }
  81460. if (this.grainEnabled) {
  81461. if (!this.grain.isReady()) {
  81462. this.grain.updateEffect();
  81463. }
  81464. this.addEffect(this._grainEffect);
  81465. this._setAutoClearAndTextureSharing(this.grain);
  81466. }
  81467. if (this.chromaticAberrationEnabled) {
  81468. if (!this.chromaticAberration.isReady()) {
  81469. this.chromaticAberration.updateEffect();
  81470. }
  81471. this.addEffect(this._chromaticAberrationEffect);
  81472. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  81473. }
  81474. if (this.fxaaEnabled) {
  81475. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  81476. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  81477. this._setAutoClearAndTextureSharing(this.fxaa, true);
  81478. }
  81479. if (this._cameras !== null) {
  81480. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  81481. }
  81482. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  81483. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  81484. }
  81485. };
  81486. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  81487. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  81488. for (var i = 0; i < this._cameras.length; i++) {
  81489. var camera = this._cameras[i];
  81490. if (this.imageProcessing) {
  81491. this.imageProcessing.dispose(camera);
  81492. }
  81493. if (this.fxaa) {
  81494. this.fxaa.dispose(camera);
  81495. }
  81496. // These are created in the constructor and should not be disposed on every pipeline change
  81497. if (disposeNonRecreated) {
  81498. if (this.sharpen) {
  81499. this.sharpen.dispose(camera);
  81500. }
  81501. if (this.depthOfField) {
  81502. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81503. this.depthOfField.disposeEffects(camera);
  81504. }
  81505. if (this.bloom) {
  81506. this.bloom.disposeEffects(camera);
  81507. }
  81508. if (this.chromaticAberration) {
  81509. this.chromaticAberration.dispose(camera);
  81510. }
  81511. if (this.grain) {
  81512. this.grain.dispose(camera);
  81513. }
  81514. if (this._glowLayer) {
  81515. this._glowLayer.dispose();
  81516. }
  81517. }
  81518. }
  81519. this.imageProcessing = null;
  81520. this.fxaa = null;
  81521. if (disposeNonRecreated) {
  81522. this.sharpen = null;
  81523. this._sharpenEffect = null;
  81524. this.depthOfField = null;
  81525. this.bloom = null;
  81526. this.chromaticAberration = null;
  81527. this._chromaticAberrationEffect = null;
  81528. this.grain = null;
  81529. this._grainEffect = null;
  81530. this._glowLayer = null;
  81531. }
  81532. };
  81533. /**
  81534. * Adds a camera to the pipeline
  81535. * @param camera the camera to be added
  81536. */
  81537. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  81538. this._camerasToBeAttached.push(camera);
  81539. this._buildPipeline();
  81540. };
  81541. /**
  81542. * Removes a camera from the pipeline
  81543. * @param camera the camera to remove
  81544. */
  81545. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  81546. var index = this._camerasToBeAttached.indexOf(camera);
  81547. this._camerasToBeAttached.splice(index, 1);
  81548. this._buildPipeline();
  81549. };
  81550. /**
  81551. * Dispose of the pipeline and stop all post processes
  81552. */
  81553. DefaultRenderingPipeline.prototype.dispose = function () {
  81554. this._disposePostProcesses(true);
  81555. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81556. this._scene.autoClear = true;
  81557. if (this._resizeObserver) {
  81558. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  81559. this._resizeObserver = null;
  81560. }
  81561. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  81562. _super.prototype.dispose.call(this);
  81563. };
  81564. /**
  81565. * Serialize the rendering pipeline (Used when exporting)
  81566. * @returns the serialized object
  81567. */
  81568. DefaultRenderingPipeline.prototype.serialize = function () {
  81569. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81570. serializationObject.customType = "DefaultRenderingPipeline";
  81571. return serializationObject;
  81572. };
  81573. /**
  81574. * Parse the serialized pipeline
  81575. * @param source Source pipeline.
  81576. * @param scene The scene to load the pipeline to.
  81577. * @param rootUrl The URL of the serialized pipeline.
  81578. * @returns An instantiated pipeline from the serialized object.
  81579. */
  81580. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  81581. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  81582. };
  81583. __decorate([
  81584. BABYLON.serialize()
  81585. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  81586. __decorate([
  81587. BABYLON.serialize()
  81588. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  81589. __decorate([
  81590. BABYLON.serialize()
  81591. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  81592. __decorate([
  81593. BABYLON.serialize()
  81594. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  81595. __decorate([
  81596. BABYLON.serialize()
  81597. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  81598. __decorate([
  81599. BABYLON.serialize()
  81600. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  81601. __decorate([
  81602. BABYLON.serialize()
  81603. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  81604. __decorate([
  81605. BABYLON.serialize()
  81606. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  81607. __decorate([
  81608. BABYLON.serialize()
  81609. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  81610. __decorate([
  81611. BABYLON.serialize()
  81612. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  81613. __decorate([
  81614. BABYLON.serialize()
  81615. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  81616. __decorate([
  81617. BABYLON.serialize()
  81618. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  81619. __decorate([
  81620. BABYLON.serialize()
  81621. ], DefaultRenderingPipeline.prototype, "samples", null);
  81622. __decorate([
  81623. BABYLON.serialize()
  81624. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  81625. __decorate([
  81626. BABYLON.serialize()
  81627. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  81628. __decorate([
  81629. BABYLON.serialize()
  81630. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  81631. __decorate([
  81632. BABYLON.serialize()
  81633. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  81634. return DefaultRenderingPipeline;
  81635. }(BABYLON.PostProcessRenderPipeline));
  81636. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  81637. })(BABYLON || (BABYLON = {}));
  81638. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  81639. var BABYLON;
  81640. (function (BABYLON) {
  81641. /**
  81642. * @hidden
  81643. */
  81644. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  81645. __extends(ImageProcessingConfigurationDefines, _super);
  81646. function ImageProcessingConfigurationDefines() {
  81647. var _this = _super.call(this) || this;
  81648. _this.IMAGEPROCESSING = false;
  81649. _this.VIGNETTE = false;
  81650. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  81651. _this.VIGNETTEBLENDMODEOPAQUE = false;
  81652. _this.TONEMAPPING = false;
  81653. _this.TONEMAPPING_ACES = false;
  81654. _this.CONTRAST = false;
  81655. _this.COLORCURVES = false;
  81656. _this.COLORGRADING = false;
  81657. _this.COLORGRADING3D = false;
  81658. _this.SAMPLER3DGREENDEPTH = false;
  81659. _this.SAMPLER3DBGRMAP = false;
  81660. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  81661. _this.EXPOSURE = false;
  81662. _this.rebuild();
  81663. return _this;
  81664. }
  81665. return ImageProcessingConfigurationDefines;
  81666. }(BABYLON.MaterialDefines));
  81667. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  81668. /**
  81669. * This groups together the common properties used for image processing either in direct forward pass
  81670. * or through post processing effect depending on the use of the image processing pipeline in your scene
  81671. * or not.
  81672. */
  81673. var ImageProcessingConfiguration = /** @class */ (function () {
  81674. function ImageProcessingConfiguration() {
  81675. /**
  81676. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  81677. */
  81678. this.colorCurves = new BABYLON.ColorCurves();
  81679. this._colorCurvesEnabled = false;
  81680. this._colorGradingEnabled = false;
  81681. this._colorGradingWithGreenDepth = true;
  81682. this._colorGradingBGR = true;
  81683. /** @hidden */
  81684. this._exposure = 1.0;
  81685. this._toneMappingEnabled = false;
  81686. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  81687. this._contrast = 1.0;
  81688. /**
  81689. * Vignette stretch size.
  81690. */
  81691. this.vignetteStretch = 0;
  81692. /**
  81693. * Vignette centre X Offset.
  81694. */
  81695. this.vignetteCentreX = 0;
  81696. /**
  81697. * Vignette centre Y Offset.
  81698. */
  81699. this.vignetteCentreY = 0;
  81700. /**
  81701. * Vignette weight or intensity of the vignette effect.
  81702. */
  81703. this.vignetteWeight = 1.5;
  81704. /**
  81705. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  81706. * if vignetteEnabled is set to true.
  81707. */
  81708. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81709. /**
  81710. * Camera field of view used by the Vignette effect.
  81711. */
  81712. this.vignetteCameraFov = 0.5;
  81713. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  81714. this._vignetteEnabled = false;
  81715. this._applyByPostProcess = false;
  81716. this._isEnabled = true;
  81717. /**
  81718. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  81719. */
  81720. this.onUpdateParameters = new BABYLON.Observable();
  81721. }
  81722. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  81723. /**
  81724. * Gets wether the color curves effect is enabled.
  81725. */
  81726. get: function () {
  81727. return this._colorCurvesEnabled;
  81728. },
  81729. /**
  81730. * Sets wether the color curves effect is enabled.
  81731. */
  81732. set: function (value) {
  81733. if (this._colorCurvesEnabled === value) {
  81734. return;
  81735. }
  81736. this._colorCurvesEnabled = value;
  81737. this._updateParameters();
  81738. },
  81739. enumerable: true,
  81740. configurable: true
  81741. });
  81742. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  81743. /**
  81744. * Gets wether the color grading effect is enabled.
  81745. */
  81746. get: function () {
  81747. return this._colorGradingEnabled;
  81748. },
  81749. /**
  81750. * Sets wether the color grading effect is enabled.
  81751. */
  81752. set: function (value) {
  81753. if (this._colorGradingEnabled === value) {
  81754. return;
  81755. }
  81756. this._colorGradingEnabled = value;
  81757. this._updateParameters();
  81758. },
  81759. enumerable: true,
  81760. configurable: true
  81761. });
  81762. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  81763. /**
  81764. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  81765. */
  81766. get: function () {
  81767. return this._colorGradingWithGreenDepth;
  81768. },
  81769. /**
  81770. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  81771. */
  81772. set: function (value) {
  81773. if (this._colorGradingWithGreenDepth === value) {
  81774. return;
  81775. }
  81776. this._colorGradingWithGreenDepth = value;
  81777. this._updateParameters();
  81778. },
  81779. enumerable: true,
  81780. configurable: true
  81781. });
  81782. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  81783. /**
  81784. * Gets wether the color grading texture contains BGR values.
  81785. */
  81786. get: function () {
  81787. return this._colorGradingBGR;
  81788. },
  81789. /**
  81790. * Sets wether the color grading texture contains BGR values.
  81791. */
  81792. set: function (value) {
  81793. if (this._colorGradingBGR === value) {
  81794. return;
  81795. }
  81796. this._colorGradingBGR = value;
  81797. this._updateParameters();
  81798. },
  81799. enumerable: true,
  81800. configurable: true
  81801. });
  81802. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  81803. /**
  81804. * Gets the Exposure used in the effect.
  81805. */
  81806. get: function () {
  81807. return this._exposure;
  81808. },
  81809. /**
  81810. * Sets the Exposure used in the effect.
  81811. */
  81812. set: function (value) {
  81813. if (this._exposure === value) {
  81814. return;
  81815. }
  81816. this._exposure = value;
  81817. this._updateParameters();
  81818. },
  81819. enumerable: true,
  81820. configurable: true
  81821. });
  81822. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  81823. /**
  81824. * Gets wether the tone mapping effect is enabled.
  81825. */
  81826. get: function () {
  81827. return this._toneMappingEnabled;
  81828. },
  81829. /**
  81830. * Sets wether the tone mapping effect is enabled.
  81831. */
  81832. set: function (value) {
  81833. if (this._toneMappingEnabled === value) {
  81834. return;
  81835. }
  81836. this._toneMappingEnabled = value;
  81837. this._updateParameters();
  81838. },
  81839. enumerable: true,
  81840. configurable: true
  81841. });
  81842. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  81843. /**
  81844. * Gets the type of tone mapping effect.
  81845. */
  81846. get: function () {
  81847. return this._toneMappingType;
  81848. },
  81849. /**
  81850. * Sets the type of tone mapping effect used in BabylonJS.
  81851. */
  81852. set: function (value) {
  81853. if (this._toneMappingType === value) {
  81854. return;
  81855. }
  81856. this._toneMappingType = value;
  81857. this._updateParameters();
  81858. },
  81859. enumerable: true,
  81860. configurable: true
  81861. });
  81862. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  81863. /**
  81864. * Gets the contrast used in the effect.
  81865. */
  81866. get: function () {
  81867. return this._contrast;
  81868. },
  81869. /**
  81870. * Sets the contrast used in the effect.
  81871. */
  81872. set: function (value) {
  81873. if (this._contrast === value) {
  81874. return;
  81875. }
  81876. this._contrast = value;
  81877. this._updateParameters();
  81878. },
  81879. enumerable: true,
  81880. configurable: true
  81881. });
  81882. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  81883. /**
  81884. * Gets the vignette blend mode allowing different kind of effect.
  81885. */
  81886. get: function () {
  81887. return this._vignetteBlendMode;
  81888. },
  81889. /**
  81890. * Sets the vignette blend mode allowing different kind of effect.
  81891. */
  81892. set: function (value) {
  81893. if (this._vignetteBlendMode === value) {
  81894. return;
  81895. }
  81896. this._vignetteBlendMode = value;
  81897. this._updateParameters();
  81898. },
  81899. enumerable: true,
  81900. configurable: true
  81901. });
  81902. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  81903. /**
  81904. * Gets wether the vignette effect is enabled.
  81905. */
  81906. get: function () {
  81907. return this._vignetteEnabled;
  81908. },
  81909. /**
  81910. * Sets wether the vignette effect is enabled.
  81911. */
  81912. set: function (value) {
  81913. if (this._vignetteEnabled === value) {
  81914. return;
  81915. }
  81916. this._vignetteEnabled = value;
  81917. this._updateParameters();
  81918. },
  81919. enumerable: true,
  81920. configurable: true
  81921. });
  81922. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  81923. /**
  81924. * Gets wether the image processing is applied through a post process or not.
  81925. */
  81926. get: function () {
  81927. return this._applyByPostProcess;
  81928. },
  81929. /**
  81930. * Sets wether the image processing is applied through a post process or not.
  81931. */
  81932. set: function (value) {
  81933. if (this._applyByPostProcess === value) {
  81934. return;
  81935. }
  81936. this._applyByPostProcess = value;
  81937. this._updateParameters();
  81938. },
  81939. enumerable: true,
  81940. configurable: true
  81941. });
  81942. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  81943. /**
  81944. * Gets wether the image processing is enabled or not.
  81945. */
  81946. get: function () {
  81947. return this._isEnabled;
  81948. },
  81949. /**
  81950. * Sets wether the image processing is enabled or not.
  81951. */
  81952. set: function (value) {
  81953. if (this._isEnabled === value) {
  81954. return;
  81955. }
  81956. this._isEnabled = value;
  81957. this._updateParameters();
  81958. },
  81959. enumerable: true,
  81960. configurable: true
  81961. });
  81962. /**
  81963. * Method called each time the image processing information changes requires to recompile the effect.
  81964. */
  81965. ImageProcessingConfiguration.prototype._updateParameters = function () {
  81966. this.onUpdateParameters.notifyObservers(this);
  81967. };
  81968. ImageProcessingConfiguration.prototype.getClassName = function () {
  81969. return "ImageProcessingConfiguration";
  81970. };
  81971. /**
  81972. * Prepare the list of uniforms associated with the Image Processing effects.
  81973. * @param uniformsList The list of uniforms used in the effect
  81974. * @param defines the list of defines currently in use
  81975. */
  81976. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  81977. if (defines.EXPOSURE) {
  81978. uniforms.push("exposureLinear");
  81979. }
  81980. if (defines.CONTRAST) {
  81981. uniforms.push("contrast");
  81982. }
  81983. if (defines.COLORGRADING) {
  81984. uniforms.push("colorTransformSettings");
  81985. }
  81986. if (defines.VIGNETTE) {
  81987. uniforms.push("vInverseScreenSize");
  81988. uniforms.push("vignetteSettings1");
  81989. uniforms.push("vignetteSettings2");
  81990. }
  81991. if (defines.COLORCURVES) {
  81992. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  81993. }
  81994. };
  81995. /**
  81996. * Prepare the list of samplers associated with the Image Processing effects.
  81997. * @param uniformsList The list of uniforms used in the effect
  81998. * @param defines the list of defines currently in use
  81999. */
  82000. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  82001. if (defines.COLORGRADING) {
  82002. samplersList.push("txColorTransform");
  82003. }
  82004. };
  82005. /**
  82006. * Prepare the list of defines associated to the shader.
  82007. * @param defines the list of defines to complete
  82008. */
  82009. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  82010. if (forPostProcess === void 0) { forPostProcess = false; }
  82011. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  82012. defines.VIGNETTE = false;
  82013. defines.TONEMAPPING = false;
  82014. defines.TONEMAPPING_ACES = false;
  82015. defines.CONTRAST = false;
  82016. defines.EXPOSURE = false;
  82017. defines.COLORCURVES = false;
  82018. defines.COLORGRADING = false;
  82019. defines.COLORGRADING3D = false;
  82020. defines.IMAGEPROCESSING = false;
  82021. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  82022. return;
  82023. }
  82024. defines.VIGNETTE = this.vignetteEnabled;
  82025. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  82026. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  82027. defines.TONEMAPPING = this.toneMappingEnabled;
  82028. switch (this._toneMappingType) {
  82029. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  82030. defines.TONEMAPPING_ACES = true;
  82031. break;
  82032. }
  82033. defines.CONTRAST = (this.contrast !== 1.0);
  82034. defines.EXPOSURE = (this.exposure !== 1.0);
  82035. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  82036. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  82037. if (defines.COLORGRADING) {
  82038. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  82039. }
  82040. else {
  82041. defines.COLORGRADING3D = false;
  82042. }
  82043. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  82044. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  82045. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  82046. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  82047. };
  82048. /**
  82049. * Returns true if all the image processing information are ready.
  82050. */
  82051. ImageProcessingConfiguration.prototype.isReady = function () {
  82052. // Color Grading texure can not be none blocking.
  82053. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  82054. };
  82055. /**
  82056. * Binds the image processing to the shader.
  82057. * @param effect The effect to bind to
  82058. */
  82059. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  82060. if (aspectRatio === void 0) { aspectRatio = 1; }
  82061. // Color Curves
  82062. if (this._colorCurvesEnabled && this.colorCurves) {
  82063. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  82064. }
  82065. // Vignette
  82066. if (this._vignetteEnabled) {
  82067. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  82068. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  82069. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  82070. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  82071. var vignetteScaleX = vignetteScaleY * aspectRatio;
  82072. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  82073. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  82074. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  82075. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  82076. var vignettePower = -2.0 * this.vignetteWeight;
  82077. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  82078. }
  82079. // Exposure
  82080. effect.setFloat("exposureLinear", this.exposure);
  82081. // Contrast
  82082. effect.setFloat("contrast", this.contrast);
  82083. // Color transform settings
  82084. if (this.colorGradingTexture) {
  82085. effect.setTexture("txColorTransform", this.colorGradingTexture);
  82086. var textureSize = this.colorGradingTexture.getSize().height;
  82087. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  82088. 0.5 / textureSize, // textureOffset
  82089. textureSize, // textureSize
  82090. this.colorGradingTexture.level // weight
  82091. );
  82092. }
  82093. };
  82094. /**
  82095. * Clones the current image processing instance.
  82096. * @return The cloned image processing
  82097. */
  82098. ImageProcessingConfiguration.prototype.clone = function () {
  82099. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  82100. };
  82101. /**
  82102. * Serializes the current image processing instance to a json representation.
  82103. * @return a JSON representation
  82104. */
  82105. ImageProcessingConfiguration.prototype.serialize = function () {
  82106. return BABYLON.SerializationHelper.Serialize(this);
  82107. };
  82108. /**
  82109. * Parses the image processing from a json representation.
  82110. * @param source the JSON source to parse
  82111. * @return The parsed image processing
  82112. */
  82113. ImageProcessingConfiguration.Parse = function (source) {
  82114. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  82115. };
  82116. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  82117. /**
  82118. * Used to apply the vignette as a mix with the pixel color.
  82119. */
  82120. get: function () {
  82121. return this._VIGNETTEMODE_MULTIPLY;
  82122. },
  82123. enumerable: true,
  82124. configurable: true
  82125. });
  82126. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  82127. /**
  82128. * Used to apply the vignette as a replacement of the pixel color.
  82129. */
  82130. get: function () {
  82131. return this._VIGNETTEMODE_OPAQUE;
  82132. },
  82133. enumerable: true,
  82134. configurable: true
  82135. });
  82136. /**
  82137. * Default tone mapping applied in BabylonJS.
  82138. */
  82139. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  82140. /**
  82141. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  82142. * to other engines rendering to increase portability.
  82143. */
  82144. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  82145. // Static constants associated to the image processing.
  82146. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  82147. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  82148. __decorate([
  82149. BABYLON.serializeAsColorCurves()
  82150. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  82151. __decorate([
  82152. BABYLON.serialize()
  82153. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  82154. __decorate([
  82155. BABYLON.serializeAsTexture()
  82156. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  82157. __decorate([
  82158. BABYLON.serialize()
  82159. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  82160. __decorate([
  82161. BABYLON.serialize()
  82162. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  82163. __decorate([
  82164. BABYLON.serialize()
  82165. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  82166. __decorate([
  82167. BABYLON.serialize()
  82168. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  82169. __decorate([
  82170. BABYLON.serialize()
  82171. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  82172. __decorate([
  82173. BABYLON.serialize()
  82174. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  82175. __decorate([
  82176. BABYLON.serialize()
  82177. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  82178. __decorate([
  82179. BABYLON.serialize()
  82180. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  82181. __decorate([
  82182. BABYLON.serialize()
  82183. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  82184. __decorate([
  82185. BABYLON.serialize()
  82186. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  82187. __decorate([
  82188. BABYLON.serialize()
  82189. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  82190. __decorate([
  82191. BABYLON.serializeAsColor4()
  82192. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  82193. __decorate([
  82194. BABYLON.serialize()
  82195. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  82196. __decorate([
  82197. BABYLON.serialize()
  82198. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  82199. __decorate([
  82200. BABYLON.serialize()
  82201. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  82202. __decorate([
  82203. BABYLON.serialize()
  82204. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  82205. __decorate([
  82206. BABYLON.serialize()
  82207. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  82208. return ImageProcessingConfiguration;
  82209. }());
  82210. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  82211. })(BABYLON || (BABYLON = {}));
  82212. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  82213. var BABYLON;
  82214. (function (BABYLON) {
  82215. /**
  82216. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  82217. * It can help converting any input color in a desired output one. This can then be used to create effects
  82218. * from sepia, black and white to sixties or futuristic rendering...
  82219. *
  82220. * The only supported format is currently 3dl.
  82221. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  82222. */
  82223. var ColorGradingTexture = /** @class */ (function (_super) {
  82224. __extends(ColorGradingTexture, _super);
  82225. /**
  82226. * Instantiates a ColorGradingTexture from the following parameters.
  82227. *
  82228. * @param url The location of the color gradind data (currently only supporting 3dl)
  82229. * @param scene The scene the texture will be used in
  82230. */
  82231. function ColorGradingTexture(url, scene) {
  82232. var _this = _super.call(this, scene) || this;
  82233. if (!url) {
  82234. return _this;
  82235. }
  82236. _this._engine = scene.getEngine();
  82237. _this._textureMatrix = BABYLON.Matrix.Identity();
  82238. _this.name = url;
  82239. _this.url = url;
  82240. _this.hasAlpha = false;
  82241. _this.isCube = false;
  82242. _this.is3D = _this._engine.webGLVersion > 1;
  82243. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82244. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82245. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82246. _this.anisotropicFilteringLevel = 1;
  82247. _this._texture = _this._getFromCache(url, true);
  82248. if (!_this._texture) {
  82249. if (!scene.useDelayedTextureLoading) {
  82250. _this.loadTexture();
  82251. }
  82252. else {
  82253. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82254. }
  82255. }
  82256. return _this;
  82257. }
  82258. /**
  82259. * Returns the texture matrix used in most of the material.
  82260. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  82261. */
  82262. ColorGradingTexture.prototype.getTextureMatrix = function () {
  82263. return this._textureMatrix;
  82264. };
  82265. /**
  82266. * Occurs when the file being loaded is a .3dl LUT file.
  82267. */
  82268. ColorGradingTexture.prototype.load3dlTexture = function () {
  82269. var engine = this._engine;
  82270. var texture;
  82271. if (engine.webGLVersion === 1) {
  82272. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82273. }
  82274. else {
  82275. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82276. }
  82277. this._texture = texture;
  82278. var callback = function (text) {
  82279. if (typeof text !== "string") {
  82280. return;
  82281. }
  82282. var data = null;
  82283. var tempData = null;
  82284. var line;
  82285. var lines = text.split('\n');
  82286. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  82287. var maxColor = 0;
  82288. for (var i = 0; i < lines.length; i++) {
  82289. line = lines[i];
  82290. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  82291. continue;
  82292. if (line.indexOf('#') === 0)
  82293. continue;
  82294. var words = line.split(" ");
  82295. if (size === 0) {
  82296. // Number of space + one
  82297. size = words.length;
  82298. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  82299. tempData = new Float32Array(size * size * size * 4);
  82300. continue;
  82301. }
  82302. if (size != 0) {
  82303. var r = Math.max(parseInt(words[0]), 0);
  82304. var g = Math.max(parseInt(words[1]), 0);
  82305. var b = Math.max(parseInt(words[2]), 0);
  82306. maxColor = Math.max(r, maxColor);
  82307. maxColor = Math.max(g, maxColor);
  82308. maxColor = Math.max(b, maxColor);
  82309. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  82310. if (tempData) {
  82311. tempData[pixelStorageIndex + 0] = r;
  82312. tempData[pixelStorageIndex + 1] = g;
  82313. tempData[pixelStorageIndex + 2] = b;
  82314. }
  82315. pixelIndexSlice++;
  82316. if (pixelIndexSlice % size == 0) {
  82317. pixelIndexH++;
  82318. pixelIndexSlice = 0;
  82319. if (pixelIndexH % size == 0) {
  82320. pixelIndexW++;
  82321. pixelIndexH = 0;
  82322. }
  82323. }
  82324. }
  82325. }
  82326. if (tempData && data) {
  82327. for (var i = 0; i < tempData.length; i++) {
  82328. if (i > 0 && (i + 1) % 4 === 0) {
  82329. data[i] = 255;
  82330. }
  82331. else {
  82332. var value = tempData[i];
  82333. data[i] = (value / maxColor * 255);
  82334. }
  82335. }
  82336. }
  82337. if (texture.is3D) {
  82338. texture.updateSize(size, size, size);
  82339. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82340. }
  82341. else {
  82342. texture.updateSize(size * size, size);
  82343. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82344. }
  82345. };
  82346. var scene = this.getScene();
  82347. if (scene) {
  82348. scene._loadFile(this.url, callback);
  82349. }
  82350. else {
  82351. this._engine._loadFile(this.url, callback);
  82352. }
  82353. return this._texture;
  82354. };
  82355. /**
  82356. * Starts the loading process of the texture.
  82357. */
  82358. ColorGradingTexture.prototype.loadTexture = function () {
  82359. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  82360. this.load3dlTexture();
  82361. }
  82362. };
  82363. /**
  82364. * Clones the color gradind texture.
  82365. */
  82366. ColorGradingTexture.prototype.clone = function () {
  82367. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  82368. // Base texture
  82369. newTexture.level = this.level;
  82370. return newTexture;
  82371. };
  82372. /**
  82373. * Called during delayed load for textures.
  82374. */
  82375. ColorGradingTexture.prototype.delayLoad = function () {
  82376. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82377. return;
  82378. }
  82379. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82380. this._texture = this._getFromCache(this.url, true);
  82381. if (!this._texture) {
  82382. this.loadTexture();
  82383. }
  82384. };
  82385. /**
  82386. * Parses a color grading texture serialized by Babylon.
  82387. * @param parsedTexture The texture information being parsedTexture
  82388. * @param scene The scene to load the texture in
  82389. * @param rootUrl The root url of the data assets to load
  82390. * @return A color gradind texture
  82391. */
  82392. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82393. var texture = null;
  82394. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82395. texture = new ColorGradingTexture(parsedTexture.name, scene);
  82396. texture.name = parsedTexture.name;
  82397. texture.level = parsedTexture.level;
  82398. }
  82399. return texture;
  82400. };
  82401. /**
  82402. * Serializes the LUT texture to json format.
  82403. */
  82404. ColorGradingTexture.prototype.serialize = function () {
  82405. if (!this.name) {
  82406. return null;
  82407. }
  82408. var serializationObject = {};
  82409. serializationObject.name = this.name;
  82410. serializationObject.level = this.level;
  82411. serializationObject.customType = "BABYLON.ColorGradingTexture";
  82412. return serializationObject;
  82413. };
  82414. /**
  82415. * Empty line regex stored for GC.
  82416. */
  82417. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  82418. return ColorGradingTexture;
  82419. }(BABYLON.BaseTexture));
  82420. BABYLON.ColorGradingTexture = ColorGradingTexture;
  82421. })(BABYLON || (BABYLON = {}));
  82422. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  82423. var BABYLON;
  82424. (function (BABYLON) {
  82425. /**
  82426. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  82427. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  82428. * 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;
  82429. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  82430. */
  82431. var ColorCurves = /** @class */ (function () {
  82432. function ColorCurves() {
  82433. this._dirty = true;
  82434. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  82435. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  82436. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  82437. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  82438. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  82439. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  82440. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  82441. this._globalHue = 30;
  82442. this._globalDensity = 0;
  82443. this._globalSaturation = 0;
  82444. this._globalExposure = 0;
  82445. this._highlightsHue = 30;
  82446. this._highlightsDensity = 0;
  82447. this._highlightsSaturation = 0;
  82448. this._highlightsExposure = 0;
  82449. this._midtonesHue = 30;
  82450. this._midtonesDensity = 0;
  82451. this._midtonesSaturation = 0;
  82452. this._midtonesExposure = 0;
  82453. this._shadowsHue = 30;
  82454. this._shadowsDensity = 0;
  82455. this._shadowsSaturation = 0;
  82456. this._shadowsExposure = 0;
  82457. }
  82458. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  82459. /**
  82460. * Gets the global Hue value.
  82461. * 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).
  82462. */
  82463. get: function () {
  82464. return this._globalHue;
  82465. },
  82466. /**
  82467. * Sets the global Hue value.
  82468. * 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).
  82469. */
  82470. set: function (value) {
  82471. this._globalHue = value;
  82472. this._dirty = true;
  82473. },
  82474. enumerable: true,
  82475. configurable: true
  82476. });
  82477. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  82478. /**
  82479. * Gets the global Density value.
  82480. * 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.
  82481. * Values less than zero provide a filter of opposite hue.
  82482. */
  82483. get: function () {
  82484. return this._globalDensity;
  82485. },
  82486. /**
  82487. * Sets the global Density value.
  82488. * 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.
  82489. * Values less than zero provide a filter of opposite hue.
  82490. */
  82491. set: function (value) {
  82492. this._globalDensity = value;
  82493. this._dirty = true;
  82494. },
  82495. enumerable: true,
  82496. configurable: true
  82497. });
  82498. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  82499. /**
  82500. * Gets the global Saturation value.
  82501. * 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.
  82502. */
  82503. get: function () {
  82504. return this._globalSaturation;
  82505. },
  82506. /**
  82507. * Sets the global Saturation value.
  82508. * 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.
  82509. */
  82510. set: function (value) {
  82511. this._globalSaturation = value;
  82512. this._dirty = true;
  82513. },
  82514. enumerable: true,
  82515. configurable: true
  82516. });
  82517. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  82518. /**
  82519. * Gets the global Exposure value.
  82520. * 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.
  82521. */
  82522. get: function () {
  82523. return this._globalExposure;
  82524. },
  82525. /**
  82526. * Sets the global Exposure value.
  82527. * 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.
  82528. */
  82529. set: function (value) {
  82530. this._globalExposure = value;
  82531. this._dirty = true;
  82532. },
  82533. enumerable: true,
  82534. configurable: true
  82535. });
  82536. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  82537. /**
  82538. * Gets the highlights Hue value.
  82539. * 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).
  82540. */
  82541. get: function () {
  82542. return this._highlightsHue;
  82543. },
  82544. /**
  82545. * Sets the highlights Hue value.
  82546. * 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).
  82547. */
  82548. set: function (value) {
  82549. this._highlightsHue = value;
  82550. this._dirty = true;
  82551. },
  82552. enumerable: true,
  82553. configurable: true
  82554. });
  82555. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  82556. /**
  82557. * Gets the highlights Density value.
  82558. * 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.
  82559. * Values less than zero provide a filter of opposite hue.
  82560. */
  82561. get: function () {
  82562. return this._highlightsDensity;
  82563. },
  82564. /**
  82565. * Sets the highlights Density value.
  82566. * 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.
  82567. * Values less than zero provide a filter of opposite hue.
  82568. */
  82569. set: function (value) {
  82570. this._highlightsDensity = value;
  82571. this._dirty = true;
  82572. },
  82573. enumerable: true,
  82574. configurable: true
  82575. });
  82576. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  82577. /**
  82578. * Gets the highlights Saturation value.
  82579. * 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.
  82580. */
  82581. get: function () {
  82582. return this._highlightsSaturation;
  82583. },
  82584. /**
  82585. * Sets the highlights Saturation value.
  82586. * 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.
  82587. */
  82588. set: function (value) {
  82589. this._highlightsSaturation = value;
  82590. this._dirty = true;
  82591. },
  82592. enumerable: true,
  82593. configurable: true
  82594. });
  82595. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  82596. /**
  82597. * Gets the highlights Exposure value.
  82598. * 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.
  82599. */
  82600. get: function () {
  82601. return this._highlightsExposure;
  82602. },
  82603. /**
  82604. * Sets the highlights Exposure value.
  82605. * 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.
  82606. */
  82607. set: function (value) {
  82608. this._highlightsExposure = value;
  82609. this._dirty = true;
  82610. },
  82611. enumerable: true,
  82612. configurable: true
  82613. });
  82614. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  82615. /**
  82616. * Gets the midtones Hue value.
  82617. * 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).
  82618. */
  82619. get: function () {
  82620. return this._midtonesHue;
  82621. },
  82622. /**
  82623. * Sets the midtones Hue value.
  82624. * 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).
  82625. */
  82626. set: function (value) {
  82627. this._midtonesHue = value;
  82628. this._dirty = true;
  82629. },
  82630. enumerable: true,
  82631. configurable: true
  82632. });
  82633. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  82634. /**
  82635. * Gets the midtones Density value.
  82636. * 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.
  82637. * Values less than zero provide a filter of opposite hue.
  82638. */
  82639. get: function () {
  82640. return this._midtonesDensity;
  82641. },
  82642. /**
  82643. * Sets the midtones Density value.
  82644. * 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.
  82645. * Values less than zero provide a filter of opposite hue.
  82646. */
  82647. set: function (value) {
  82648. this._midtonesDensity = value;
  82649. this._dirty = true;
  82650. },
  82651. enumerable: true,
  82652. configurable: true
  82653. });
  82654. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  82655. /**
  82656. * Gets the midtones Saturation value.
  82657. * 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.
  82658. */
  82659. get: function () {
  82660. return this._midtonesSaturation;
  82661. },
  82662. /**
  82663. * Sets the midtones Saturation value.
  82664. * 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.
  82665. */
  82666. set: function (value) {
  82667. this._midtonesSaturation = value;
  82668. this._dirty = true;
  82669. },
  82670. enumerable: true,
  82671. configurable: true
  82672. });
  82673. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  82674. /**
  82675. * Gets the midtones Exposure value.
  82676. * 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.
  82677. */
  82678. get: function () {
  82679. return this._midtonesExposure;
  82680. },
  82681. /**
  82682. * Sets the midtones Exposure value.
  82683. * 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.
  82684. */
  82685. set: function (value) {
  82686. this._midtonesExposure = value;
  82687. this._dirty = true;
  82688. },
  82689. enumerable: true,
  82690. configurable: true
  82691. });
  82692. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  82693. /**
  82694. * Gets the shadows Hue value.
  82695. * 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).
  82696. */
  82697. get: function () {
  82698. return this._shadowsHue;
  82699. },
  82700. /**
  82701. * Sets the shadows Hue value.
  82702. * 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).
  82703. */
  82704. set: function (value) {
  82705. this._shadowsHue = value;
  82706. this._dirty = true;
  82707. },
  82708. enumerable: true,
  82709. configurable: true
  82710. });
  82711. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  82712. /**
  82713. * Gets the shadows Density value.
  82714. * 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.
  82715. * Values less than zero provide a filter of opposite hue.
  82716. */
  82717. get: function () {
  82718. return this._shadowsDensity;
  82719. },
  82720. /**
  82721. * Sets the shadows Density value.
  82722. * 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.
  82723. * Values less than zero provide a filter of opposite hue.
  82724. */
  82725. set: function (value) {
  82726. this._shadowsDensity = value;
  82727. this._dirty = true;
  82728. },
  82729. enumerable: true,
  82730. configurable: true
  82731. });
  82732. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  82733. /**
  82734. * Gets the shadows Saturation value.
  82735. * 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.
  82736. */
  82737. get: function () {
  82738. return this._shadowsSaturation;
  82739. },
  82740. /**
  82741. * Sets the shadows Saturation value.
  82742. * 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.
  82743. */
  82744. set: function (value) {
  82745. this._shadowsSaturation = value;
  82746. this._dirty = true;
  82747. },
  82748. enumerable: true,
  82749. configurable: true
  82750. });
  82751. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  82752. /**
  82753. * Gets the shadows Exposure value.
  82754. * 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.
  82755. */
  82756. get: function () {
  82757. return this._shadowsExposure;
  82758. },
  82759. /**
  82760. * Sets the shadows Exposure value.
  82761. * 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.
  82762. */
  82763. set: function (value) {
  82764. this._shadowsExposure = value;
  82765. this._dirty = true;
  82766. },
  82767. enumerable: true,
  82768. configurable: true
  82769. });
  82770. ColorCurves.prototype.getClassName = function () {
  82771. return "ColorCurves";
  82772. };
  82773. /**
  82774. * Binds the color curves to the shader.
  82775. * @param colorCurves The color curve to bind
  82776. * @param effect The effect to bind to
  82777. */
  82778. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  82779. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  82780. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  82781. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  82782. if (colorCurves._dirty) {
  82783. colorCurves._dirty = false;
  82784. // Fill in global info.
  82785. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  82786. // Compute highlights info.
  82787. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  82788. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  82789. // Compute midtones info.
  82790. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  82791. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  82792. // Compute shadows info.
  82793. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  82794. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  82795. // Compute deltas (neutral is midtones).
  82796. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  82797. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  82798. }
  82799. if (effect) {
  82800. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  82801. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  82802. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  82803. }
  82804. };
  82805. /**
  82806. * Prepare the list of uniforms associated with the ColorCurves effects.
  82807. * @param uniformsList The list of uniforms used in the effect
  82808. */
  82809. ColorCurves.PrepareUniforms = function (uniformsList) {
  82810. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  82811. };
  82812. /**
  82813. * Returns color grading data based on a hue, density, saturation and exposure value.
  82814. * @param filterHue The hue of the color filter.
  82815. * @param filterDensity The density of the color filter.
  82816. * @param saturation The saturation.
  82817. * @param exposure The exposure.
  82818. * @param result The result data container.
  82819. */
  82820. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  82821. if (hue == null) {
  82822. return;
  82823. }
  82824. hue = ColorCurves.clamp(hue, 0, 360);
  82825. density = ColorCurves.clamp(density, -100, 100);
  82826. saturation = ColorCurves.clamp(saturation, -100, 100);
  82827. exposure = ColorCurves.clamp(exposure, -100, 100);
  82828. // Remap the slider/config filter density with non-linear mapping and also scale by half
  82829. // so that the maximum filter density is only 50% control. This provides fine control
  82830. // for small values and reasonable range.
  82831. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  82832. density *= 0.5;
  82833. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  82834. if (density < 0) {
  82835. density *= -1;
  82836. hue = (hue + 180) % 360;
  82837. }
  82838. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  82839. result.scaleToRef(2, result);
  82840. result.a = 1 + 0.01 * saturation;
  82841. };
  82842. /**
  82843. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  82844. * @param value The input slider value in range [-100,100].
  82845. * @returns Adjusted value.
  82846. */
  82847. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  82848. value /= 100;
  82849. var x = Math.abs(value);
  82850. x = Math.pow(x, 2);
  82851. if (value < 0) {
  82852. x *= -1;
  82853. }
  82854. x *= 100;
  82855. return x;
  82856. };
  82857. /**
  82858. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  82859. * @param hue The hue (H) input.
  82860. * @param saturation The saturation (S) input.
  82861. * @param brightness The brightness (B) input.
  82862. * @result An RGBA color represented as Vector4.
  82863. */
  82864. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  82865. var h = ColorCurves.clamp(hue, 0, 360);
  82866. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  82867. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  82868. if (s === 0) {
  82869. result.r = v;
  82870. result.g = v;
  82871. result.b = v;
  82872. }
  82873. else {
  82874. // sector 0 to 5
  82875. h /= 60;
  82876. var i = Math.floor(h);
  82877. // fractional part of h
  82878. var f = h - i;
  82879. var p = v * (1 - s);
  82880. var q = v * (1 - s * f);
  82881. var t = v * (1 - s * (1 - f));
  82882. switch (i) {
  82883. case 0:
  82884. result.r = v;
  82885. result.g = t;
  82886. result.b = p;
  82887. break;
  82888. case 1:
  82889. result.r = q;
  82890. result.g = v;
  82891. result.b = p;
  82892. break;
  82893. case 2:
  82894. result.r = p;
  82895. result.g = v;
  82896. result.b = t;
  82897. break;
  82898. case 3:
  82899. result.r = p;
  82900. result.g = q;
  82901. result.b = v;
  82902. break;
  82903. case 4:
  82904. result.r = t;
  82905. result.g = p;
  82906. result.b = v;
  82907. break;
  82908. default: // case 5:
  82909. result.r = v;
  82910. result.g = p;
  82911. result.b = q;
  82912. break;
  82913. }
  82914. }
  82915. result.a = 1;
  82916. };
  82917. /**
  82918. * Returns a value clamped between min and max
  82919. * @param value The value to clamp
  82920. * @param min The minimum of value
  82921. * @param max The maximum of value
  82922. * @returns The clamped value.
  82923. */
  82924. ColorCurves.clamp = function (value, min, max) {
  82925. return Math.min(Math.max(value, min), max);
  82926. };
  82927. /**
  82928. * Clones the current color curve instance.
  82929. * @return The cloned curves
  82930. */
  82931. ColorCurves.prototype.clone = function () {
  82932. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  82933. };
  82934. /**
  82935. * Serializes the current color curve instance to a json representation.
  82936. * @return a JSON representation
  82937. */
  82938. ColorCurves.prototype.serialize = function () {
  82939. return BABYLON.SerializationHelper.Serialize(this);
  82940. };
  82941. /**
  82942. * Parses the color curve from a json representation.
  82943. * @param source the JSON source to parse
  82944. * @return The parsed curves
  82945. */
  82946. ColorCurves.Parse = function (source) {
  82947. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  82948. };
  82949. __decorate([
  82950. BABYLON.serialize()
  82951. ], ColorCurves.prototype, "_globalHue", void 0);
  82952. __decorate([
  82953. BABYLON.serialize()
  82954. ], ColorCurves.prototype, "_globalDensity", void 0);
  82955. __decorate([
  82956. BABYLON.serialize()
  82957. ], ColorCurves.prototype, "_globalSaturation", void 0);
  82958. __decorate([
  82959. BABYLON.serialize()
  82960. ], ColorCurves.prototype, "_globalExposure", void 0);
  82961. __decorate([
  82962. BABYLON.serialize()
  82963. ], ColorCurves.prototype, "_highlightsHue", void 0);
  82964. __decorate([
  82965. BABYLON.serialize()
  82966. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  82967. __decorate([
  82968. BABYLON.serialize()
  82969. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  82970. __decorate([
  82971. BABYLON.serialize()
  82972. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  82973. __decorate([
  82974. BABYLON.serialize()
  82975. ], ColorCurves.prototype, "_midtonesHue", void 0);
  82976. __decorate([
  82977. BABYLON.serialize()
  82978. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  82979. __decorate([
  82980. BABYLON.serialize()
  82981. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  82982. __decorate([
  82983. BABYLON.serialize()
  82984. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  82985. return ColorCurves;
  82986. }());
  82987. BABYLON.ColorCurves = ColorCurves;
  82988. })(BABYLON || (BABYLON = {}));
  82989. //# sourceMappingURL=babylon.colorCurves.js.map
  82990. var BABYLON;
  82991. (function (BABYLON) {
  82992. var RefractionPostProcess = /** @class */ (function (_super) {
  82993. __extends(RefractionPostProcess, _super);
  82994. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  82995. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  82996. _this.color = color;
  82997. _this.depth = depth;
  82998. _this.colorLevel = colorLevel;
  82999. _this._ownRefractionTexture = true;
  83000. _this.onActivateObservable.add(function (cam) {
  83001. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  83002. });
  83003. _this.onApplyObservable.add(function (effect) {
  83004. effect.setColor3("baseColor", _this.color);
  83005. effect.setFloat("depth", _this.depth);
  83006. effect.setFloat("colorLevel", _this.colorLevel);
  83007. effect.setTexture("refractionSampler", _this._refTexture);
  83008. });
  83009. return _this;
  83010. }
  83011. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  83012. /**
  83013. * Gets or sets the refraction texture
  83014. * Please note that you are responsible for disposing the texture if you set it manually
  83015. */
  83016. get: function () {
  83017. return this._refTexture;
  83018. },
  83019. set: function (value) {
  83020. if (this._refTexture && this._ownRefractionTexture) {
  83021. this._refTexture.dispose();
  83022. }
  83023. this._refTexture = value;
  83024. this._ownRefractionTexture = false;
  83025. },
  83026. enumerable: true,
  83027. configurable: true
  83028. });
  83029. // Methods
  83030. RefractionPostProcess.prototype.dispose = function (camera) {
  83031. if (this._refTexture && this._ownRefractionTexture) {
  83032. this._refTexture.dispose();
  83033. this._refTexture = null;
  83034. }
  83035. _super.prototype.dispose.call(this, camera);
  83036. };
  83037. return RefractionPostProcess;
  83038. }(BABYLON.PostProcess));
  83039. BABYLON.RefractionPostProcess = RefractionPostProcess;
  83040. })(BABYLON || (BABYLON = {}));
  83041. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  83042. var BABYLON;
  83043. (function (BABYLON) {
  83044. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  83045. __extends(BlackAndWhitePostProcess, _super);
  83046. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  83047. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  83048. _this.degree = 1;
  83049. _this.onApplyObservable.add(function (effect) {
  83050. effect.setFloat("degree", _this.degree);
  83051. });
  83052. return _this;
  83053. }
  83054. return BlackAndWhitePostProcess;
  83055. }(BABYLON.PostProcess));
  83056. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  83057. })(BABYLON || (BABYLON = {}));
  83058. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  83059. var BABYLON;
  83060. (function (BABYLON) {
  83061. /**
  83062. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  83063. * input texture to perform effects such as edge detection or sharpening
  83064. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  83065. */
  83066. var ConvolutionPostProcess = /** @class */ (function (_super) {
  83067. __extends(ConvolutionPostProcess, _super);
  83068. /**
  83069. * Creates a new instance ConvolutionPostProcess
  83070. * @param name The name of the effect.
  83071. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  83072. * @param options The required width/height ratio to downsize to before computing the render pass.
  83073. * @param camera The camera to apply the render pass to.
  83074. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83075. * @param engine The engine which the post process will be applied. (default: current engine)
  83076. * @param reusable If the post process can be reused on the same frame. (default: false)
  83077. * @param textureType Type of textures used when performing the post process. (default: 0)
  83078. */
  83079. function ConvolutionPostProcess(name,
  83080. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  83081. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  83082. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83083. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83084. _this.kernel = kernel;
  83085. _this.onApply = function (effect) {
  83086. effect.setFloat2("screenSize", _this.width, _this.height);
  83087. effect.setArray("kernel", _this.kernel);
  83088. };
  83089. return _this;
  83090. }
  83091. // Statics
  83092. /**
  83093. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83094. */
  83095. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  83096. /**
  83097. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83098. */
  83099. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  83100. /**
  83101. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83102. */
  83103. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  83104. /**
  83105. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83106. */
  83107. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  83108. /**
  83109. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83110. */
  83111. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  83112. /**
  83113. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83114. */
  83115. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  83116. return ConvolutionPostProcess;
  83117. }(BABYLON.PostProcess));
  83118. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  83119. })(BABYLON || (BABYLON = {}));
  83120. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  83121. var BABYLON;
  83122. (function (BABYLON) {
  83123. var FilterPostProcess = /** @class */ (function (_super) {
  83124. __extends(FilterPostProcess, _super);
  83125. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  83126. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  83127. _this.kernelMatrix = kernelMatrix;
  83128. _this.onApply = function (effect) {
  83129. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  83130. };
  83131. return _this;
  83132. }
  83133. return FilterPostProcess;
  83134. }(BABYLON.PostProcess));
  83135. BABYLON.FilterPostProcess = FilterPostProcess;
  83136. })(BABYLON || (BABYLON = {}));
  83137. //# sourceMappingURL=babylon.filterPostProcess.js.map
  83138. var BABYLON;
  83139. (function (BABYLON) {
  83140. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  83141. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  83142. __extends(VolumetricLightScatteringPostProcess, _super);
  83143. /**
  83144. * @constructor
  83145. * @param {string} name - The post-process name
  83146. * @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)
  83147. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  83148. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  83149. * @param {number} samples - The post-process quality, default 100
  83150. * @param {number} samplingMode - The post-process filtering mode
  83151. * @param {BABYLON.Engine} engine - The babylon engine
  83152. * @param {boolean} reusable - If the post-process is reusable
  83153. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  83154. */
  83155. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  83156. if (samples === void 0) { samples = 100; }
  83157. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83158. 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;
  83159. _this._screenCoordinates = BABYLON.Vector2.Zero();
  83160. /**
  83161. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  83162. */
  83163. _this.customMeshPosition = BABYLON.Vector3.Zero();
  83164. /**
  83165. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  83166. */
  83167. _this.useCustomMeshPosition = false;
  83168. /**
  83169. * If the post-process should inverse the light scattering direction
  83170. */
  83171. _this.invert = true;
  83172. /**
  83173. * Array containing the excluded meshes not rendered in the internal pass
  83174. */
  83175. _this.excludedMeshes = new Array();
  83176. /**
  83177. * Controls the overall intensity of the post-process
  83178. */
  83179. _this.exposure = 0.3;
  83180. /**
  83181. * Dissipates each sample's contribution in range [0, 1]
  83182. */
  83183. _this.decay = 0.96815;
  83184. /**
  83185. * Controls the overall intensity of each sample
  83186. */
  83187. _this.weight = 0.58767;
  83188. /**
  83189. * Controls the density of each sample
  83190. */
  83191. _this.density = 0.926;
  83192. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  83193. engine = scene.getEngine();
  83194. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  83195. // Configure mesh
  83196. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  83197. // Configure
  83198. _this._createPass(scene, ratio.passRatio || ratio);
  83199. _this.onActivate = function (camera) {
  83200. if (!_this.isSupported) {
  83201. _this.dispose(camera);
  83202. }
  83203. _this.onActivate = null;
  83204. };
  83205. _this.onApplyObservable.add(function (effect) {
  83206. _this._updateMeshScreenCoordinates(scene);
  83207. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  83208. effect.setFloat("exposure", _this.exposure);
  83209. effect.setFloat("decay", _this.decay);
  83210. effect.setFloat("weight", _this.weight);
  83211. effect.setFloat("density", _this.density);
  83212. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  83213. });
  83214. return _this;
  83215. }
  83216. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  83217. get: function () {
  83218. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83219. return false;
  83220. },
  83221. set: function (useDiffuseColor) {
  83222. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83223. },
  83224. enumerable: true,
  83225. configurable: true
  83226. });
  83227. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  83228. return "VolumetricLightScatteringPostProcess";
  83229. };
  83230. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  83231. var mesh = subMesh.getMesh();
  83232. // Render this.mesh as default
  83233. if (mesh === this.mesh && mesh.material) {
  83234. return mesh.material.isReady(mesh);
  83235. }
  83236. var defines = [];
  83237. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83238. var material = subMesh.getMaterial();
  83239. // Alpha test
  83240. if (material) {
  83241. if (material.needAlphaTesting()) {
  83242. defines.push("#define ALPHATEST");
  83243. }
  83244. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83245. attribs.push(BABYLON.VertexBuffer.UVKind);
  83246. defines.push("#define UV1");
  83247. }
  83248. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83249. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83250. defines.push("#define UV2");
  83251. }
  83252. }
  83253. // Bones
  83254. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83255. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83256. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83257. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83258. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  83259. }
  83260. else {
  83261. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83262. }
  83263. // Instances
  83264. if (useInstances) {
  83265. defines.push("#define INSTANCES");
  83266. attribs.push("world0");
  83267. attribs.push("world1");
  83268. attribs.push("world2");
  83269. attribs.push("world3");
  83270. }
  83271. // Get correct effect
  83272. var join = defines.join("\n");
  83273. if (this._cachedDefines !== join) {
  83274. this._cachedDefines = join;
  83275. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  83276. }
  83277. return this._volumetricLightScatteringPass.isReady();
  83278. };
  83279. /**
  83280. * Sets the new light position for light scattering effect
  83281. * @param {BABYLON.Vector3} The new custom light position
  83282. */
  83283. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  83284. this.customMeshPosition = position;
  83285. };
  83286. /**
  83287. * Returns the light position for light scattering effect
  83288. * @return {BABYLON.Vector3} The custom light position
  83289. */
  83290. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  83291. return this.customMeshPosition;
  83292. };
  83293. /**
  83294. * Disposes the internal assets and detaches the post-process from the camera
  83295. */
  83296. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  83297. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  83298. if (rttIndex !== -1) {
  83299. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  83300. }
  83301. this._volumetricLightScatteringRTT.dispose();
  83302. _super.prototype.dispose.call(this, camera);
  83303. };
  83304. /**
  83305. * Returns the render target texture used by the post-process
  83306. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  83307. */
  83308. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  83309. return this._volumetricLightScatteringRTT;
  83310. };
  83311. // Private methods
  83312. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  83313. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  83314. return true;
  83315. }
  83316. return false;
  83317. };
  83318. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  83319. var _this = this;
  83320. var engine = scene.getEngine();
  83321. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83322. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83323. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83324. this._volumetricLightScatteringRTT.renderList = null;
  83325. this._volumetricLightScatteringRTT.renderParticles = false;
  83326. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  83327. var camera = this.getCamera();
  83328. if (camera) {
  83329. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83330. }
  83331. else {
  83332. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83333. }
  83334. // Custom render function for submeshes
  83335. var renderSubMesh = function (subMesh) {
  83336. var mesh = subMesh.getRenderingMesh();
  83337. if (_this._meshExcluded(mesh)) {
  83338. return;
  83339. }
  83340. var material = subMesh.getMaterial();
  83341. if (!material) {
  83342. return;
  83343. }
  83344. var scene = mesh.getScene();
  83345. var engine = scene.getEngine();
  83346. // Culling
  83347. engine.setState(material.backFaceCulling);
  83348. // Managing instances
  83349. var batch = mesh._getInstancesRenderList(subMesh._id);
  83350. if (batch.mustReturn) {
  83351. return;
  83352. }
  83353. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83354. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  83355. var effect = _this._volumetricLightScatteringPass;
  83356. if (mesh === _this.mesh) {
  83357. if (subMesh.effect) {
  83358. effect = subMesh.effect;
  83359. }
  83360. else {
  83361. effect = material.getEffect();
  83362. }
  83363. }
  83364. engine.enableEffect(effect);
  83365. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  83366. if (mesh === _this.mesh) {
  83367. material.bind(mesh.getWorldMatrix(), mesh);
  83368. }
  83369. else {
  83370. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  83371. // Alpha test
  83372. if (material && material.needAlphaTesting()) {
  83373. var alphaTexture = material.getAlphaTestTexture();
  83374. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  83375. if (alphaTexture) {
  83376. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83377. }
  83378. }
  83379. // Bones
  83380. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83381. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83382. }
  83383. }
  83384. // Draw
  83385. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  83386. }
  83387. };
  83388. // Render target texture callbacks
  83389. var savedSceneClearColor;
  83390. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  83391. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  83392. savedSceneClearColor = scene.clearColor;
  83393. scene.clearColor = sceneClearColor;
  83394. });
  83395. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  83396. scene.clearColor = savedSceneClearColor;
  83397. });
  83398. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83399. var engine = scene.getEngine();
  83400. var index;
  83401. if (depthOnlySubMeshes.length) {
  83402. engine.setColorWrite(false);
  83403. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83404. renderSubMesh(depthOnlySubMeshes.data[index]);
  83405. }
  83406. engine.setColorWrite(true);
  83407. }
  83408. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83409. renderSubMesh(opaqueSubMeshes.data[index]);
  83410. }
  83411. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83412. renderSubMesh(alphaTestSubMeshes.data[index]);
  83413. }
  83414. if (transparentSubMeshes.length) {
  83415. // Sort sub meshes
  83416. for (index = 0; index < transparentSubMeshes.length; index++) {
  83417. var submesh = transparentSubMeshes.data[index];
  83418. var boundingInfo = submesh.getBoundingInfo();
  83419. if (boundingInfo && scene.activeCamera) {
  83420. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  83421. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  83422. }
  83423. }
  83424. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  83425. sortedArray.sort(function (a, b) {
  83426. // Alpha index first
  83427. if (a._alphaIndex > b._alphaIndex) {
  83428. return 1;
  83429. }
  83430. if (a._alphaIndex < b._alphaIndex) {
  83431. return -1;
  83432. }
  83433. // Then distance to camera
  83434. if (a._distanceToCamera < b._distanceToCamera) {
  83435. return 1;
  83436. }
  83437. if (a._distanceToCamera > b._distanceToCamera) {
  83438. return -1;
  83439. }
  83440. return 0;
  83441. });
  83442. // Render sub meshes
  83443. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  83444. for (index = 0; index < sortedArray.length; index++) {
  83445. renderSubMesh(sortedArray[index]);
  83446. }
  83447. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83448. }
  83449. };
  83450. };
  83451. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  83452. var transform = scene.getTransformMatrix();
  83453. var meshPosition;
  83454. if (this.useCustomMeshPosition) {
  83455. meshPosition = this.customMeshPosition;
  83456. }
  83457. else if (this.attachedNode) {
  83458. meshPosition = this.attachedNode.position;
  83459. }
  83460. else {
  83461. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  83462. }
  83463. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  83464. this._screenCoordinates.x = pos.x / this._viewPort.width;
  83465. this._screenCoordinates.y = pos.y / this._viewPort.height;
  83466. if (this.invert)
  83467. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  83468. };
  83469. // Static methods
  83470. /**
  83471. * Creates a default mesh for the Volumeric Light Scattering post-process
  83472. * @param {string} The mesh name
  83473. * @param {BABYLON.Scene} The scene where to create the mesh
  83474. * @return {BABYLON.Mesh} the default mesh
  83475. */
  83476. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  83477. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  83478. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  83479. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  83480. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  83481. mesh.material = material;
  83482. return mesh;
  83483. };
  83484. __decorate([
  83485. BABYLON.serializeAsVector3()
  83486. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  83487. __decorate([
  83488. BABYLON.serialize()
  83489. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  83490. __decorate([
  83491. BABYLON.serialize()
  83492. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  83493. __decorate([
  83494. BABYLON.serializeAsMeshReference()
  83495. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  83496. __decorate([
  83497. BABYLON.serialize()
  83498. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  83499. __decorate([
  83500. BABYLON.serialize()
  83501. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  83502. __decorate([
  83503. BABYLON.serialize()
  83504. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  83505. __decorate([
  83506. BABYLON.serialize()
  83507. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  83508. __decorate([
  83509. BABYLON.serialize()
  83510. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  83511. return VolumetricLightScatteringPostProcess;
  83512. }(BABYLON.PostProcess));
  83513. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  83514. })(BABYLON || (BABYLON = {}));
  83515. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  83516. //
  83517. // This post-process allows the modification of rendered colors by using
  83518. // a 'look-up table' (LUT). This effect is also called Color Grading.
  83519. //
  83520. // The object needs to be provided an url to a texture containing the color
  83521. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  83522. // Use an image editing software to tweak the LUT to match your needs.
  83523. //
  83524. // For an example of a color LUT, see here:
  83525. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  83526. // For explanations on color grading, see here:
  83527. // http://udn.epicgames.com/Three/ColorGrading.html
  83528. //
  83529. var BABYLON;
  83530. (function (BABYLON) {
  83531. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  83532. __extends(ColorCorrectionPostProcess, _super);
  83533. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  83534. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  83535. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83536. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  83537. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83538. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83539. _this.onApply = function (effect) {
  83540. effect.setTexture("colorTable", _this._colorTableTexture);
  83541. };
  83542. return _this;
  83543. }
  83544. return ColorCorrectionPostProcess;
  83545. }(BABYLON.PostProcess));
  83546. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  83547. })(BABYLON || (BABYLON = {}));
  83548. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  83549. var BABYLON;
  83550. (function (BABYLON) {
  83551. /** Defines operator used for tonemapping */
  83552. var TonemappingOperator;
  83553. (function (TonemappingOperator) {
  83554. /** Hable */
  83555. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  83556. /** Reinhard */
  83557. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  83558. /** HejiDawson */
  83559. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  83560. /** Photographic */
  83561. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  83562. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  83563. ;
  83564. /**
  83565. * Defines a post process to apply tone mapping
  83566. */
  83567. var TonemapPostProcess = /** @class */ (function (_super) {
  83568. __extends(TonemapPostProcess, _super);
  83569. /**
  83570. * Creates a new TonemapPostProcess
  83571. * @param name defines the name of the postprocess
  83572. * @param _operator defines the operator to use
  83573. * @param exposureAdjustment defines the required exposure adjustement
  83574. * @param camera defines the camera to use (can be null)
  83575. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  83576. * @param engine defines the hosting engine (can be ignore if camera is set)
  83577. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  83578. */
  83579. function TonemapPostProcess(name, _operator,
  83580. /** Defines the required exposure adjustement */
  83581. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  83582. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83583. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83584. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  83585. _this._operator = _operator;
  83586. _this.exposureAdjustment = exposureAdjustment;
  83587. var defines = "#define ";
  83588. if (_this._operator === TonemappingOperator.Hable)
  83589. defines += "HABLE_TONEMAPPING";
  83590. else if (_this._operator === TonemappingOperator.Reinhard)
  83591. defines += "REINHARD_TONEMAPPING";
  83592. else if (_this._operator === TonemappingOperator.HejiDawson)
  83593. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  83594. else if (_this._operator === TonemappingOperator.Photographic)
  83595. defines += "PHOTOGRAPHIC_TONEMAPPING";
  83596. //sadly a second call to create the effect.
  83597. _this.updateEffect(defines);
  83598. _this.onApply = function (effect) {
  83599. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  83600. };
  83601. return _this;
  83602. }
  83603. return TonemapPostProcess;
  83604. }(BABYLON.PostProcess));
  83605. BABYLON.TonemapPostProcess = TonemapPostProcess;
  83606. })(BABYLON || (BABYLON = {}));
  83607. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  83608. var BABYLON;
  83609. (function (BABYLON) {
  83610. var DisplayPassPostProcess = /** @class */ (function (_super) {
  83611. __extends(DisplayPassPostProcess, _super);
  83612. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  83613. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  83614. }
  83615. return DisplayPassPostProcess;
  83616. }(BABYLON.PostProcess));
  83617. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  83618. })(BABYLON || (BABYLON = {}));
  83619. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  83620. var BABYLON;
  83621. (function (BABYLON) {
  83622. var HighlightsPostProcess = /** @class */ (function (_super) {
  83623. __extends(HighlightsPostProcess, _super);
  83624. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  83625. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83626. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83627. }
  83628. return HighlightsPostProcess;
  83629. }(BABYLON.PostProcess));
  83630. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  83631. })(BABYLON || (BABYLON = {}));
  83632. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  83633. var BABYLON;
  83634. (function (BABYLON) {
  83635. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  83636. __extends(ImageProcessingPostProcess, _super);
  83637. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  83638. if (camera === void 0) { camera = null; }
  83639. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83640. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  83641. _this._fromLinearSpace = true;
  83642. /**
  83643. * Defines cache preventing GC.
  83644. */
  83645. _this._defines = {
  83646. IMAGEPROCESSING: false,
  83647. VIGNETTE: false,
  83648. VIGNETTEBLENDMODEMULTIPLY: false,
  83649. VIGNETTEBLENDMODEOPAQUE: false,
  83650. TONEMAPPING: false,
  83651. TONEMAPPING_ACES: false,
  83652. CONTRAST: false,
  83653. COLORCURVES: false,
  83654. COLORGRADING: false,
  83655. COLORGRADING3D: false,
  83656. FROMLINEARSPACE: false,
  83657. SAMPLER3DGREENDEPTH: false,
  83658. SAMPLER3DBGRMAP: false,
  83659. IMAGEPROCESSINGPOSTPROCESS: false,
  83660. EXPOSURE: false,
  83661. };
  83662. // Setup the configuration as forced by the constructor. This would then not force the
  83663. // scene materials output in linear space and let untouched the default forward pass.
  83664. if (imageProcessingConfiguration) {
  83665. imageProcessingConfiguration.applyByPostProcess = true;
  83666. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  83667. // This will cause the shader to be compiled
  83668. _this.fromLinearSpace = false;
  83669. }
  83670. // Setup the default processing configuration to the scene.
  83671. else {
  83672. _this._attachImageProcessingConfiguration(null, true);
  83673. _this.imageProcessingConfiguration.applyByPostProcess = true;
  83674. }
  83675. _this.onApply = function (effect) {
  83676. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  83677. };
  83678. return _this;
  83679. }
  83680. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  83681. /**
  83682. * Gets the image processing configuration used either in this material.
  83683. */
  83684. get: function () {
  83685. return this._imageProcessingConfiguration;
  83686. },
  83687. /**
  83688. * Sets the Default image processing configuration used either in the this material.
  83689. *
  83690. * If sets to null, the scene one is in use.
  83691. */
  83692. set: function (value) {
  83693. this._attachImageProcessingConfiguration(value);
  83694. },
  83695. enumerable: true,
  83696. configurable: true
  83697. });
  83698. /**
  83699. * Attaches a new image processing configuration to the PBR Material.
  83700. * @param configuration
  83701. */
  83702. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  83703. var _this = this;
  83704. if (doNotBuild === void 0) { doNotBuild = false; }
  83705. if (configuration === this._imageProcessingConfiguration) {
  83706. return;
  83707. }
  83708. // Detaches observer.
  83709. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83710. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83711. }
  83712. // Pick the scene configuration if needed.
  83713. if (!configuration) {
  83714. var scene = null;
  83715. var engine = this.getEngine();
  83716. var camera = this.getCamera();
  83717. if (camera) {
  83718. scene = camera.getScene();
  83719. }
  83720. else if (engine && engine.scenes) {
  83721. var scenes = engine.scenes;
  83722. scene = scenes[scenes.length - 1];
  83723. }
  83724. else {
  83725. scene = BABYLON.Engine.LastCreatedScene;
  83726. }
  83727. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  83728. }
  83729. else {
  83730. this._imageProcessingConfiguration = configuration;
  83731. }
  83732. // Attaches observer.
  83733. if (this._imageProcessingConfiguration) {
  83734. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  83735. _this._updateParameters();
  83736. });
  83737. }
  83738. // Ensure the effect will be rebuilt.
  83739. if (!doNotBuild) {
  83740. this._updateParameters();
  83741. }
  83742. };
  83743. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  83744. /**
  83745. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  83746. */
  83747. get: function () {
  83748. return this.imageProcessingConfiguration.colorCurves;
  83749. },
  83750. /**
  83751. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  83752. */
  83753. set: function (value) {
  83754. this.imageProcessingConfiguration.colorCurves = value;
  83755. },
  83756. enumerable: true,
  83757. configurable: true
  83758. });
  83759. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  83760. /**
  83761. * Gets wether the color curves effect is enabled.
  83762. */
  83763. get: function () {
  83764. return this.imageProcessingConfiguration.colorCurvesEnabled;
  83765. },
  83766. /**
  83767. * Sets wether the color curves effect is enabled.
  83768. */
  83769. set: function (value) {
  83770. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  83771. },
  83772. enumerable: true,
  83773. configurable: true
  83774. });
  83775. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  83776. /**
  83777. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  83778. */
  83779. get: function () {
  83780. return this.imageProcessingConfiguration.colorGradingTexture;
  83781. },
  83782. /**
  83783. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  83784. */
  83785. set: function (value) {
  83786. this.imageProcessingConfiguration.colorGradingTexture = value;
  83787. },
  83788. enumerable: true,
  83789. configurable: true
  83790. });
  83791. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  83792. /**
  83793. * Gets wether the color grading effect is enabled.
  83794. */
  83795. get: function () {
  83796. return this.imageProcessingConfiguration.colorGradingEnabled;
  83797. },
  83798. /**
  83799. * Gets wether the color grading effect is enabled.
  83800. */
  83801. set: function (value) {
  83802. this.imageProcessingConfiguration.colorGradingEnabled = value;
  83803. },
  83804. enumerable: true,
  83805. configurable: true
  83806. });
  83807. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  83808. /**
  83809. * Gets exposure used in the effect.
  83810. */
  83811. get: function () {
  83812. return this.imageProcessingConfiguration.exposure;
  83813. },
  83814. /**
  83815. * Sets exposure used in the effect.
  83816. */
  83817. set: function (value) {
  83818. this.imageProcessingConfiguration.exposure = value;
  83819. },
  83820. enumerable: true,
  83821. configurable: true
  83822. });
  83823. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  83824. /**
  83825. * Gets wether tonemapping is enabled or not.
  83826. */
  83827. get: function () {
  83828. return this._imageProcessingConfiguration.toneMappingEnabled;
  83829. },
  83830. /**
  83831. * Sets wether tonemapping is enabled or not
  83832. */
  83833. set: function (value) {
  83834. this._imageProcessingConfiguration.toneMappingEnabled = value;
  83835. },
  83836. enumerable: true,
  83837. configurable: true
  83838. });
  83839. ;
  83840. ;
  83841. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  83842. /**
  83843. * Gets contrast used in the effect.
  83844. */
  83845. get: function () {
  83846. return this.imageProcessingConfiguration.contrast;
  83847. },
  83848. /**
  83849. * Sets contrast used in the effect.
  83850. */
  83851. set: function (value) {
  83852. this.imageProcessingConfiguration.contrast = value;
  83853. },
  83854. enumerable: true,
  83855. configurable: true
  83856. });
  83857. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  83858. /**
  83859. * Gets Vignette stretch size.
  83860. */
  83861. get: function () {
  83862. return this.imageProcessingConfiguration.vignetteStretch;
  83863. },
  83864. /**
  83865. * Sets Vignette stretch size.
  83866. */
  83867. set: function (value) {
  83868. this.imageProcessingConfiguration.vignetteStretch = value;
  83869. },
  83870. enumerable: true,
  83871. configurable: true
  83872. });
  83873. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  83874. /**
  83875. * Gets Vignette centre X Offset.
  83876. */
  83877. get: function () {
  83878. return this.imageProcessingConfiguration.vignetteCentreX;
  83879. },
  83880. /**
  83881. * Sets Vignette centre X Offset.
  83882. */
  83883. set: function (value) {
  83884. this.imageProcessingConfiguration.vignetteCentreX = value;
  83885. },
  83886. enumerable: true,
  83887. configurable: true
  83888. });
  83889. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  83890. /**
  83891. * Gets Vignette centre Y Offset.
  83892. */
  83893. get: function () {
  83894. return this.imageProcessingConfiguration.vignetteCentreY;
  83895. },
  83896. /**
  83897. * Sets Vignette centre Y Offset.
  83898. */
  83899. set: function (value) {
  83900. this.imageProcessingConfiguration.vignetteCentreY = value;
  83901. },
  83902. enumerable: true,
  83903. configurable: true
  83904. });
  83905. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  83906. /**
  83907. * Gets Vignette weight or intensity of the vignette effect.
  83908. */
  83909. get: function () {
  83910. return this.imageProcessingConfiguration.vignetteWeight;
  83911. },
  83912. /**
  83913. * Sets Vignette weight or intensity of the vignette effect.
  83914. */
  83915. set: function (value) {
  83916. this.imageProcessingConfiguration.vignetteWeight = value;
  83917. },
  83918. enumerable: true,
  83919. configurable: true
  83920. });
  83921. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  83922. /**
  83923. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  83924. * if vignetteEnabled is set to true.
  83925. */
  83926. get: function () {
  83927. return this.imageProcessingConfiguration.vignetteColor;
  83928. },
  83929. /**
  83930. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  83931. * if vignetteEnabled is set to true.
  83932. */
  83933. set: function (value) {
  83934. this.imageProcessingConfiguration.vignetteColor = value;
  83935. },
  83936. enumerable: true,
  83937. configurable: true
  83938. });
  83939. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  83940. /**
  83941. * Gets Camera field of view used by the Vignette effect.
  83942. */
  83943. get: function () {
  83944. return this.imageProcessingConfiguration.vignetteCameraFov;
  83945. },
  83946. /**
  83947. * Sets Camera field of view used by the Vignette effect.
  83948. */
  83949. set: function (value) {
  83950. this.imageProcessingConfiguration.vignetteCameraFov = value;
  83951. },
  83952. enumerable: true,
  83953. configurable: true
  83954. });
  83955. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  83956. /**
  83957. * Gets the vignette blend mode allowing different kind of effect.
  83958. */
  83959. get: function () {
  83960. return this.imageProcessingConfiguration.vignetteBlendMode;
  83961. },
  83962. /**
  83963. * Sets the vignette blend mode allowing different kind of effect.
  83964. */
  83965. set: function (value) {
  83966. this.imageProcessingConfiguration.vignetteBlendMode = value;
  83967. },
  83968. enumerable: true,
  83969. configurable: true
  83970. });
  83971. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  83972. /**
  83973. * Gets wether the vignette effect is enabled.
  83974. */
  83975. get: function () {
  83976. return this.imageProcessingConfiguration.vignetteEnabled;
  83977. },
  83978. /**
  83979. * Sets wether the vignette effect is enabled.
  83980. */
  83981. set: function (value) {
  83982. this.imageProcessingConfiguration.vignetteEnabled = value;
  83983. },
  83984. enumerable: true,
  83985. configurable: true
  83986. });
  83987. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  83988. /**
  83989. * Gets wether the input of the processing is in Gamma or Linear Space.
  83990. */
  83991. get: function () {
  83992. return this._fromLinearSpace;
  83993. },
  83994. /**
  83995. * Sets wether the input of the processing is in Gamma or Linear Space.
  83996. */
  83997. set: function (value) {
  83998. if (this._fromLinearSpace === value) {
  83999. return;
  84000. }
  84001. this._fromLinearSpace = value;
  84002. this._updateParameters();
  84003. },
  84004. enumerable: true,
  84005. configurable: true
  84006. });
  84007. ImageProcessingPostProcess.prototype.getClassName = function () {
  84008. return "ImageProcessingPostProcess";
  84009. };
  84010. ImageProcessingPostProcess.prototype._updateParameters = function () {
  84011. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  84012. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  84013. var defines = "";
  84014. for (var define in this._defines) {
  84015. if (this._defines[define]) {
  84016. defines += "#define " + define + ";\r\n";
  84017. }
  84018. }
  84019. var samplers = ["textureSampler"];
  84020. var uniforms = ["scale"];
  84021. if (BABYLON.ImageProcessingConfiguration) {
  84022. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  84023. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  84024. }
  84025. this.updateEffect(defines, uniforms, samplers);
  84026. };
  84027. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  84028. _super.prototype.dispose.call(this, camera);
  84029. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  84030. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  84031. }
  84032. if (this._imageProcessingConfiguration) {
  84033. this.imageProcessingConfiguration.applyByPostProcess = false;
  84034. }
  84035. };
  84036. __decorate([
  84037. BABYLON.serialize()
  84038. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  84039. return ImageProcessingPostProcess;
  84040. }(BABYLON.PostProcess));
  84041. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  84042. })(BABYLON || (BABYLON = {}));
  84043. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  84044. var BABYLON;
  84045. (function (BABYLON) {
  84046. /**
  84047. * Class used to store bone information
  84048. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  84049. */
  84050. var Bone = /** @class */ (function (_super) {
  84051. __extends(Bone, _super);
  84052. /**
  84053. * Create a new bone
  84054. * @param name defines the bone name
  84055. * @param skeleton defines the parent skeleton
  84056. * @param parentBone defines the parent (can be null if the bone is the root)
  84057. * @param localMatrix defines the local matrix
  84058. * @param restPose defines the rest pose matrix
  84059. * @param baseMatrix defines the base matrix
  84060. * @param index defines index of the bone in the hiearchy
  84061. */
  84062. function Bone(
  84063. /**
  84064. * defines the bone name
  84065. */
  84066. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  84067. if (parentBone === void 0) { parentBone = null; }
  84068. if (localMatrix === void 0) { localMatrix = null; }
  84069. if (restPose === void 0) { restPose = null; }
  84070. if (baseMatrix === void 0) { baseMatrix = null; }
  84071. if (index === void 0) { index = null; }
  84072. var _this = _super.call(this, name, skeleton.getScene()) || this;
  84073. _this.name = name;
  84074. /**
  84075. * Gets the list of child bones
  84076. */
  84077. _this.children = new Array();
  84078. /** Gets the animations associated with this bone */
  84079. _this.animations = new Array();
  84080. /**
  84081. * @hidden Internal only
  84082. * Set this value to map this bone to a different index in the transform matrices
  84083. * Set this value to -1 to exclude the bone from the transform matrices
  84084. */
  84085. _this._index = null;
  84086. _this._absoluteTransform = new BABYLON.Matrix();
  84087. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  84088. _this._scalingDeterminant = 1;
  84089. _this._worldTransform = new BABYLON.Matrix();
  84090. _this._needToDecompose = true;
  84091. _this._needToCompose = false;
  84092. _this._skeleton = skeleton;
  84093. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  84094. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  84095. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  84096. _this._index = index;
  84097. skeleton.bones.push(_this);
  84098. _this.setParent(parentBone, false);
  84099. if (baseMatrix || localMatrix) {
  84100. _this._updateDifferenceMatrix();
  84101. }
  84102. return _this;
  84103. }
  84104. Object.defineProperty(Bone.prototype, "_matrix", {
  84105. /** @hidden */
  84106. get: function () {
  84107. this._compose();
  84108. return this._localMatrix;
  84109. },
  84110. /** @hidden */
  84111. set: function (value) {
  84112. this._localMatrix.copyFrom(value);
  84113. this._needToDecompose = true;
  84114. },
  84115. enumerable: true,
  84116. configurable: true
  84117. });
  84118. // Members
  84119. /**
  84120. * Gets the parent skeleton
  84121. * @returns a skeleton
  84122. */
  84123. Bone.prototype.getSkeleton = function () {
  84124. return this._skeleton;
  84125. };
  84126. /**
  84127. * Gets parent bone
  84128. * @returns a bone or null if the bone is the root of the bone hierarchy
  84129. */
  84130. Bone.prototype.getParent = function () {
  84131. return this._parent;
  84132. };
  84133. /**
  84134. * Sets the parent bone
  84135. * @param parent defines the parent (can be null if the bone is the root)
  84136. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84137. */
  84138. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  84139. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84140. if (this._parent === parent) {
  84141. return;
  84142. }
  84143. if (this._parent) {
  84144. var index = this._parent.children.indexOf(this);
  84145. if (index !== -1) {
  84146. this._parent.children.splice(index, 1);
  84147. }
  84148. }
  84149. this._parent = parent;
  84150. if (this._parent) {
  84151. this._parent.children.push(this);
  84152. }
  84153. if (updateDifferenceMatrix) {
  84154. this._updateDifferenceMatrix();
  84155. }
  84156. this.markAsDirty();
  84157. };
  84158. /**
  84159. * Gets the local matrix
  84160. * @returns a matrix
  84161. */
  84162. Bone.prototype.getLocalMatrix = function () {
  84163. this._compose();
  84164. return this._localMatrix;
  84165. };
  84166. /**
  84167. * Gets the base matrix (initial matrix which remains unchanged)
  84168. * @returns a matrix
  84169. */
  84170. Bone.prototype.getBaseMatrix = function () {
  84171. return this._baseMatrix;
  84172. };
  84173. /**
  84174. * Gets the rest pose matrix
  84175. * @returns a matrix
  84176. */
  84177. Bone.prototype.getRestPose = function () {
  84178. return this._restPose;
  84179. };
  84180. /**
  84181. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  84182. */
  84183. Bone.prototype.getWorldMatrix = function () {
  84184. return this._worldTransform;
  84185. };
  84186. /**
  84187. * Sets the local matrix to rest pose matrix
  84188. */
  84189. Bone.prototype.returnToRest = function () {
  84190. this.updateMatrix(this._restPose.clone());
  84191. };
  84192. /**
  84193. * Gets the inverse of the absolute transform matrix.
  84194. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  84195. * @returns a matrix
  84196. */
  84197. Bone.prototype.getInvertedAbsoluteTransform = function () {
  84198. return this._invertedAbsoluteTransform;
  84199. };
  84200. /**
  84201. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  84202. * @returns a matrix
  84203. */
  84204. Bone.prototype.getAbsoluteTransform = function () {
  84205. return this._absoluteTransform;
  84206. };
  84207. Object.defineProperty(Bone.prototype, "position", {
  84208. // Properties (matches AbstractMesh properties)
  84209. /** Gets or sets current position (in local space) */
  84210. get: function () {
  84211. this._decompose();
  84212. return this._localPosition;
  84213. },
  84214. set: function (newPosition) {
  84215. this._decompose();
  84216. this._localPosition.copyFrom(newPosition);
  84217. this._markAsDirtyAndCompose();
  84218. },
  84219. enumerable: true,
  84220. configurable: true
  84221. });
  84222. Object.defineProperty(Bone.prototype, "rotation", {
  84223. /** Gets or sets current rotation (in local space) */
  84224. get: function () {
  84225. return this.getRotation();
  84226. },
  84227. set: function (newRotation) {
  84228. this.setRotation(newRotation);
  84229. },
  84230. enumerable: true,
  84231. configurable: true
  84232. });
  84233. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  84234. /** Gets or sets current rotation quaternion (in local space) */
  84235. get: function () {
  84236. this._decompose();
  84237. return this._localRotation;
  84238. },
  84239. set: function (newRotation) {
  84240. this.setRotationQuaternion(newRotation);
  84241. },
  84242. enumerable: true,
  84243. configurable: true
  84244. });
  84245. Object.defineProperty(Bone.prototype, "scaling", {
  84246. /** Gets or sets current scaling (in local space) */
  84247. get: function () {
  84248. return this.getScale();
  84249. },
  84250. set: function (newScaling) {
  84251. this.setScale(newScaling);
  84252. },
  84253. enumerable: true,
  84254. configurable: true
  84255. });
  84256. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  84257. /**
  84258. * Gets the animation properties override
  84259. */
  84260. get: function () {
  84261. return this._skeleton.animationPropertiesOverride;
  84262. },
  84263. enumerable: true,
  84264. configurable: true
  84265. });
  84266. // Methods
  84267. Bone.prototype._decompose = function () {
  84268. if (!this._needToDecompose) {
  84269. return;
  84270. }
  84271. this._needToDecompose = false;
  84272. if (!this._localScaling) {
  84273. this._localScaling = BABYLON.Vector3.Zero();
  84274. this._localRotation = BABYLON.Quaternion.Zero();
  84275. this._localPosition = BABYLON.Vector3.Zero();
  84276. }
  84277. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  84278. };
  84279. Bone.prototype._compose = function () {
  84280. if (!this._needToCompose) {
  84281. return;
  84282. }
  84283. this._needToCompose = false;
  84284. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  84285. };
  84286. /**
  84287. * Update the base and local matrices
  84288. * @param matrix defines the new base or local matrix
  84289. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84290. * @param updateLocalMatrix defines if the local matrix should be updated
  84291. */
  84292. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  84293. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84294. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  84295. this._baseMatrix.copyFrom(matrix);
  84296. if (updateDifferenceMatrix) {
  84297. this._updateDifferenceMatrix();
  84298. }
  84299. if (updateLocalMatrix) {
  84300. this._localMatrix.copyFrom(matrix);
  84301. this._markAsDirtyAndDecompose();
  84302. }
  84303. else {
  84304. this.markAsDirty();
  84305. }
  84306. };
  84307. /** @hidden */
  84308. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  84309. if (updateChildren === void 0) { updateChildren = true; }
  84310. if (!rootMatrix) {
  84311. rootMatrix = this._baseMatrix;
  84312. }
  84313. if (this._parent) {
  84314. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  84315. }
  84316. else {
  84317. this._absoluteTransform.copyFrom(rootMatrix);
  84318. }
  84319. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  84320. if (updateChildren) {
  84321. for (var index = 0; index < this.children.length; index++) {
  84322. this.children[index]._updateDifferenceMatrix();
  84323. }
  84324. }
  84325. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  84326. };
  84327. /**
  84328. * Flag the bone as dirty (Forcing it to update everything)
  84329. */
  84330. Bone.prototype.markAsDirty = function () {
  84331. this._currentRenderId++;
  84332. this._childRenderId++;
  84333. this._skeleton._markAsDirty();
  84334. };
  84335. Bone.prototype._markAsDirtyAndCompose = function () {
  84336. this.markAsDirty();
  84337. this._needToCompose = true;
  84338. };
  84339. Bone.prototype._markAsDirtyAndDecompose = function () {
  84340. this.markAsDirty();
  84341. this._needToDecompose = true;
  84342. };
  84343. /**
  84344. * Copy an animation range from another bone
  84345. * @param source defines the source bone
  84346. * @param rangeName defines the range name to copy
  84347. * @param frameOffset defines the frame offset
  84348. * @param rescaleAsRequired defines if rescaling must be applied if required
  84349. * @param skelDimensionsRatio defines the scaling ratio
  84350. * @returns true if operation was successful
  84351. */
  84352. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  84353. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  84354. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  84355. // all animation may be coming from a library skeleton, so may need to create animation
  84356. if (this.animations.length === 0) {
  84357. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  84358. this.animations[0].setKeys([]);
  84359. }
  84360. // get animation info / verify there is such a range from the source bone
  84361. var sourceRange = source.animations[0].getRange(rangeName);
  84362. if (!sourceRange) {
  84363. return false;
  84364. }
  84365. var from = sourceRange.from;
  84366. var to = sourceRange.to;
  84367. var sourceKeys = source.animations[0].getKeys();
  84368. // rescaling prep
  84369. var sourceBoneLength = source.length;
  84370. var sourceParent = source.getParent();
  84371. var parent = this.getParent();
  84372. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  84373. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  84374. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  84375. var destKeys = this.animations[0].getKeys();
  84376. // loop vars declaration
  84377. var orig;
  84378. var origTranslation;
  84379. var mat;
  84380. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  84381. orig = sourceKeys[key];
  84382. if (orig.frame >= from && orig.frame <= to) {
  84383. if (rescaleAsRequired) {
  84384. mat = orig.value.clone();
  84385. // scale based on parent ratio, when bone has parent
  84386. if (parentScalingReqd) {
  84387. origTranslation = mat.getTranslation();
  84388. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  84389. // scale based on skeleton dimension ratio when root bone, and value is passed
  84390. }
  84391. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  84392. origTranslation = mat.getTranslation();
  84393. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  84394. // use original when root bone, and no data for skelDimensionsRatio
  84395. }
  84396. else {
  84397. mat = orig.value;
  84398. }
  84399. }
  84400. else {
  84401. mat = orig.value;
  84402. }
  84403. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  84404. }
  84405. }
  84406. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  84407. return true;
  84408. };
  84409. /**
  84410. * Translate the bone in local or world space
  84411. * @param vec The amount to translate the bone
  84412. * @param space The space that the translation is in
  84413. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84414. */
  84415. Bone.prototype.translate = function (vec, space, mesh) {
  84416. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84417. var lm = this.getLocalMatrix();
  84418. if (space == BABYLON.Space.LOCAL) {
  84419. lm.m[12] += vec.x;
  84420. lm.m[13] += vec.y;
  84421. lm.m[14] += vec.z;
  84422. }
  84423. else {
  84424. var wm = null;
  84425. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84426. if (mesh) {
  84427. wm = mesh.getWorldMatrix();
  84428. }
  84429. this._skeleton.computeAbsoluteTransforms();
  84430. var tmat = Bone._tmpMats[0];
  84431. var tvec = Bone._tmpVecs[0];
  84432. if (this._parent) {
  84433. if (mesh && wm) {
  84434. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84435. tmat.multiplyToRef(wm, tmat);
  84436. }
  84437. else {
  84438. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84439. }
  84440. }
  84441. tmat.m[12] = 0;
  84442. tmat.m[13] = 0;
  84443. tmat.m[14] = 0;
  84444. tmat.invert();
  84445. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  84446. lm.m[12] += tvec.x;
  84447. lm.m[13] += tvec.y;
  84448. lm.m[14] += tvec.z;
  84449. }
  84450. this._markAsDirtyAndDecompose();
  84451. };
  84452. /**
  84453. * Set the postion of the bone in local or world space
  84454. * @param position The position to set the bone
  84455. * @param space The space that the position is in
  84456. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84457. */
  84458. Bone.prototype.setPosition = function (position, space, mesh) {
  84459. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84460. var lm = this.getLocalMatrix();
  84461. if (space == BABYLON.Space.LOCAL) {
  84462. lm.m[12] = position.x;
  84463. lm.m[13] = position.y;
  84464. lm.m[14] = position.z;
  84465. }
  84466. else {
  84467. var wm = null;
  84468. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84469. if (mesh) {
  84470. wm = mesh.getWorldMatrix();
  84471. }
  84472. this._skeleton.computeAbsoluteTransforms();
  84473. var tmat = Bone._tmpMats[0];
  84474. var vec = Bone._tmpVecs[0];
  84475. if (this._parent) {
  84476. if (mesh && wm) {
  84477. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84478. tmat.multiplyToRef(wm, tmat);
  84479. }
  84480. else {
  84481. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84482. }
  84483. }
  84484. tmat.invert();
  84485. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  84486. lm.m[12] = vec.x;
  84487. lm.m[13] = vec.y;
  84488. lm.m[14] = vec.z;
  84489. }
  84490. this._markAsDirtyAndDecompose();
  84491. };
  84492. /**
  84493. * Set the absolute position of the bone (world space)
  84494. * @param position The position to set the bone
  84495. * @param mesh The mesh that this bone is attached to
  84496. */
  84497. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  84498. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  84499. };
  84500. /**
  84501. * Scale the bone on the x, y and z axes (in local space)
  84502. * @param x The amount to scale the bone on the x axis
  84503. * @param y The amount to scale the bone on the y axis
  84504. * @param z The amount to scale the bone on the z axis
  84505. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  84506. */
  84507. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  84508. if (scaleChildren === void 0) { scaleChildren = false; }
  84509. var locMat = this.getLocalMatrix();
  84510. // Apply new scaling on top of current local matrix
  84511. var scaleMat = Bone._tmpMats[0];
  84512. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  84513. scaleMat.multiplyToRef(locMat, locMat);
  84514. // Invert scaling matrix and apply the inverse to all children
  84515. scaleMat.invert();
  84516. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  84517. var child = _a[_i];
  84518. var cm = child.getLocalMatrix();
  84519. cm.multiplyToRef(scaleMat, cm);
  84520. cm.m[12] *= x;
  84521. cm.m[13] *= y;
  84522. cm.m[14] *= z;
  84523. child._markAsDirtyAndDecompose();
  84524. }
  84525. this._markAsDirtyAndDecompose();
  84526. if (scaleChildren) {
  84527. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  84528. var child = _c[_b];
  84529. child.scale(x, y, z, scaleChildren);
  84530. }
  84531. }
  84532. };
  84533. /**
  84534. * Set the bone scaling in local space
  84535. * @param scale defines the scaling vector
  84536. */
  84537. Bone.prototype.setScale = function (scale) {
  84538. this._decompose();
  84539. this._localScaling.copyFrom(scale);
  84540. this._markAsDirtyAndCompose();
  84541. };
  84542. /**
  84543. * Gets the current scaling in local space
  84544. * @returns the current scaling vector
  84545. */
  84546. Bone.prototype.getScale = function () {
  84547. this._decompose();
  84548. return this._localScaling;
  84549. };
  84550. /**
  84551. * Gets the current scaling in local space and stores it in a target vector
  84552. * @param result defines the target vector
  84553. */
  84554. Bone.prototype.getScaleToRef = function (result) {
  84555. this._decompose();
  84556. result.copyFrom(this._localScaling);
  84557. };
  84558. /**
  84559. * Set the yaw, pitch, and roll of the bone in local or world space
  84560. * @param yaw The rotation of the bone on the y axis
  84561. * @param pitch The rotation of the bone on the x axis
  84562. * @param roll The rotation of the bone on the z axis
  84563. * @param space The space that the axes of rotation are in
  84564. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84565. */
  84566. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  84567. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84568. if (space === BABYLON.Space.LOCAL) {
  84569. var quat = Bone._tmpQuat;
  84570. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  84571. this.setRotationQuaternion(quat, space, mesh);
  84572. return;
  84573. }
  84574. var rotMatInv = Bone._tmpMats[0];
  84575. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84576. return;
  84577. }
  84578. var rotMat = Bone._tmpMats[1];
  84579. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  84580. rotMatInv.multiplyToRef(rotMat, rotMat);
  84581. this._rotateWithMatrix(rotMat, space, mesh);
  84582. };
  84583. /**
  84584. * Add a rotation to the bone on an axis in local or world space
  84585. * @param axis The axis to rotate the bone on
  84586. * @param amount The amount to rotate the bone
  84587. * @param space The space that the axis is in
  84588. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84589. */
  84590. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  84591. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84592. var rmat = Bone._tmpMats[0];
  84593. rmat.m[12] = 0;
  84594. rmat.m[13] = 0;
  84595. rmat.m[14] = 0;
  84596. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  84597. this._rotateWithMatrix(rmat, space, mesh);
  84598. };
  84599. /**
  84600. * Set the rotation of the bone to a particular axis angle in local or world space
  84601. * @param axis The axis to rotate the bone on
  84602. * @param angle The angle that the bone should be rotated to
  84603. * @param space The space that the axis is in
  84604. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84605. */
  84606. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  84607. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84608. if (space === BABYLON.Space.LOCAL) {
  84609. var quat = Bone._tmpQuat;
  84610. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  84611. this.setRotationQuaternion(quat, space, mesh);
  84612. return;
  84613. }
  84614. var rotMatInv = Bone._tmpMats[0];
  84615. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84616. return;
  84617. }
  84618. var rotMat = Bone._tmpMats[1];
  84619. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  84620. rotMatInv.multiplyToRef(rotMat, rotMat);
  84621. this._rotateWithMatrix(rotMat, space, mesh);
  84622. };
  84623. /**
  84624. * Set the euler rotation of the bone in local of world space
  84625. * @param rotation The euler rotation that the bone should be set to
  84626. * @param space The space that the rotation is in
  84627. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84628. */
  84629. Bone.prototype.setRotation = function (rotation, space, mesh) {
  84630. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84631. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  84632. };
  84633. /**
  84634. * Set the quaternion rotation of the bone in local of world space
  84635. * @param quat The quaternion rotation that the bone should be set to
  84636. * @param space The space that the rotation is in
  84637. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84638. */
  84639. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  84640. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84641. if (space === BABYLON.Space.LOCAL) {
  84642. this._decompose();
  84643. this._localRotation.copyFrom(quat);
  84644. this._markAsDirtyAndCompose();
  84645. return;
  84646. }
  84647. var rotMatInv = Bone._tmpMats[0];
  84648. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84649. return;
  84650. }
  84651. var rotMat = Bone._tmpMats[1];
  84652. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  84653. rotMatInv.multiplyToRef(rotMat, rotMat);
  84654. this._rotateWithMatrix(rotMat, space, mesh);
  84655. };
  84656. /**
  84657. * Set the rotation matrix of the bone in local of world space
  84658. * @param rotMat The rotation matrix that the bone should be set to
  84659. * @param space The space that the rotation is in
  84660. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84661. */
  84662. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  84663. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84664. if (space === BABYLON.Space.LOCAL) {
  84665. var quat = Bone._tmpQuat;
  84666. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  84667. this.setRotationQuaternion(quat, space, mesh);
  84668. return;
  84669. }
  84670. var rotMatInv = Bone._tmpMats[0];
  84671. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84672. return;
  84673. }
  84674. var rotMat2 = Bone._tmpMats[1];
  84675. rotMat2.copyFrom(rotMat);
  84676. rotMatInv.multiplyToRef(rotMat, rotMat2);
  84677. this._rotateWithMatrix(rotMat2, space, mesh);
  84678. };
  84679. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  84680. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84681. var lmat = this.getLocalMatrix();
  84682. var lx = lmat.m[12];
  84683. var ly = lmat.m[13];
  84684. var lz = lmat.m[14];
  84685. var parent = this.getParent();
  84686. var parentScale = Bone._tmpMats[3];
  84687. var parentScaleInv = Bone._tmpMats[4];
  84688. if (parent && space == BABYLON.Space.WORLD) {
  84689. if (mesh) {
  84690. parentScale.copyFrom(mesh.getWorldMatrix());
  84691. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  84692. }
  84693. else {
  84694. parentScale.copyFrom(parent.getAbsoluteTransform());
  84695. }
  84696. parentScaleInv.copyFrom(parentScale);
  84697. parentScaleInv.invert();
  84698. lmat.multiplyToRef(parentScale, lmat);
  84699. lmat.multiplyToRef(rmat, lmat);
  84700. lmat.multiplyToRef(parentScaleInv, lmat);
  84701. }
  84702. else {
  84703. if (space == BABYLON.Space.WORLD && mesh) {
  84704. parentScale.copyFrom(mesh.getWorldMatrix());
  84705. parentScaleInv.copyFrom(parentScale);
  84706. parentScaleInv.invert();
  84707. lmat.multiplyToRef(parentScale, lmat);
  84708. lmat.multiplyToRef(rmat, lmat);
  84709. lmat.multiplyToRef(parentScaleInv, lmat);
  84710. }
  84711. else {
  84712. lmat.multiplyToRef(rmat, lmat);
  84713. }
  84714. }
  84715. lmat.m[12] = lx;
  84716. lmat.m[13] = ly;
  84717. lmat.m[14] = lz;
  84718. this.computeAbsoluteTransforms();
  84719. this._markAsDirtyAndDecompose();
  84720. };
  84721. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  84722. var scaleMatrix = Bone._tmpMats[2];
  84723. rotMatInv.copyFrom(this.getAbsoluteTransform());
  84724. if (mesh) {
  84725. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  84726. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  84727. }
  84728. rotMatInv.invert();
  84729. if (isNaN(rotMatInv.m[0])) {
  84730. // Matrix failed to invert.
  84731. // This can happen if scale is zero for example.
  84732. return false;
  84733. }
  84734. scaleMatrix.m[0] *= this._scalingDeterminant;
  84735. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  84736. return true;
  84737. };
  84738. /**
  84739. * Get the position of the bone in local or world space
  84740. * @param space The space that the returned position is in
  84741. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84742. * @returns The position of the bone
  84743. */
  84744. Bone.prototype.getPosition = function (space, mesh) {
  84745. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84746. if (mesh === void 0) { mesh = null; }
  84747. var pos = BABYLON.Vector3.Zero();
  84748. this.getPositionToRef(space, mesh, pos);
  84749. return pos;
  84750. };
  84751. /**
  84752. * Copy the position of the bone to a vector3 in local or world space
  84753. * @param space The space that the returned position is in
  84754. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84755. * @param result The vector3 to copy the position to
  84756. */
  84757. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  84758. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84759. if (space == BABYLON.Space.LOCAL) {
  84760. var lm = this.getLocalMatrix();
  84761. result.x = lm.m[12];
  84762. result.y = lm.m[13];
  84763. result.z = lm.m[14];
  84764. }
  84765. else {
  84766. var wm = null;
  84767. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84768. if (mesh) {
  84769. wm = mesh.getWorldMatrix();
  84770. }
  84771. this._skeleton.computeAbsoluteTransforms();
  84772. var tmat = Bone._tmpMats[0];
  84773. if (mesh && wm) {
  84774. tmat.copyFrom(this.getAbsoluteTransform());
  84775. tmat.multiplyToRef(wm, tmat);
  84776. }
  84777. else {
  84778. tmat = this.getAbsoluteTransform();
  84779. }
  84780. result.x = tmat.m[12];
  84781. result.y = tmat.m[13];
  84782. result.z = tmat.m[14];
  84783. }
  84784. };
  84785. /**
  84786. * Get the absolute position of the bone (world space)
  84787. * @param mesh The mesh that this bone is attached to
  84788. * @returns The absolute position of the bone
  84789. */
  84790. Bone.prototype.getAbsolutePosition = function (mesh) {
  84791. if (mesh === void 0) { mesh = null; }
  84792. var pos = BABYLON.Vector3.Zero();
  84793. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  84794. return pos;
  84795. };
  84796. /**
  84797. * Copy the absolute position of the bone (world space) to the result param
  84798. * @param mesh The mesh that this bone is attached to
  84799. * @param result The vector3 to copy the absolute position to
  84800. */
  84801. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  84802. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  84803. };
  84804. /**
  84805. * Compute the absolute transforms of this bone and its children
  84806. */
  84807. Bone.prototype.computeAbsoluteTransforms = function () {
  84808. this._compose();
  84809. if (this._parent) {
  84810. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  84811. }
  84812. else {
  84813. this._absoluteTransform.copyFrom(this._localMatrix);
  84814. var poseMatrix = this._skeleton.getPoseMatrix();
  84815. if (poseMatrix) {
  84816. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  84817. }
  84818. }
  84819. var children = this.children;
  84820. var len = children.length;
  84821. for (var i = 0; i < len; i++) {
  84822. children[i].computeAbsoluteTransforms();
  84823. }
  84824. };
  84825. /**
  84826. * Get the world direction from an axis that is in the local space of the bone
  84827. * @param localAxis The local direction that is used to compute the world direction
  84828. * @param mesh The mesh that this bone is attached to
  84829. * @returns The world direction
  84830. */
  84831. Bone.prototype.getDirection = function (localAxis, mesh) {
  84832. if (mesh === void 0) { mesh = null; }
  84833. var result = BABYLON.Vector3.Zero();
  84834. this.getDirectionToRef(localAxis, mesh, result);
  84835. return result;
  84836. };
  84837. /**
  84838. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  84839. * @param localAxis The local direction that is used to compute the world direction
  84840. * @param mesh The mesh that this bone is attached to
  84841. * @param result The vector3 that the world direction will be copied to
  84842. */
  84843. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  84844. if (mesh === void 0) { mesh = null; }
  84845. var wm = null;
  84846. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84847. if (mesh) {
  84848. wm = mesh.getWorldMatrix();
  84849. }
  84850. this._skeleton.computeAbsoluteTransforms();
  84851. var mat = Bone._tmpMats[0];
  84852. mat.copyFrom(this.getAbsoluteTransform());
  84853. if (mesh && wm) {
  84854. mat.multiplyToRef(wm, mat);
  84855. }
  84856. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  84857. result.normalize();
  84858. };
  84859. /**
  84860. * Get the euler rotation of the bone in local or world space
  84861. * @param space The space that the rotation should be in
  84862. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84863. * @returns The euler rotation
  84864. */
  84865. Bone.prototype.getRotation = function (space, mesh) {
  84866. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84867. if (mesh === void 0) { mesh = null; }
  84868. var result = BABYLON.Vector3.Zero();
  84869. this.getRotationToRef(space, mesh, result);
  84870. return result;
  84871. };
  84872. /**
  84873. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  84874. * @param space The space that the rotation should be in
  84875. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84876. * @param result The vector3 that the rotation should be copied to
  84877. */
  84878. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  84879. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84880. if (mesh === void 0) { mesh = null; }
  84881. var quat = Bone._tmpQuat;
  84882. this.getRotationQuaternionToRef(space, mesh, quat);
  84883. quat.toEulerAnglesToRef(result);
  84884. };
  84885. /**
  84886. * Get the quaternion rotation of the bone in either local or world space
  84887. * @param space The space that the rotation should be in
  84888. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84889. * @returns The quaternion rotation
  84890. */
  84891. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  84892. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84893. if (mesh === void 0) { mesh = null; }
  84894. var result = BABYLON.Quaternion.Identity();
  84895. this.getRotationQuaternionToRef(space, mesh, result);
  84896. return result;
  84897. };
  84898. /**
  84899. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  84900. * @param space The space that the rotation should be in
  84901. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84902. * @param result The quaternion that the rotation should be copied to
  84903. */
  84904. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  84905. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84906. if (mesh === void 0) { mesh = null; }
  84907. if (space == BABYLON.Space.LOCAL) {
  84908. this._decompose();
  84909. result.copyFrom(this._localRotation);
  84910. }
  84911. else {
  84912. var mat = Bone._tmpMats[0];
  84913. var amat = this.getAbsoluteTransform();
  84914. if (mesh) {
  84915. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  84916. }
  84917. else {
  84918. mat.copyFrom(amat);
  84919. }
  84920. mat.m[0] *= this._scalingDeterminant;
  84921. mat.m[1] *= this._scalingDeterminant;
  84922. mat.m[2] *= this._scalingDeterminant;
  84923. mat.decompose(undefined, result, undefined);
  84924. }
  84925. };
  84926. /**
  84927. * Get the rotation matrix of the bone in local or world space
  84928. * @param space The space that the rotation should be in
  84929. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84930. * @returns The rotation matrix
  84931. */
  84932. Bone.prototype.getRotationMatrix = function (space, mesh) {
  84933. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84934. var result = BABYLON.Matrix.Identity();
  84935. this.getRotationMatrixToRef(space, mesh, result);
  84936. return result;
  84937. };
  84938. /**
  84939. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  84940. * @param space The space that the rotation should be in
  84941. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84942. * @param result The quaternion that the rotation should be copied to
  84943. */
  84944. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  84945. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84946. if (space == BABYLON.Space.LOCAL) {
  84947. this.getLocalMatrix().getRotationMatrixToRef(result);
  84948. }
  84949. else {
  84950. var mat = Bone._tmpMats[0];
  84951. var amat = this.getAbsoluteTransform();
  84952. if (mesh) {
  84953. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  84954. }
  84955. else {
  84956. mat.copyFrom(amat);
  84957. }
  84958. mat.m[0] *= this._scalingDeterminant;
  84959. mat.m[1] *= this._scalingDeterminant;
  84960. mat.m[2] *= this._scalingDeterminant;
  84961. mat.getRotationMatrixToRef(result);
  84962. }
  84963. };
  84964. /**
  84965. * Get the world position of a point that is in the local space of the bone
  84966. * @param position The local position
  84967. * @param mesh The mesh that this bone is attached to
  84968. * @returns The world position
  84969. */
  84970. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  84971. if (mesh === void 0) { mesh = null; }
  84972. var result = BABYLON.Vector3.Zero();
  84973. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  84974. return result;
  84975. };
  84976. /**
  84977. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  84978. * @param position The local position
  84979. * @param mesh The mesh that this bone is attached to
  84980. * @param result The vector3 that the world position should be copied to
  84981. */
  84982. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  84983. if (mesh === void 0) { mesh = null; }
  84984. var wm = null;
  84985. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84986. if (mesh) {
  84987. wm = mesh.getWorldMatrix();
  84988. }
  84989. this._skeleton.computeAbsoluteTransforms();
  84990. var tmat = Bone._tmpMats[0];
  84991. if (mesh && wm) {
  84992. tmat.copyFrom(this.getAbsoluteTransform());
  84993. tmat.multiplyToRef(wm, tmat);
  84994. }
  84995. else {
  84996. tmat = this.getAbsoluteTransform();
  84997. }
  84998. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  84999. };
  85000. /**
  85001. * Get the local position of a point that is in world space
  85002. * @param position The world position
  85003. * @param mesh The mesh that this bone is attached to
  85004. * @returns The local position
  85005. */
  85006. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  85007. if (mesh === void 0) { mesh = null; }
  85008. var result = BABYLON.Vector3.Zero();
  85009. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  85010. return result;
  85011. };
  85012. /**
  85013. * Get the local position of a point that is in world space and copy it to the result param
  85014. * @param position The world position
  85015. * @param mesh The mesh that this bone is attached to
  85016. * @param result The vector3 that the local position should be copied to
  85017. */
  85018. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  85019. if (mesh === void 0) { mesh = null; }
  85020. var wm = null;
  85021. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  85022. if (mesh) {
  85023. wm = mesh.getWorldMatrix();
  85024. }
  85025. this._skeleton.computeAbsoluteTransforms();
  85026. var tmat = Bone._tmpMats[0];
  85027. tmat.copyFrom(this.getAbsoluteTransform());
  85028. if (mesh && wm) {
  85029. tmat.multiplyToRef(wm, tmat);
  85030. }
  85031. tmat.invert();
  85032. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  85033. };
  85034. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85035. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  85036. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85037. return Bone;
  85038. }(BABYLON.Node));
  85039. BABYLON.Bone = Bone;
  85040. })(BABYLON || (BABYLON = {}));
  85041. //# sourceMappingURL=babylon.bone.js.map
  85042. var BABYLON;
  85043. (function (BABYLON) {
  85044. /**
  85045. * Class used to apply inverse kinematics to bones
  85046. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  85047. */
  85048. var BoneIKController = /** @class */ (function () {
  85049. /**
  85050. * Creates a new BoneIKController
  85051. * @param mesh defines the mesh to control
  85052. * @param bone defines the bone to control
  85053. * @param options defines options to set up the controller
  85054. */
  85055. function BoneIKController(mesh, bone, options) {
  85056. /**
  85057. * Gets or sets the target position
  85058. */
  85059. this.targetPosition = BABYLON.Vector3.Zero();
  85060. /**
  85061. * Gets or sets the pole target position
  85062. */
  85063. this.poleTargetPosition = BABYLON.Vector3.Zero();
  85064. /**
  85065. * Gets or sets the pole target local offset
  85066. */
  85067. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  85068. /**
  85069. * Gets or sets the pole angle
  85070. */
  85071. this.poleAngle = 0;
  85072. /**
  85073. * 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)
  85074. */
  85075. this.slerpAmount = 1;
  85076. this._bone1Quat = BABYLON.Quaternion.Identity();
  85077. this._bone1Mat = BABYLON.Matrix.Identity();
  85078. this._bone2Ang = Math.PI;
  85079. this._maxAngle = Math.PI;
  85080. this._rightHandedSystem = false;
  85081. this._bendAxis = BABYLON.Vector3.Right();
  85082. this._slerping = false;
  85083. this._adjustRoll = 0;
  85084. this._bone2 = bone;
  85085. this._bone1 = bone.getParent();
  85086. if (!this._bone1) {
  85087. return;
  85088. }
  85089. this.mesh = mesh;
  85090. var bonePos = bone.getPosition();
  85091. if (bone.getAbsoluteTransform().determinant() > 0) {
  85092. this._rightHandedSystem = true;
  85093. this._bendAxis.x = 0;
  85094. this._bendAxis.y = 0;
  85095. this._bendAxis.z = -1;
  85096. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  85097. this._adjustRoll = Math.PI * .5;
  85098. this._bendAxis.z = 1;
  85099. }
  85100. }
  85101. if (this._bone1.length) {
  85102. var boneScale1 = this._bone1.getScale();
  85103. var boneScale2 = this._bone2.getScale();
  85104. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  85105. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  85106. }
  85107. else if (this._bone1.children[0]) {
  85108. mesh.computeWorldMatrix(true);
  85109. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  85110. var pos2 = this._bone2.getAbsolutePosition(mesh);
  85111. var pos3 = this._bone1.getAbsolutePosition(mesh);
  85112. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  85113. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  85114. }
  85115. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  85116. this.maxAngle = Math.PI;
  85117. if (options) {
  85118. if (options.targetMesh) {
  85119. this.targetMesh = options.targetMesh;
  85120. this.targetMesh.computeWorldMatrix(true);
  85121. }
  85122. if (options.poleTargetMesh) {
  85123. this.poleTargetMesh = options.poleTargetMesh;
  85124. this.poleTargetMesh.computeWorldMatrix(true);
  85125. }
  85126. else if (options.poleTargetBone) {
  85127. this.poleTargetBone = options.poleTargetBone;
  85128. }
  85129. else if (this._bone1.getParent()) {
  85130. this.poleTargetBone = this._bone1.getParent();
  85131. }
  85132. if (options.poleTargetLocalOffset) {
  85133. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  85134. }
  85135. if (options.poleAngle) {
  85136. this.poleAngle = options.poleAngle;
  85137. }
  85138. if (options.bendAxis) {
  85139. this._bendAxis.copyFrom(options.bendAxis);
  85140. }
  85141. if (options.maxAngle) {
  85142. this.maxAngle = options.maxAngle;
  85143. }
  85144. if (options.slerpAmount) {
  85145. this.slerpAmount = options.slerpAmount;
  85146. }
  85147. }
  85148. }
  85149. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  85150. /**
  85151. * Gets or sets maximum allowed angle
  85152. */
  85153. get: function () {
  85154. return this._maxAngle;
  85155. },
  85156. set: function (value) {
  85157. this._setMaxAngle(value);
  85158. },
  85159. enumerable: true,
  85160. configurable: true
  85161. });
  85162. BoneIKController.prototype._setMaxAngle = function (ang) {
  85163. if (ang < 0) {
  85164. ang = 0;
  85165. }
  85166. if (ang > Math.PI || ang == undefined) {
  85167. ang = Math.PI;
  85168. }
  85169. this._maxAngle = ang;
  85170. var a = this._bone1Length;
  85171. var b = this._bone2Length;
  85172. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  85173. };
  85174. /**
  85175. * Force the controller to update the bones
  85176. */
  85177. BoneIKController.prototype.update = function () {
  85178. var bone1 = this._bone1;
  85179. if (!bone1) {
  85180. return;
  85181. }
  85182. var target = this.targetPosition;
  85183. var poleTarget = this.poleTargetPosition;
  85184. var mat1 = BoneIKController._tmpMats[0];
  85185. var mat2 = BoneIKController._tmpMats[1];
  85186. if (this.targetMesh) {
  85187. target.copyFrom(this.targetMesh.getAbsolutePosition());
  85188. }
  85189. if (this.poleTargetBone) {
  85190. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  85191. }
  85192. else if (this.poleTargetMesh) {
  85193. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  85194. }
  85195. var bonePos = BoneIKController._tmpVecs[0];
  85196. var zaxis = BoneIKController._tmpVecs[1];
  85197. var xaxis = BoneIKController._tmpVecs[2];
  85198. var yaxis = BoneIKController._tmpVecs[3];
  85199. var upAxis = BoneIKController._tmpVecs[4];
  85200. var _tmpQuat = BoneIKController._tmpQuat;
  85201. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  85202. poleTarget.subtractToRef(bonePos, upAxis);
  85203. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  85204. upAxis.y = 1;
  85205. }
  85206. else {
  85207. upAxis.normalize();
  85208. }
  85209. target.subtractToRef(bonePos, yaxis);
  85210. yaxis.normalize();
  85211. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  85212. zaxis.normalize();
  85213. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  85214. xaxis.normalize();
  85215. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  85216. var a = this._bone1Length;
  85217. var b = this._bone2Length;
  85218. var c = BABYLON.Vector3.Distance(bonePos, target);
  85219. if (this._maxReach > 0) {
  85220. c = Math.min(this._maxReach, c);
  85221. }
  85222. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  85223. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  85224. if (acosa > 1) {
  85225. acosa = 1;
  85226. }
  85227. if (acosb > 1) {
  85228. acosb = 1;
  85229. }
  85230. if (acosa < -1) {
  85231. acosa = -1;
  85232. }
  85233. if (acosb < -1) {
  85234. acosb = -1;
  85235. }
  85236. var angA = Math.acos(acosa);
  85237. var angB = Math.acos(acosb);
  85238. var angC = -angA - angB;
  85239. if (this._rightHandedSystem) {
  85240. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  85241. mat2.multiplyToRef(mat1, mat1);
  85242. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  85243. mat2.multiplyToRef(mat1, mat1);
  85244. }
  85245. else {
  85246. var _tmpVec = BoneIKController._tmpVecs[5];
  85247. _tmpVec.copyFrom(this._bendAxis);
  85248. _tmpVec.x *= -1;
  85249. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  85250. mat2.multiplyToRef(mat1, mat1);
  85251. }
  85252. if (this.poleAngle) {
  85253. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  85254. mat1.multiplyToRef(mat2, mat1);
  85255. }
  85256. if (this._bone1) {
  85257. if (this.slerpAmount < 1) {
  85258. if (!this._slerping) {
  85259. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  85260. }
  85261. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  85262. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  85263. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  85264. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  85265. this._slerping = true;
  85266. }
  85267. else {
  85268. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  85269. this._bone1Mat.copyFrom(mat1);
  85270. this._slerping = false;
  85271. }
  85272. }
  85273. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  85274. this._bone2Ang = angC;
  85275. };
  85276. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85277. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  85278. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85279. return BoneIKController;
  85280. }());
  85281. BABYLON.BoneIKController = BoneIKController;
  85282. })(BABYLON || (BABYLON = {}));
  85283. //# sourceMappingURL=babylon.boneIKController.js.map
  85284. var BABYLON;
  85285. (function (BABYLON) {
  85286. /**
  85287. * Class used to make a bone look toward a point in space
  85288. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  85289. */
  85290. var BoneLookController = /** @class */ (function () {
  85291. /**
  85292. * Create a BoneLookController
  85293. * @param mesh the mesh that the bone belongs to
  85294. * @param bone the bone that will be looking to the target
  85295. * @param target the target Vector3 to look at
  85296. * @param settings optional settings:
  85297. * * maxYaw: the maximum angle the bone will yaw to
  85298. * * minYaw: the minimum angle the bone will yaw to
  85299. * * maxPitch: the maximum angle the bone will pitch to
  85300. * * minPitch: the minimum angle the bone will yaw to
  85301. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  85302. * * upAxis: the up axis of the coordinate system
  85303. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  85304. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  85305. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  85306. * * adjustYaw: used to make an adjustment to the yaw of the bone
  85307. * * adjustPitch: used to make an adjustment to the pitch of the bone
  85308. * * adjustRoll: used to make an adjustment to the roll of the bone
  85309. **/
  85310. function BoneLookController(mesh, bone, target, options) {
  85311. /**
  85312. * The up axis of the coordinate system that is used when the bone is rotated
  85313. */
  85314. this.upAxis = BABYLON.Vector3.Up();
  85315. /**
  85316. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  85317. */
  85318. this.upAxisSpace = BABYLON.Space.LOCAL;
  85319. /**
  85320. * Used to make an adjustment to the yaw of the bone
  85321. */
  85322. this.adjustYaw = 0;
  85323. /**
  85324. * Used to make an adjustment to the pitch of the bone
  85325. */
  85326. this.adjustPitch = 0;
  85327. /**
  85328. * Used to make an adjustment to the roll of the bone
  85329. */
  85330. this.adjustRoll = 0;
  85331. /**
  85332. * 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)
  85333. */
  85334. this.slerpAmount = 1;
  85335. this._boneQuat = BABYLON.Quaternion.Identity();
  85336. this._slerping = false;
  85337. this._firstFrameSkipped = false;
  85338. this._fowardAxis = BABYLON.Vector3.Forward();
  85339. this.mesh = mesh;
  85340. this.bone = bone;
  85341. this.target = target;
  85342. if (options) {
  85343. if (options.adjustYaw) {
  85344. this.adjustYaw = options.adjustYaw;
  85345. }
  85346. if (options.adjustPitch) {
  85347. this.adjustPitch = options.adjustPitch;
  85348. }
  85349. if (options.adjustRoll) {
  85350. this.adjustRoll = options.adjustRoll;
  85351. }
  85352. if (options.maxYaw != null) {
  85353. this.maxYaw = options.maxYaw;
  85354. }
  85355. else {
  85356. this.maxYaw = Math.PI;
  85357. }
  85358. if (options.minYaw != null) {
  85359. this.minYaw = options.minYaw;
  85360. }
  85361. else {
  85362. this.minYaw = -Math.PI;
  85363. }
  85364. if (options.maxPitch != null) {
  85365. this.maxPitch = options.maxPitch;
  85366. }
  85367. else {
  85368. this.maxPitch = Math.PI;
  85369. }
  85370. if (options.minPitch != null) {
  85371. this.minPitch = options.minPitch;
  85372. }
  85373. else {
  85374. this.minPitch = -Math.PI;
  85375. }
  85376. if (options.slerpAmount != null) {
  85377. this.slerpAmount = options.slerpAmount;
  85378. }
  85379. if (options.upAxis != null) {
  85380. this.upAxis = options.upAxis;
  85381. }
  85382. if (options.upAxisSpace != null) {
  85383. this.upAxisSpace = options.upAxisSpace;
  85384. }
  85385. if (options.yawAxis != null || options.pitchAxis != null) {
  85386. var newYawAxis = BABYLON.Axis.Y;
  85387. var newPitchAxis = BABYLON.Axis.X;
  85388. if (options.yawAxis != null) {
  85389. newYawAxis = options.yawAxis.clone();
  85390. newYawAxis.normalize();
  85391. }
  85392. if (options.pitchAxis != null) {
  85393. newPitchAxis = options.pitchAxis.clone();
  85394. newPitchAxis.normalize();
  85395. }
  85396. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  85397. this._transformYawPitch = BABYLON.Matrix.Identity();
  85398. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  85399. this._transformYawPitchInv = this._transformYawPitch.clone();
  85400. this._transformYawPitch.invert();
  85401. }
  85402. }
  85403. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  85404. this.upAxisSpace = BABYLON.Space.LOCAL;
  85405. }
  85406. }
  85407. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  85408. /**
  85409. * Gets or sets the minimum yaw angle that the bone can look to
  85410. */
  85411. get: function () {
  85412. return this._minYaw;
  85413. },
  85414. set: function (value) {
  85415. this._minYaw = value;
  85416. this._minYawSin = Math.sin(value);
  85417. this._minYawCos = Math.cos(value);
  85418. if (this._maxYaw != null) {
  85419. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  85420. this._yawRange = this._maxYaw - this._minYaw;
  85421. }
  85422. },
  85423. enumerable: true,
  85424. configurable: true
  85425. });
  85426. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  85427. /**
  85428. * Gets or sets the maximum yaw angle that the bone can look to
  85429. */
  85430. get: function () {
  85431. return this._maxYaw;
  85432. },
  85433. set: function (value) {
  85434. this._maxYaw = value;
  85435. this._maxYawSin = Math.sin(value);
  85436. this._maxYawCos = Math.cos(value);
  85437. if (this._minYaw != null) {
  85438. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  85439. this._yawRange = this._maxYaw - this._minYaw;
  85440. }
  85441. },
  85442. enumerable: true,
  85443. configurable: true
  85444. });
  85445. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  85446. /**
  85447. * Gets or sets the minimum pitch angle that the bone can look to
  85448. */
  85449. get: function () {
  85450. return this._minPitch;
  85451. },
  85452. set: function (value) {
  85453. this._minPitch = value;
  85454. this._minPitchTan = Math.tan(value);
  85455. },
  85456. enumerable: true,
  85457. configurable: true
  85458. });
  85459. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  85460. /**
  85461. * Gets or sets the maximum pitch angle that the bone can look to
  85462. */
  85463. get: function () {
  85464. return this._maxPitch;
  85465. },
  85466. set: function (value) {
  85467. this._maxPitch = value;
  85468. this._maxPitchTan = Math.tan(value);
  85469. },
  85470. enumerable: true,
  85471. configurable: true
  85472. });
  85473. /**
  85474. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  85475. */
  85476. BoneLookController.prototype.update = function () {
  85477. //skip the first frame when slerping so that the mesh rotation is correct
  85478. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  85479. this._firstFrameSkipped = true;
  85480. return;
  85481. }
  85482. var bone = this.bone;
  85483. var bonePos = BoneLookController._tmpVecs[0];
  85484. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  85485. var target = this.target;
  85486. var _tmpMat1 = BoneLookController._tmpMats[0];
  85487. var _tmpMat2 = BoneLookController._tmpMats[1];
  85488. var mesh = this.mesh;
  85489. var parentBone = bone.getParent();
  85490. var upAxis = BoneLookController._tmpVecs[1];
  85491. upAxis.copyFrom(this.upAxis);
  85492. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  85493. if (this._transformYawPitch) {
  85494. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  85495. }
  85496. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  85497. }
  85498. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  85499. mesh.getDirectionToRef(upAxis, upAxis);
  85500. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  85501. upAxis.normalize();
  85502. }
  85503. }
  85504. var checkYaw = false;
  85505. var checkPitch = false;
  85506. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  85507. checkYaw = true;
  85508. }
  85509. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  85510. checkPitch = true;
  85511. }
  85512. if (checkYaw || checkPitch) {
  85513. var spaceMat = BoneLookController._tmpMats[2];
  85514. var spaceMatInv = BoneLookController._tmpMats[3];
  85515. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  85516. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  85517. }
  85518. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  85519. spaceMat.copyFrom(mesh.getWorldMatrix());
  85520. }
  85521. else {
  85522. var forwardAxis = BoneLookController._tmpVecs[2];
  85523. forwardAxis.copyFrom(this._fowardAxis);
  85524. if (this._transformYawPitch) {
  85525. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  85526. }
  85527. if (parentBone) {
  85528. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  85529. }
  85530. else {
  85531. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  85532. }
  85533. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  85534. rightAxis.normalize();
  85535. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  85536. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  85537. }
  85538. spaceMat.invertToRef(spaceMatInv);
  85539. var xzlen = null;
  85540. if (checkPitch) {
  85541. var localTarget = BoneLookController._tmpVecs[3];
  85542. target.subtractToRef(bonePos, localTarget);
  85543. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  85544. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85545. var pitch = Math.atan2(localTarget.y, xzlen);
  85546. var newPitch = pitch;
  85547. if (pitch > this._maxPitch) {
  85548. localTarget.y = this._maxPitchTan * xzlen;
  85549. newPitch = this._maxPitch;
  85550. }
  85551. else if (pitch < this._minPitch) {
  85552. localTarget.y = this._minPitchTan * xzlen;
  85553. newPitch = this._minPitch;
  85554. }
  85555. if (pitch != newPitch) {
  85556. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  85557. localTarget.addInPlace(bonePos);
  85558. target = localTarget;
  85559. }
  85560. }
  85561. if (checkYaw) {
  85562. var localTarget = BoneLookController._tmpVecs[4];
  85563. target.subtractToRef(bonePos, localTarget);
  85564. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  85565. var yaw = Math.atan2(localTarget.x, localTarget.z);
  85566. var newYaw = yaw;
  85567. if (yaw > this._maxYaw || yaw < this._minYaw) {
  85568. if (xzlen == null) {
  85569. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85570. }
  85571. if (this._yawRange > Math.PI) {
  85572. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  85573. localTarget.z = this._maxYawCos * xzlen;
  85574. localTarget.x = this._maxYawSin * xzlen;
  85575. newYaw = this._maxYaw;
  85576. }
  85577. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  85578. localTarget.z = this._minYawCos * xzlen;
  85579. localTarget.x = this._minYawSin * xzlen;
  85580. newYaw = this._minYaw;
  85581. }
  85582. }
  85583. else {
  85584. if (yaw > this._maxYaw) {
  85585. localTarget.z = this._maxYawCos * xzlen;
  85586. localTarget.x = this._maxYawSin * xzlen;
  85587. newYaw = this._maxYaw;
  85588. }
  85589. else if (yaw < this._minYaw) {
  85590. localTarget.z = this._minYawCos * xzlen;
  85591. localTarget.x = this._minYawSin * xzlen;
  85592. newYaw = this._minYaw;
  85593. }
  85594. }
  85595. }
  85596. if (this._slerping && this._yawRange > Math.PI) {
  85597. //are we going to be crossing into the min/max region?
  85598. var boneFwd = BoneLookController._tmpVecs[8];
  85599. boneFwd.copyFrom(BABYLON.Axis.Z);
  85600. if (this._transformYawPitch) {
  85601. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  85602. }
  85603. var boneRotMat = BoneLookController._tmpMats[4];
  85604. this._boneQuat.toRotationMatrix(boneRotMat);
  85605. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  85606. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  85607. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  85608. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  85609. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  85610. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  85611. if (angBtwTar > angBtwMidYaw) {
  85612. if (xzlen == null) {
  85613. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85614. }
  85615. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  85616. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  85617. if (angBtwMin < angBtwMax) {
  85618. newYaw = boneYaw + Math.PI * .75;
  85619. localTarget.z = Math.cos(newYaw) * xzlen;
  85620. localTarget.x = Math.sin(newYaw) * xzlen;
  85621. }
  85622. else {
  85623. newYaw = boneYaw - Math.PI * .75;
  85624. localTarget.z = Math.cos(newYaw) * xzlen;
  85625. localTarget.x = Math.sin(newYaw) * xzlen;
  85626. }
  85627. }
  85628. }
  85629. if (yaw != newYaw) {
  85630. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  85631. localTarget.addInPlace(bonePos);
  85632. target = localTarget;
  85633. }
  85634. }
  85635. }
  85636. var zaxis = BoneLookController._tmpVecs[5];
  85637. var xaxis = BoneLookController._tmpVecs[6];
  85638. var yaxis = BoneLookController._tmpVecs[7];
  85639. var _tmpQuat = BoneLookController._tmpQuat;
  85640. target.subtractToRef(bonePos, zaxis);
  85641. zaxis.normalize();
  85642. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  85643. xaxis.normalize();
  85644. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  85645. yaxis.normalize();
  85646. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  85647. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  85648. return;
  85649. }
  85650. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  85651. return;
  85652. }
  85653. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  85654. return;
  85655. }
  85656. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  85657. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  85658. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  85659. }
  85660. if (this.slerpAmount < 1) {
  85661. if (!this._slerping) {
  85662. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  85663. }
  85664. if (this._transformYawPitch) {
  85665. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  85666. }
  85667. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  85668. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  85669. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  85670. this._slerping = true;
  85671. }
  85672. else {
  85673. if (this._transformYawPitch) {
  85674. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  85675. }
  85676. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  85677. this._slerping = false;
  85678. }
  85679. };
  85680. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  85681. var angDiff = ang2 - ang1;
  85682. angDiff %= Math.PI * 2;
  85683. if (angDiff > Math.PI) {
  85684. angDiff -= Math.PI * 2;
  85685. }
  85686. else if (angDiff < -Math.PI) {
  85687. angDiff += Math.PI * 2;
  85688. }
  85689. return angDiff;
  85690. };
  85691. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  85692. ang1 %= (2 * Math.PI);
  85693. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  85694. ang2 %= (2 * Math.PI);
  85695. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  85696. var ab = 0;
  85697. if (ang1 < ang2) {
  85698. ab = ang2 - ang1;
  85699. }
  85700. else {
  85701. ab = ang1 - ang2;
  85702. }
  85703. if (ab > Math.PI) {
  85704. ab = Math.PI * 2 - ab;
  85705. }
  85706. return ab;
  85707. };
  85708. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  85709. ang %= (2 * Math.PI);
  85710. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  85711. ang1 %= (2 * Math.PI);
  85712. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  85713. ang2 %= (2 * Math.PI);
  85714. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  85715. if (ang1 < ang2) {
  85716. if (ang > ang1 && ang < ang2) {
  85717. return true;
  85718. }
  85719. }
  85720. else {
  85721. if (ang > ang2 && ang < ang1) {
  85722. return true;
  85723. }
  85724. }
  85725. return false;
  85726. };
  85727. 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()];
  85728. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  85729. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85730. return BoneLookController;
  85731. }());
  85732. BABYLON.BoneLookController = BoneLookController;
  85733. })(BABYLON || (BABYLON = {}));
  85734. //# sourceMappingURL=babylon.boneLookController.js.map
  85735. var BABYLON;
  85736. (function (BABYLON) {
  85737. /**
  85738. * Class used to handle skinning animations
  85739. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  85740. */
  85741. var Skeleton = /** @class */ (function () {
  85742. /**
  85743. * Creates a new skeleton
  85744. * @param name defines the skeleton name
  85745. * @param id defines the skeleton Id
  85746. * @param scene defines the hosting scene
  85747. */
  85748. function Skeleton(
  85749. /** defines the skeleton name */
  85750. name,
  85751. /** defines the skeleton Id */
  85752. id, scene) {
  85753. this.name = name;
  85754. this.id = id;
  85755. /**
  85756. * Gets the list of child bones
  85757. */
  85758. this.bones = new Array();
  85759. /**
  85760. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  85761. */
  85762. this.needInitialSkinMatrix = false;
  85763. this._isDirty = true;
  85764. this._meshesWithPoseMatrix = new Array();
  85765. this._identity = BABYLON.Matrix.Identity();
  85766. this._ranges = {};
  85767. this._lastAbsoluteTransformsUpdateId = -1;
  85768. /**
  85769. * Specifies if the skeleton should be serialized
  85770. */
  85771. this.doNotSerialize = false;
  85772. this._animationPropertiesOverride = null;
  85773. // Events
  85774. /**
  85775. * An observable triggered before computing the skeleton's matrices
  85776. */
  85777. this.onBeforeComputeObservable = new BABYLON.Observable();
  85778. this.bones = [];
  85779. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85780. scene.skeletons.push(this);
  85781. //make sure it will recalculate the matrix next time prepare is called.
  85782. this._isDirty = true;
  85783. }
  85784. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  85785. /**
  85786. * Gets or sets the animation properties override
  85787. */
  85788. get: function () {
  85789. if (!this._animationPropertiesOverride) {
  85790. return this._scene.animationPropertiesOverride;
  85791. }
  85792. return this._animationPropertiesOverride;
  85793. },
  85794. set: function (value) {
  85795. this._animationPropertiesOverride = value;
  85796. },
  85797. enumerable: true,
  85798. configurable: true
  85799. });
  85800. // Members
  85801. /**
  85802. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  85803. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  85804. * @returns a Float32Array containing matrices data
  85805. */
  85806. Skeleton.prototype.getTransformMatrices = function (mesh) {
  85807. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  85808. return mesh._bonesTransformMatrices;
  85809. }
  85810. if (!this._transformMatrices) {
  85811. this.prepare();
  85812. }
  85813. return this._transformMatrices;
  85814. };
  85815. /**
  85816. * Gets the current hosting scene
  85817. * @returns a scene object
  85818. */
  85819. Skeleton.prototype.getScene = function () {
  85820. return this._scene;
  85821. };
  85822. // Methods
  85823. /**
  85824. * Gets a string representing the current skeleton data
  85825. * @param fullDetails defines a boolean indicating if we want a verbose version
  85826. * @returns a string representing the current skeleton data
  85827. */
  85828. Skeleton.prototype.toString = function (fullDetails) {
  85829. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  85830. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  85831. if (fullDetails) {
  85832. ret += ", Ranges: {";
  85833. var first = true;
  85834. for (var name_1 in this._ranges) {
  85835. if (first) {
  85836. ret += ", ";
  85837. first = false;
  85838. }
  85839. ret += name_1;
  85840. }
  85841. ret += "}";
  85842. }
  85843. return ret;
  85844. };
  85845. /**
  85846. * Get bone's index searching by name
  85847. * @param name defines bone's name to search for
  85848. * @return the indice of the bone. Returns -1 if not found
  85849. */
  85850. Skeleton.prototype.getBoneIndexByName = function (name) {
  85851. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  85852. if (this.bones[boneIndex].name === name) {
  85853. return boneIndex;
  85854. }
  85855. }
  85856. return -1;
  85857. };
  85858. /**
  85859. * Creater a new animation range
  85860. * @param name defines the name of the range
  85861. * @param from defines the start key
  85862. * @param to defines the end key
  85863. */
  85864. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  85865. // check name not already in use
  85866. if (!this._ranges[name]) {
  85867. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  85868. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85869. if (this.bones[i].animations[0]) {
  85870. this.bones[i].animations[0].createRange(name, from, to);
  85871. }
  85872. }
  85873. }
  85874. };
  85875. /**
  85876. * Delete a specific animation range
  85877. * @param name defines the name of the range
  85878. * @param deleteFrames defines if frames must be removed as well
  85879. */
  85880. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  85881. if (deleteFrames === void 0) { deleteFrames = true; }
  85882. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85883. if (this.bones[i].animations[0]) {
  85884. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  85885. }
  85886. }
  85887. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  85888. };
  85889. /**
  85890. * Gets a specific animation range
  85891. * @param name defines the name of the range to look for
  85892. * @returns the requested animation range or null if not found
  85893. */
  85894. Skeleton.prototype.getAnimationRange = function (name) {
  85895. return this._ranges[name];
  85896. };
  85897. /**
  85898. * Gets the list of all animation ranges defined on this skeleton
  85899. * @returns an array
  85900. */
  85901. Skeleton.prototype.getAnimationRanges = function () {
  85902. var animationRanges = [];
  85903. var name;
  85904. var i = 0;
  85905. for (name in this._ranges) {
  85906. animationRanges[i] = this._ranges[name];
  85907. i++;
  85908. }
  85909. return animationRanges;
  85910. };
  85911. /**
  85912. * Copy animation range from a source skeleton.
  85913. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  85914. * @param source defines the source skeleton
  85915. * @param name defines the name of the range to copy
  85916. * @param rescaleAsRequired defines if rescaling must be applied if required
  85917. * @returns true if operation was successful
  85918. */
  85919. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  85920. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  85921. if (this._ranges[name] || !source.getAnimationRange(name)) {
  85922. return false;
  85923. }
  85924. var ret = true;
  85925. var frameOffset = this._getHighestAnimationFrame() + 1;
  85926. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  85927. var boneDict = {};
  85928. var sourceBones = source.bones;
  85929. var nBones;
  85930. var i;
  85931. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  85932. boneDict[sourceBones[i].name] = sourceBones[i];
  85933. }
  85934. if (this.bones.length !== sourceBones.length) {
  85935. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  85936. ret = false;
  85937. }
  85938. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  85939. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  85940. var boneName = this.bones[i].name;
  85941. var sourceBone = boneDict[boneName];
  85942. if (sourceBone) {
  85943. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  85944. }
  85945. else {
  85946. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  85947. ret = false;
  85948. }
  85949. }
  85950. // do not call createAnimationRange(), since it also is done to bones, which was already done
  85951. var range = source.getAnimationRange(name);
  85952. if (range) {
  85953. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  85954. }
  85955. return ret;
  85956. };
  85957. /**
  85958. * Forces the skeleton to go to rest pose
  85959. */
  85960. Skeleton.prototype.returnToRest = function () {
  85961. for (var index = 0; index < this.bones.length; index++) {
  85962. this.bones[index].returnToRest();
  85963. }
  85964. };
  85965. Skeleton.prototype._getHighestAnimationFrame = function () {
  85966. var ret = 0;
  85967. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85968. if (this.bones[i].animations[0]) {
  85969. var highest = this.bones[i].animations[0].getHighestFrame();
  85970. if (ret < highest) {
  85971. ret = highest;
  85972. }
  85973. }
  85974. }
  85975. return ret;
  85976. };
  85977. /**
  85978. * Begin a specific animation range
  85979. * @param name defines the name of the range to start
  85980. * @param loop defines if looping must be turned on (false by default)
  85981. * @param speedRatio defines the speed ratio to apply (1 by default)
  85982. * @param onAnimationEnd defines a callback which will be called when animation will end
  85983. * @returns a new animatable
  85984. */
  85985. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  85986. var range = this.getAnimationRange(name);
  85987. if (!range) {
  85988. return null;
  85989. }
  85990. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  85991. };
  85992. /** @hidden */
  85993. Skeleton.prototype._markAsDirty = function () {
  85994. this._isDirty = true;
  85995. };
  85996. /** @hidden */
  85997. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  85998. this._meshesWithPoseMatrix.push(mesh);
  85999. };
  86000. /** @hidden */
  86001. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  86002. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  86003. if (index > -1) {
  86004. this._meshesWithPoseMatrix.splice(index, 1);
  86005. }
  86006. };
  86007. /** @hidden */
  86008. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  86009. this.onBeforeComputeObservable.notifyObservers(this);
  86010. for (var index = 0; index < this.bones.length; index++) {
  86011. var bone = this.bones[index];
  86012. var parentBone = bone.getParent();
  86013. if (parentBone) {
  86014. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  86015. }
  86016. else {
  86017. if (initialSkinMatrix) {
  86018. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  86019. }
  86020. else {
  86021. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  86022. }
  86023. }
  86024. if (bone._index !== -1) {
  86025. var mappedIndex = bone._index === null ? index : bone._index;
  86026. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  86027. }
  86028. }
  86029. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  86030. };
  86031. /**
  86032. * Build all resources required to render a skeleton
  86033. */
  86034. Skeleton.prototype.prepare = function () {
  86035. if (!this._isDirty) {
  86036. return;
  86037. }
  86038. if (this.needInitialSkinMatrix) {
  86039. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  86040. var mesh = this._meshesWithPoseMatrix[index];
  86041. var poseMatrix = mesh.getPoseMatrix();
  86042. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  86043. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86044. }
  86045. if (this._synchronizedWithMesh !== mesh) {
  86046. this._synchronizedWithMesh = mesh;
  86047. // Prepare bones
  86048. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  86049. var bone = this.bones[boneIndex];
  86050. if (!bone.getParent()) {
  86051. var matrix = bone.getBaseMatrix();
  86052. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  86053. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  86054. }
  86055. }
  86056. }
  86057. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  86058. }
  86059. }
  86060. else {
  86061. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  86062. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86063. }
  86064. this._computeTransformMatrices(this._transformMatrices, null);
  86065. }
  86066. this._isDirty = false;
  86067. this._scene._activeBones.addCount(this.bones.length, false);
  86068. };
  86069. /**
  86070. * Gets the list of animatables currently running for this skeleton
  86071. * @returns an array of animatables
  86072. */
  86073. Skeleton.prototype.getAnimatables = function () {
  86074. if (!this._animatables || this._animatables.length !== this.bones.length) {
  86075. this._animatables = [];
  86076. for (var index = 0; index < this.bones.length; index++) {
  86077. this._animatables.push(this.bones[index]);
  86078. }
  86079. }
  86080. return this._animatables;
  86081. };
  86082. /**
  86083. * Clone the current skeleton
  86084. * @param name defines the name of the new skeleton
  86085. * @param id defines the id of the enw skeleton
  86086. * @returns the new skeleton
  86087. */
  86088. Skeleton.prototype.clone = function (name, id) {
  86089. var result = new Skeleton(name, id || name, this._scene);
  86090. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86091. for (var index = 0; index < this.bones.length; index++) {
  86092. var source = this.bones[index];
  86093. var parentBone = null;
  86094. var parent_1 = source.getParent();
  86095. if (parent_1) {
  86096. var parentIndex = this.bones.indexOf(parent_1);
  86097. parentBone = result.bones[parentIndex];
  86098. }
  86099. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  86100. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  86101. }
  86102. if (this._ranges) {
  86103. result._ranges = {};
  86104. for (var rangeName in this._ranges) {
  86105. var range = this._ranges[rangeName];
  86106. if (range) {
  86107. result._ranges[rangeName] = range.clone();
  86108. }
  86109. }
  86110. }
  86111. this._isDirty = true;
  86112. return result;
  86113. };
  86114. /**
  86115. * Enable animation blending for this skeleton
  86116. * @param blendingSpeed defines the blending speed to apply
  86117. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  86118. */
  86119. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  86120. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  86121. this.bones.forEach(function (bone) {
  86122. bone.animations.forEach(function (animation) {
  86123. animation.enableBlending = true;
  86124. animation.blendingSpeed = blendingSpeed;
  86125. });
  86126. });
  86127. };
  86128. /**
  86129. * Releases all resources associated with the current skeleton
  86130. */
  86131. Skeleton.prototype.dispose = function () {
  86132. this._meshesWithPoseMatrix = [];
  86133. // Animations
  86134. this.getScene().stopAnimation(this);
  86135. // Remove from scene
  86136. this.getScene().removeSkeleton(this);
  86137. };
  86138. /**
  86139. * Serialize the skeleton in a JSON object
  86140. * @returns a JSON object
  86141. */
  86142. Skeleton.prototype.serialize = function () {
  86143. var serializationObject = {};
  86144. serializationObject.name = this.name;
  86145. serializationObject.id = this.id;
  86146. if (this.dimensionsAtRest) {
  86147. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  86148. }
  86149. serializationObject.bones = [];
  86150. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86151. for (var index = 0; index < this.bones.length; index++) {
  86152. var bone = this.bones[index];
  86153. var parent_2 = bone.getParent();
  86154. var serializedBone = {
  86155. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  86156. name: bone.name,
  86157. matrix: bone.getBaseMatrix().toArray(),
  86158. rest: bone.getRestPose().toArray()
  86159. };
  86160. serializationObject.bones.push(serializedBone);
  86161. if (bone.length) {
  86162. serializedBone.length = bone.length;
  86163. }
  86164. if (bone.metadata) {
  86165. serializedBone.metadata = bone.metadata;
  86166. }
  86167. if (bone.animations && bone.animations.length > 0) {
  86168. serializedBone.animation = bone.animations[0].serialize();
  86169. }
  86170. serializationObject.ranges = [];
  86171. for (var name in this._ranges) {
  86172. var source = this._ranges[name];
  86173. if (!source) {
  86174. continue;
  86175. }
  86176. var range = {};
  86177. range.name = name;
  86178. range.from = source.from;
  86179. range.to = source.to;
  86180. serializationObject.ranges.push(range);
  86181. }
  86182. }
  86183. return serializationObject;
  86184. };
  86185. /**
  86186. * Creates a new skeleton from serialized data
  86187. * @param parsedSkeleton defines the serialized data
  86188. * @param scene defines the hosting scene
  86189. * @returns a new skeleton
  86190. */
  86191. Skeleton.Parse = function (parsedSkeleton, scene) {
  86192. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  86193. if (parsedSkeleton.dimensionsAtRest) {
  86194. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  86195. }
  86196. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  86197. var index;
  86198. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  86199. var parsedBone = parsedSkeleton.bones[index];
  86200. var parentBone = null;
  86201. if (parsedBone.parentBoneIndex > -1) {
  86202. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  86203. }
  86204. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  86205. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  86206. if (parsedBone.length) {
  86207. bone.length = parsedBone.length;
  86208. }
  86209. if (parsedBone.metadata) {
  86210. bone.metadata = parsedBone.metadata;
  86211. }
  86212. if (parsedBone.animation) {
  86213. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  86214. }
  86215. }
  86216. // placed after bones, so createAnimationRange can cascade down
  86217. if (parsedSkeleton.ranges) {
  86218. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  86219. var data = parsedSkeleton.ranges[index];
  86220. skeleton.createAnimationRange(data.name, data.from, data.to);
  86221. }
  86222. }
  86223. return skeleton;
  86224. };
  86225. /**
  86226. * Compute all node absolute transforms
  86227. * @param forceUpdate defines if computation must be done even if cache is up to date
  86228. */
  86229. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  86230. if (forceUpdate === void 0) { forceUpdate = false; }
  86231. var renderId = this._scene.getRenderId();
  86232. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  86233. this.bones[0].computeAbsoluteTransforms();
  86234. this._lastAbsoluteTransformsUpdateId = renderId;
  86235. }
  86236. };
  86237. /**
  86238. * Gets the root pose matrix
  86239. * @returns a matrix
  86240. */
  86241. Skeleton.prototype.getPoseMatrix = function () {
  86242. var poseMatrix = null;
  86243. if (this._meshesWithPoseMatrix.length > 0) {
  86244. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  86245. }
  86246. return poseMatrix;
  86247. };
  86248. /**
  86249. * Sorts bones per internal index
  86250. */
  86251. Skeleton.prototype.sortBones = function () {
  86252. var bones = new Array();
  86253. var visited = new Array(this.bones.length);
  86254. for (var index = 0; index < this.bones.length; index++) {
  86255. this._sortBones(index, bones, visited);
  86256. }
  86257. this.bones = bones;
  86258. };
  86259. Skeleton.prototype._sortBones = function (index, bones, visited) {
  86260. if (visited[index]) {
  86261. return;
  86262. }
  86263. visited[index] = true;
  86264. var bone = this.bones[index];
  86265. if (bone._index === undefined) {
  86266. bone._index = index;
  86267. }
  86268. var parentBone = bone.getParent();
  86269. if (parentBone) {
  86270. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  86271. }
  86272. bones.push(bone);
  86273. };
  86274. return Skeleton;
  86275. }());
  86276. BABYLON.Skeleton = Skeleton;
  86277. })(BABYLON || (BABYLON = {}));
  86278. //# sourceMappingURL=babylon.skeleton.js.map
  86279. var BABYLON;
  86280. (function (BABYLON) {
  86281. ;
  86282. /**
  86283. * This groups tools to convert HDR texture to native colors array.
  86284. */
  86285. var HDRTools = /** @class */ (function () {
  86286. function HDRTools() {
  86287. }
  86288. HDRTools.Ldexp = function (mantissa, exponent) {
  86289. if (exponent > 1023) {
  86290. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  86291. }
  86292. if (exponent < -1074) {
  86293. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  86294. }
  86295. return mantissa * Math.pow(2, exponent);
  86296. };
  86297. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  86298. if (exponent > 0) { /*nonzero pixel*/
  86299. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  86300. float32array[index + 0] = red * exponent;
  86301. float32array[index + 1] = green * exponent;
  86302. float32array[index + 2] = blue * exponent;
  86303. }
  86304. else {
  86305. float32array[index + 0] = 0;
  86306. float32array[index + 1] = 0;
  86307. float32array[index + 2] = 0;
  86308. }
  86309. };
  86310. HDRTools.readStringLine = function (uint8array, startIndex) {
  86311. var line = "";
  86312. var character = "";
  86313. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  86314. character = String.fromCharCode(uint8array[i]);
  86315. if (character == "\n") {
  86316. break;
  86317. }
  86318. line += character;
  86319. }
  86320. return line;
  86321. };
  86322. /**
  86323. * Reads header information from an RGBE texture stored in a native array.
  86324. * More information on this format are available here:
  86325. * https://en.wikipedia.org/wiki/RGBE_image_format
  86326. *
  86327. * @param uint8array The binary file stored in native array.
  86328. * @return The header information.
  86329. */
  86330. HDRTools.RGBE_ReadHeader = function (uint8array) {
  86331. var height = 0;
  86332. var width = 0;
  86333. var line = this.readStringLine(uint8array, 0);
  86334. if (line[0] != '#' || line[1] != '?') {
  86335. throw "Bad HDR Format.";
  86336. }
  86337. var endOfHeader = false;
  86338. var findFormat = false;
  86339. var lineIndex = 0;
  86340. do {
  86341. lineIndex += (line.length + 1);
  86342. line = this.readStringLine(uint8array, lineIndex);
  86343. if (line == "FORMAT=32-bit_rle_rgbe") {
  86344. findFormat = true;
  86345. }
  86346. else if (line.length == 0) {
  86347. endOfHeader = true;
  86348. }
  86349. } while (!endOfHeader);
  86350. if (!findFormat) {
  86351. throw "HDR Bad header format, unsupported FORMAT";
  86352. }
  86353. lineIndex += (line.length + 1);
  86354. line = this.readStringLine(uint8array, lineIndex);
  86355. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  86356. var match = sizeRegexp.exec(line);
  86357. // TODO. Support +Y and -X if needed.
  86358. if (!match || match.length < 3) {
  86359. throw "HDR Bad header format, no size";
  86360. }
  86361. width = parseInt(match[2]);
  86362. height = parseInt(match[1]);
  86363. if (width < 8 || width > 0x7fff) {
  86364. throw "HDR Bad header format, unsupported size";
  86365. }
  86366. lineIndex += (line.length + 1);
  86367. return {
  86368. height: height,
  86369. width: width,
  86370. dataPosition: lineIndex
  86371. };
  86372. };
  86373. /**
  86374. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  86375. * This RGBE texture needs to store the information as a panorama.
  86376. *
  86377. * More information on this format are available here:
  86378. * https://en.wikipedia.org/wiki/RGBE_image_format
  86379. *
  86380. * @param buffer The binary file stored in an array buffer.
  86381. * @param size The expected size of the extracted cubemap.
  86382. * @return The Cube Map information.
  86383. */
  86384. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  86385. var uint8array = new Uint8Array(buffer);
  86386. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  86387. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86388. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  86389. return cubeMapData;
  86390. };
  86391. /**
  86392. * Returns the pixels data extracted from an RGBE texture.
  86393. * This pixels will be stored left to right up to down in the R G B order in one array.
  86394. *
  86395. * More information on this format are available here:
  86396. * https://en.wikipedia.org/wiki/RGBE_image_format
  86397. *
  86398. * @param uint8array The binary file stored in an array buffer.
  86399. * @param hdrInfo The header information of the file.
  86400. * @return The pixels data in RGB right to left up to down order.
  86401. */
  86402. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  86403. // Keep for multi format supports.
  86404. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86405. };
  86406. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  86407. var num_scanlines = hdrInfo.height;
  86408. var scanline_width = hdrInfo.width;
  86409. var a, b, c, d, count;
  86410. var dataIndex = hdrInfo.dataPosition;
  86411. var index = 0, endIndex = 0, i = 0;
  86412. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  86413. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  86414. // 3 channels of 4 bytes per pixel in float.
  86415. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  86416. var resultArray = new Float32Array(resultBuffer);
  86417. // read in each successive scanline
  86418. while (num_scanlines > 0) {
  86419. a = uint8array[dataIndex++];
  86420. b = uint8array[dataIndex++];
  86421. c = uint8array[dataIndex++];
  86422. d = uint8array[dataIndex++];
  86423. if (a != 2 || b != 2 || (c & 0x80)) {
  86424. // this file is not run length encoded
  86425. throw "HDR Bad header format, not RLE";
  86426. }
  86427. if (((c << 8) | d) != scanline_width) {
  86428. throw "HDR Bad header format, wrong scan line width";
  86429. }
  86430. index = 0;
  86431. // read each of the four channels for the scanline into the buffer
  86432. for (i = 0; i < 4; i++) {
  86433. endIndex = (i + 1) * scanline_width;
  86434. while (index < endIndex) {
  86435. a = uint8array[dataIndex++];
  86436. b = uint8array[dataIndex++];
  86437. if (a > 128) {
  86438. // a run of the same value
  86439. count = a - 128;
  86440. if ((count == 0) || (count > endIndex - index)) {
  86441. throw "HDR Bad Format, bad scanline data (run)";
  86442. }
  86443. while (count-- > 0) {
  86444. scanLineArray[index++] = b;
  86445. }
  86446. }
  86447. else {
  86448. // a non-run
  86449. count = a;
  86450. if ((count == 0) || (count > endIndex - index)) {
  86451. throw "HDR Bad Format, bad scanline data (non-run)";
  86452. }
  86453. scanLineArray[index++] = b;
  86454. if (--count > 0) {
  86455. for (var j = 0; j < count; j++) {
  86456. scanLineArray[index++] = uint8array[dataIndex++];
  86457. }
  86458. }
  86459. }
  86460. }
  86461. }
  86462. // now convert data from buffer into floats
  86463. for (i = 0; i < scanline_width; i++) {
  86464. a = scanLineArray[i];
  86465. b = scanLineArray[i + scanline_width];
  86466. c = scanLineArray[i + 2 * scanline_width];
  86467. d = scanLineArray[i + 3 * scanline_width];
  86468. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  86469. }
  86470. num_scanlines--;
  86471. }
  86472. return resultArray;
  86473. };
  86474. return HDRTools;
  86475. }());
  86476. BABYLON.HDRTools = HDRTools;
  86477. })(BABYLON || (BABYLON = {}));
  86478. //# sourceMappingURL=babylon.hdr.js.map
  86479. var BABYLON;
  86480. (function (BABYLON) {
  86481. /**
  86482. * This represents a texture coming from an HDR input.
  86483. *
  86484. * The only supported format is currently panorama picture stored in RGBE format.
  86485. * Example of such files can be found on HDRLib: http://hdrlib.com/
  86486. */
  86487. var HDRCubeTexture = /** @class */ (function (_super) {
  86488. __extends(HDRCubeTexture, _super);
  86489. /**
  86490. * Instantiates an HDRTexture from the following parameters.
  86491. *
  86492. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  86493. * @param scene The scene the texture will be used in
  86494. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  86495. * @param noMipmap Forces to not generate the mipmap if true
  86496. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  86497. * @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)
  86498. * @param reserved Reserved flag for internal use.
  86499. */
  86500. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  86501. if (noMipmap === void 0) { noMipmap = false; }
  86502. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86503. if (gammaSpace === void 0) { gammaSpace = false; }
  86504. if (reserved === void 0) { reserved = false; }
  86505. if (onLoad === void 0) { onLoad = null; }
  86506. if (onError === void 0) { onError = null; }
  86507. var _this = _super.call(this, scene) || this;
  86508. _this._generateHarmonics = true;
  86509. _this._onLoad = null;
  86510. _this._onError = null;
  86511. /**
  86512. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  86513. */
  86514. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  86515. _this._isBlocking = true;
  86516. _this._rotationY = 0;
  86517. /**
  86518. * Gets or sets the center of the bounding box associated with the cube texture
  86519. * It must define where the camera used to render the texture was set
  86520. */
  86521. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  86522. if (!url) {
  86523. return _this;
  86524. }
  86525. _this.name = url;
  86526. _this.url = url;
  86527. _this.hasAlpha = false;
  86528. _this.isCube = true;
  86529. _this._textureMatrix = BABYLON.Matrix.Identity();
  86530. _this._onLoad = onLoad;
  86531. _this._onError = onError;
  86532. _this.gammaSpace = gammaSpace;
  86533. _this._noMipmap = noMipmap;
  86534. _this._size = size;
  86535. _this._texture = _this._getFromCache(url, _this._noMipmap);
  86536. if (!_this._texture) {
  86537. if (!scene.useDelayedTextureLoading) {
  86538. _this.loadTexture();
  86539. }
  86540. else {
  86541. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  86542. }
  86543. }
  86544. return _this;
  86545. }
  86546. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  86547. /**
  86548. * Gets wether or not the texture is blocking during loading.
  86549. */
  86550. get: function () {
  86551. return this._isBlocking;
  86552. },
  86553. /**
  86554. * Sets wether or not the texture is blocking during loading.
  86555. */
  86556. set: function (value) {
  86557. this._isBlocking = value;
  86558. },
  86559. enumerable: true,
  86560. configurable: true
  86561. });
  86562. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  86563. /**
  86564. * Gets texture matrix rotation angle around Y axis radians.
  86565. */
  86566. get: function () {
  86567. return this._rotationY;
  86568. },
  86569. /**
  86570. * Sets texture matrix rotation angle around Y axis in radians.
  86571. */
  86572. set: function (value) {
  86573. this._rotationY = value;
  86574. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  86575. },
  86576. enumerable: true,
  86577. configurable: true
  86578. });
  86579. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  86580. get: function () {
  86581. return this._boundingBoxSize;
  86582. },
  86583. /**
  86584. * Gets or sets the size of the bounding box associated with the cube texture
  86585. * When defined, the cubemap will switch to local mode
  86586. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  86587. * @example https://www.babylonjs-playground.com/#RNASML
  86588. */
  86589. set: function (value) {
  86590. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  86591. return;
  86592. }
  86593. this._boundingBoxSize = value;
  86594. var scene = this.getScene();
  86595. if (scene) {
  86596. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  86597. }
  86598. },
  86599. enumerable: true,
  86600. configurable: true
  86601. });
  86602. /**
  86603. * Occurs when the file is raw .hdr file.
  86604. */
  86605. HDRCubeTexture.prototype.loadTexture = function () {
  86606. var _this = this;
  86607. var callback = function (buffer) {
  86608. _this.lodGenerationOffset = 0.0;
  86609. _this.lodGenerationScale = 0.8;
  86610. var scene = _this.getScene();
  86611. if (!scene) {
  86612. return null;
  86613. }
  86614. // Extract the raw linear data.
  86615. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  86616. // Generate harmonics if needed.
  86617. if (_this._generateHarmonics) {
  86618. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  86619. _this.sphericalPolynomial = sphericalPolynomial;
  86620. }
  86621. var results = [];
  86622. var byteArray = null;
  86623. // Push each faces.
  86624. for (var j = 0; j < 6; j++) {
  86625. // Create uintarray fallback.
  86626. if (!scene.getEngine().getCaps().textureFloat) {
  86627. // 3 channels of 1 bytes per pixel in bytes.
  86628. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  86629. byteArray = new Uint8Array(byteBuffer);
  86630. }
  86631. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  86632. // If special cases.
  86633. if (_this.gammaSpace || byteArray) {
  86634. for (var i = 0; i < _this._size * _this._size; i++) {
  86635. // Put in gamma space if requested.
  86636. if (_this.gammaSpace) {
  86637. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  86638. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  86639. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  86640. }
  86641. // Convert to int texture for fallback.
  86642. if (byteArray) {
  86643. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  86644. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  86645. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  86646. // May use luminance instead if the result is not accurate.
  86647. var max = Math.max(Math.max(r, g), b);
  86648. if (max > 255) {
  86649. var scale = 255 / max;
  86650. r *= scale;
  86651. g *= scale;
  86652. b *= scale;
  86653. }
  86654. byteArray[(i * 3) + 0] = r;
  86655. byteArray[(i * 3) + 1] = g;
  86656. byteArray[(i * 3) + 2] = b;
  86657. }
  86658. }
  86659. }
  86660. if (byteArray) {
  86661. results.push(byteArray);
  86662. }
  86663. else {
  86664. results.push(dataFace);
  86665. }
  86666. }
  86667. return results;
  86668. };
  86669. var scene = this.getScene();
  86670. if (scene) {
  86671. 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);
  86672. }
  86673. };
  86674. HDRCubeTexture.prototype.clone = function () {
  86675. var scene = this.getScene();
  86676. if (!scene) {
  86677. return this;
  86678. }
  86679. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  86680. // Base texture
  86681. newTexture.level = this.level;
  86682. newTexture.wrapU = this.wrapU;
  86683. newTexture.wrapV = this.wrapV;
  86684. newTexture.coordinatesIndex = this.coordinatesIndex;
  86685. newTexture.coordinatesMode = this.coordinatesMode;
  86686. return newTexture;
  86687. };
  86688. // Methods
  86689. HDRCubeTexture.prototype.delayLoad = function () {
  86690. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  86691. return;
  86692. }
  86693. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  86694. this._texture = this._getFromCache(this.url, this._noMipmap);
  86695. if (!this._texture) {
  86696. this.loadTexture();
  86697. }
  86698. };
  86699. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  86700. return this._textureMatrix;
  86701. };
  86702. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  86703. this._textureMatrix = value;
  86704. };
  86705. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  86706. var texture = null;
  86707. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  86708. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  86709. texture.name = parsedTexture.name;
  86710. texture.hasAlpha = parsedTexture.hasAlpha;
  86711. texture.level = parsedTexture.level;
  86712. texture.coordinatesMode = parsedTexture.coordinatesMode;
  86713. texture.isBlocking = parsedTexture.isBlocking;
  86714. }
  86715. if (texture) {
  86716. if (parsedTexture.boundingBoxPosition) {
  86717. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  86718. }
  86719. if (parsedTexture.boundingBoxSize) {
  86720. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  86721. }
  86722. if (parsedTexture.rotationY) {
  86723. texture.rotationY = parsedTexture.rotationY;
  86724. }
  86725. }
  86726. return texture;
  86727. };
  86728. HDRCubeTexture.prototype.serialize = function () {
  86729. if (!this.name) {
  86730. return null;
  86731. }
  86732. var serializationObject = {};
  86733. serializationObject.name = this.name;
  86734. serializationObject.hasAlpha = this.hasAlpha;
  86735. serializationObject.isCube = true;
  86736. serializationObject.level = this.level;
  86737. serializationObject.size = this._size;
  86738. serializationObject.coordinatesMode = this.coordinatesMode;
  86739. serializationObject.useInGammaSpace = this.gammaSpace;
  86740. serializationObject.generateHarmonics = this._generateHarmonics;
  86741. serializationObject.customType = "BABYLON.HDRCubeTexture";
  86742. serializationObject.noMipmap = this._noMipmap;
  86743. serializationObject.isBlocking = this._isBlocking;
  86744. serializationObject.rotationY = this._rotationY;
  86745. return serializationObject;
  86746. };
  86747. HDRCubeTexture._facesMapping = [
  86748. "right",
  86749. "left",
  86750. "up",
  86751. "down",
  86752. "front",
  86753. "back"
  86754. ];
  86755. return HDRCubeTexture;
  86756. }(BABYLON.BaseTexture));
  86757. BABYLON.HDRCubeTexture = HDRCubeTexture;
  86758. })(BABYLON || (BABYLON = {}));
  86759. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  86760. var BABYLON;
  86761. (function (BABYLON) {
  86762. /**
  86763. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  86764. */
  86765. var PanoramaToCubeMapTools = /** @class */ (function () {
  86766. function PanoramaToCubeMapTools() {
  86767. }
  86768. /**
  86769. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  86770. *
  86771. * @param float32Array The source data.
  86772. * @param inputWidth The width of the input panorama.
  86773. * @param inputhHeight The height of the input panorama.
  86774. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  86775. * @return The cubemap data
  86776. */
  86777. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  86778. if (!float32Array) {
  86779. throw "ConvertPanoramaToCubemap: input cannot be null";
  86780. }
  86781. if (float32Array.length != inputWidth * inputHeight * 3) {
  86782. throw "ConvertPanoramaToCubemap: input size is wrong";
  86783. }
  86784. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  86785. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  86786. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  86787. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  86788. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  86789. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  86790. return {
  86791. front: textureFront,
  86792. back: textureBack,
  86793. left: textureLeft,
  86794. right: textureRight,
  86795. up: textureUp,
  86796. down: textureDown,
  86797. size: size,
  86798. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86799. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  86800. gammaSpace: false,
  86801. };
  86802. };
  86803. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  86804. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  86805. var textureArray = new Float32Array(buffer);
  86806. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  86807. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  86808. var dy = 1 / texSize;
  86809. var fy = 0;
  86810. for (var y = 0; y < texSize; y++) {
  86811. var xv1 = faceData[0];
  86812. var xv2 = faceData[2];
  86813. for (var x = 0; x < texSize; x++) {
  86814. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  86815. v.normalize();
  86816. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  86817. // 3 channels per pixels
  86818. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  86819. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  86820. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  86821. xv1 = xv1.add(rotDX1);
  86822. xv2 = xv2.add(rotDX2);
  86823. }
  86824. fy += dy;
  86825. }
  86826. return textureArray;
  86827. };
  86828. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  86829. var theta = Math.atan2(vDir.z, vDir.x);
  86830. var phi = Math.acos(vDir.y);
  86831. while (theta < -Math.PI)
  86832. theta += 2 * Math.PI;
  86833. while (theta > Math.PI)
  86834. theta -= 2 * Math.PI;
  86835. var dx = theta / Math.PI;
  86836. var dy = phi / Math.PI;
  86837. // recenter.
  86838. dx = dx * 0.5 + 0.5;
  86839. var px = Math.round(dx * inputWidth);
  86840. if (px < 0)
  86841. px = 0;
  86842. else if (px >= inputWidth)
  86843. px = inputWidth - 1;
  86844. var py = Math.round(dy * inputHeight);
  86845. if (py < 0)
  86846. py = 0;
  86847. else if (py >= inputHeight)
  86848. py = inputHeight - 1;
  86849. var inputY = (inputHeight - py - 1);
  86850. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  86851. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  86852. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  86853. return {
  86854. r: r,
  86855. g: g,
  86856. b: b
  86857. };
  86858. };
  86859. PanoramaToCubeMapTools.FACE_FRONT = [
  86860. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86861. new BABYLON.Vector3(1.0, -1.0, -1.0),
  86862. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  86863. new BABYLON.Vector3(1.0, 1.0, -1.0)
  86864. ];
  86865. PanoramaToCubeMapTools.FACE_BACK = [
  86866. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86867. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86868. new BABYLON.Vector3(1.0, 1.0, 1.0),
  86869. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  86870. ];
  86871. PanoramaToCubeMapTools.FACE_RIGHT = [
  86872. new BABYLON.Vector3(1.0, -1.0, -1.0),
  86873. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86874. new BABYLON.Vector3(1.0, 1.0, -1.0),
  86875. new BABYLON.Vector3(1.0, 1.0, 1.0)
  86876. ];
  86877. PanoramaToCubeMapTools.FACE_LEFT = [
  86878. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86879. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86880. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  86881. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  86882. ];
  86883. PanoramaToCubeMapTools.FACE_DOWN = [
  86884. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  86885. new BABYLON.Vector3(1.0, 1.0, -1.0),
  86886. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  86887. new BABYLON.Vector3(1.0, 1.0, 1.0)
  86888. ];
  86889. PanoramaToCubeMapTools.FACE_UP = [
  86890. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86891. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86892. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86893. new BABYLON.Vector3(1.0, -1.0, -1.0)
  86894. ];
  86895. return PanoramaToCubeMapTools;
  86896. }());
  86897. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  86898. })(BABYLON || (BABYLON = {}));
  86899. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  86900. var BABYLON;
  86901. (function (BABYLON) {
  86902. var IndexedVector2 = /** @class */ (function (_super) {
  86903. __extends(IndexedVector2, _super);
  86904. function IndexedVector2(original, index) {
  86905. var _this = _super.call(this, original.x, original.y) || this;
  86906. _this.index = index;
  86907. return _this;
  86908. }
  86909. return IndexedVector2;
  86910. }(BABYLON.Vector2));
  86911. var PolygonPoints = /** @class */ (function () {
  86912. function PolygonPoints() {
  86913. this.elements = new Array();
  86914. }
  86915. PolygonPoints.prototype.add = function (originalPoints) {
  86916. var _this = this;
  86917. var result = new Array();
  86918. originalPoints.forEach(function (point) {
  86919. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  86920. var newPoint = new IndexedVector2(point, _this.elements.length);
  86921. result.push(newPoint);
  86922. _this.elements.push(newPoint);
  86923. }
  86924. });
  86925. return result;
  86926. };
  86927. PolygonPoints.prototype.computeBounds = function () {
  86928. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  86929. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  86930. this.elements.forEach(function (point) {
  86931. // x
  86932. if (point.x < lmin.x) {
  86933. lmin.x = point.x;
  86934. }
  86935. else if (point.x > lmax.x) {
  86936. lmax.x = point.x;
  86937. }
  86938. // y
  86939. if (point.y < lmin.y) {
  86940. lmin.y = point.y;
  86941. }
  86942. else if (point.y > lmax.y) {
  86943. lmax.y = point.y;
  86944. }
  86945. });
  86946. return {
  86947. min: lmin,
  86948. max: lmax,
  86949. width: lmax.x - lmin.x,
  86950. height: lmax.y - lmin.y
  86951. };
  86952. };
  86953. return PolygonPoints;
  86954. }());
  86955. var Polygon = /** @class */ (function () {
  86956. function Polygon() {
  86957. }
  86958. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  86959. return [
  86960. new BABYLON.Vector2(xmin, ymin),
  86961. new BABYLON.Vector2(xmax, ymin),
  86962. new BABYLON.Vector2(xmax, ymax),
  86963. new BABYLON.Vector2(xmin, ymax)
  86964. ];
  86965. };
  86966. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  86967. if (cx === void 0) { cx = 0; }
  86968. if (cy === void 0) { cy = 0; }
  86969. if (numberOfSides === void 0) { numberOfSides = 32; }
  86970. var result = new Array();
  86971. var angle = 0;
  86972. var increment = (Math.PI * 2) / numberOfSides;
  86973. for (var i = 0; i < numberOfSides; i++) {
  86974. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  86975. angle -= increment;
  86976. }
  86977. return result;
  86978. };
  86979. Polygon.Parse = function (input) {
  86980. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  86981. var i, result = [];
  86982. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  86983. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  86984. }
  86985. return result;
  86986. };
  86987. Polygon.StartingAt = function (x, y) {
  86988. return BABYLON.Path2.StartingAt(x, y);
  86989. };
  86990. return Polygon;
  86991. }());
  86992. BABYLON.Polygon = Polygon;
  86993. var PolygonMeshBuilder = /** @class */ (function () {
  86994. function PolygonMeshBuilder(name, contours, scene) {
  86995. this._points = new PolygonPoints();
  86996. this._outlinepoints = new PolygonPoints();
  86997. this._holes = new Array();
  86998. this._epoints = new Array();
  86999. this._eholes = new Array();
  87000. this._name = name;
  87001. this._scene = scene;
  87002. var points;
  87003. if (contours instanceof BABYLON.Path2) {
  87004. points = contours.getPoints();
  87005. }
  87006. else {
  87007. points = contours;
  87008. }
  87009. this._addToepoint(points);
  87010. this._points.add(points);
  87011. this._outlinepoints.add(points);
  87012. if (typeof earcut === 'undefined') {
  87013. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  87014. }
  87015. }
  87016. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  87017. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  87018. var p = points_1[_i];
  87019. this._epoints.push(p.x, p.y);
  87020. }
  87021. };
  87022. PolygonMeshBuilder.prototype.addHole = function (hole) {
  87023. this._points.add(hole);
  87024. var holepoints = new PolygonPoints();
  87025. holepoints.add(hole);
  87026. this._holes.push(holepoints);
  87027. this._eholes.push(this._epoints.length / 2);
  87028. this._addToepoint(hole);
  87029. return this;
  87030. };
  87031. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  87032. var _this = this;
  87033. if (updatable === void 0) { updatable = false; }
  87034. if (depth === void 0) { depth = 0; }
  87035. var result = new BABYLON.Mesh(this._name, this._scene);
  87036. var normals = new Array();
  87037. var positions = new Array();
  87038. var uvs = new Array();
  87039. var bounds = this._points.computeBounds();
  87040. this._points.elements.forEach(function (p) {
  87041. normals.push(0, 1.0, 0);
  87042. positions.push(p.x, 0, p.y);
  87043. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  87044. });
  87045. var indices = new Array();
  87046. var res = earcut(this._epoints, this._eholes, 2);
  87047. for (var i = 0; i < res.length; i++) {
  87048. indices.push(res[i]);
  87049. }
  87050. if (depth > 0) {
  87051. var positionscount = (positions.length / 3); //get the current pointcount
  87052. this._points.elements.forEach(function (p) {
  87053. normals.push(0, -1.0, 0);
  87054. positions.push(p.x, -depth, p.y);
  87055. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  87056. });
  87057. var totalCount = indices.length;
  87058. for (var i = 0; i < totalCount; i += 3) {
  87059. var i0 = indices[i + 0];
  87060. var i1 = indices[i + 1];
  87061. var i2 = indices[i + 2];
  87062. indices.push(i2 + positionscount);
  87063. indices.push(i1 + positionscount);
  87064. indices.push(i0 + positionscount);
  87065. }
  87066. //Add the sides
  87067. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  87068. this._holes.forEach(function (hole) {
  87069. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  87070. });
  87071. }
  87072. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  87073. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  87074. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  87075. result.setIndices(indices);
  87076. return result;
  87077. };
  87078. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  87079. var StartIndex = positions.length / 3;
  87080. var ulength = 0;
  87081. for (var i = 0; i < points.elements.length; i++) {
  87082. var p = points.elements[i];
  87083. var p1;
  87084. if ((i + 1) > points.elements.length - 1) {
  87085. p1 = points.elements[0];
  87086. }
  87087. else {
  87088. p1 = points.elements[i + 1];
  87089. }
  87090. positions.push(p.x, 0, p.y);
  87091. positions.push(p.x, -depth, p.y);
  87092. positions.push(p1.x, 0, p1.y);
  87093. positions.push(p1.x, -depth, p1.y);
  87094. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  87095. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  87096. var v3 = v2.subtract(v1);
  87097. var v4 = new BABYLON.Vector3(0, 1, 0);
  87098. var vn = BABYLON.Vector3.Cross(v3, v4);
  87099. vn = vn.normalize();
  87100. uvs.push(ulength / bounds.width, 0);
  87101. uvs.push(ulength / bounds.width, 1);
  87102. ulength += v3.length();
  87103. uvs.push((ulength / bounds.width), 0);
  87104. uvs.push((ulength / bounds.width), 1);
  87105. if (!flip) {
  87106. normals.push(-vn.x, -vn.y, -vn.z);
  87107. normals.push(-vn.x, -vn.y, -vn.z);
  87108. normals.push(-vn.x, -vn.y, -vn.z);
  87109. normals.push(-vn.x, -vn.y, -vn.z);
  87110. indices.push(StartIndex);
  87111. indices.push(StartIndex + 1);
  87112. indices.push(StartIndex + 2);
  87113. indices.push(StartIndex + 1);
  87114. indices.push(StartIndex + 3);
  87115. indices.push(StartIndex + 2);
  87116. }
  87117. else {
  87118. normals.push(vn.x, vn.y, vn.z);
  87119. normals.push(vn.x, vn.y, vn.z);
  87120. normals.push(vn.x, vn.y, vn.z);
  87121. normals.push(vn.x, vn.y, vn.z);
  87122. indices.push(StartIndex);
  87123. indices.push(StartIndex + 2);
  87124. indices.push(StartIndex + 1);
  87125. indices.push(StartIndex + 1);
  87126. indices.push(StartIndex + 2);
  87127. indices.push(StartIndex + 3);
  87128. }
  87129. StartIndex += 4;
  87130. }
  87131. ;
  87132. };
  87133. return PolygonMeshBuilder;
  87134. }());
  87135. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  87136. })(BABYLON || (BABYLON = {}));
  87137. //# sourceMappingURL=babylon.polygonMesh.js.map
  87138. var BABYLON;
  87139. (function (BABYLON) {
  87140. // Unique ID when we import meshes from Babylon to CSG
  87141. var currentCSGMeshId = 0;
  87142. // # class Vertex
  87143. // Represents a vertex of a polygon. Use your own vertex class instead of this
  87144. // one to provide additional features like texture coordinates and vertex
  87145. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  87146. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  87147. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  87148. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  87149. // is not used anywhere else.
  87150. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  87151. var Vertex = /** @class */ (function () {
  87152. function Vertex(pos, normal, uv) {
  87153. this.pos = pos;
  87154. this.normal = normal;
  87155. this.uv = uv;
  87156. }
  87157. Vertex.prototype.clone = function () {
  87158. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  87159. };
  87160. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  87161. // orientation of a polygon is flipped.
  87162. Vertex.prototype.flip = function () {
  87163. this.normal = this.normal.scale(-1);
  87164. };
  87165. // Create a new vertex between this vertex and `other` by linearly
  87166. // interpolating all properties using a parameter of `t`. Subclasses should
  87167. // override this to interpolate additional properties.
  87168. Vertex.prototype.interpolate = function (other, t) {
  87169. 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));
  87170. };
  87171. return Vertex;
  87172. }());
  87173. // # class Plane
  87174. // Represents a plane in 3D space.
  87175. var Plane = /** @class */ (function () {
  87176. function Plane(normal, w) {
  87177. this.normal = normal;
  87178. this.w = w;
  87179. }
  87180. Plane.FromPoints = function (a, b, c) {
  87181. var v0 = c.subtract(a);
  87182. var v1 = b.subtract(a);
  87183. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  87184. return null;
  87185. }
  87186. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  87187. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  87188. };
  87189. Plane.prototype.clone = function () {
  87190. return new Plane(this.normal.clone(), this.w);
  87191. };
  87192. Plane.prototype.flip = function () {
  87193. this.normal.scaleInPlace(-1);
  87194. this.w = -this.w;
  87195. };
  87196. // Split `polygon` by this plane if needed, then put the polygon or polygon
  87197. // fragments in the appropriate lists. Coplanar polygons go into either
  87198. // `coplanarFront` or `coplanarBack` depending on their orientation with
  87199. // respect to this plane. Polygons in front or in back of this plane go into
  87200. // either `front` or `back`.
  87201. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  87202. var COPLANAR = 0;
  87203. var FRONT = 1;
  87204. var BACK = 2;
  87205. var SPANNING = 3;
  87206. // Classify each point as well as the entire polygon into one of the above
  87207. // four classes.
  87208. var polygonType = 0;
  87209. var types = [];
  87210. var i;
  87211. var t;
  87212. for (i = 0; i < polygon.vertices.length; i++) {
  87213. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  87214. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  87215. polygonType |= type;
  87216. types.push(type);
  87217. }
  87218. // Put the polygon in the correct list, splitting it when necessary.
  87219. switch (polygonType) {
  87220. case COPLANAR:
  87221. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  87222. break;
  87223. case FRONT:
  87224. front.push(polygon);
  87225. break;
  87226. case BACK:
  87227. back.push(polygon);
  87228. break;
  87229. case SPANNING:
  87230. var f = [], b = [];
  87231. for (i = 0; i < polygon.vertices.length; i++) {
  87232. var j = (i + 1) % polygon.vertices.length;
  87233. var ti = types[i], tj = types[j];
  87234. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  87235. if (ti !== BACK)
  87236. f.push(vi);
  87237. if (ti !== FRONT)
  87238. b.push(ti !== BACK ? vi.clone() : vi);
  87239. if ((ti | tj) === SPANNING) {
  87240. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  87241. var v = vi.interpolate(vj, t);
  87242. f.push(v);
  87243. b.push(v.clone());
  87244. }
  87245. }
  87246. var poly;
  87247. if (f.length >= 3) {
  87248. poly = new Polygon(f, polygon.shared);
  87249. if (poly.plane)
  87250. front.push(poly);
  87251. }
  87252. if (b.length >= 3) {
  87253. poly = new Polygon(b, polygon.shared);
  87254. if (poly.plane)
  87255. back.push(poly);
  87256. }
  87257. break;
  87258. }
  87259. };
  87260. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  87261. // point is on the plane.
  87262. Plane.EPSILON = 1e-5;
  87263. return Plane;
  87264. }());
  87265. // # class Polygon
  87266. // Represents a convex polygon. The vertices used to initialize a polygon must
  87267. // be coplanar and form a convex loop.
  87268. //
  87269. // Each convex polygon has a `shared` property, which is shared between all
  87270. // polygons that are clones of each other or were split from the same polygon.
  87271. // This can be used to define per-polygon properties (such as surface color).
  87272. var Polygon = /** @class */ (function () {
  87273. function Polygon(vertices, shared) {
  87274. this.vertices = vertices;
  87275. this.shared = shared;
  87276. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  87277. }
  87278. Polygon.prototype.clone = function () {
  87279. var vertices = this.vertices.map(function (v) { return v.clone(); });
  87280. return new Polygon(vertices, this.shared);
  87281. };
  87282. Polygon.prototype.flip = function () {
  87283. this.vertices.reverse().map(function (v) { v.flip(); });
  87284. this.plane.flip();
  87285. };
  87286. return Polygon;
  87287. }());
  87288. // # class Node
  87289. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  87290. // by picking a polygon to split along. That polygon (and all other coplanar
  87291. // polygons) are added directly to that node and the other polygons are added to
  87292. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  87293. // no distinction between internal and leaf nodes.
  87294. var Node = /** @class */ (function () {
  87295. function Node(polygons) {
  87296. this.plane = null;
  87297. this.front = null;
  87298. this.back = null;
  87299. this.polygons = new Array();
  87300. if (polygons) {
  87301. this.build(polygons);
  87302. }
  87303. }
  87304. Node.prototype.clone = function () {
  87305. var node = new Node();
  87306. node.plane = this.plane && this.plane.clone();
  87307. node.front = this.front && this.front.clone();
  87308. node.back = this.back && this.back.clone();
  87309. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  87310. return node;
  87311. };
  87312. // Convert solid space to empty space and empty space to solid space.
  87313. Node.prototype.invert = function () {
  87314. for (var i = 0; i < this.polygons.length; i++) {
  87315. this.polygons[i].flip();
  87316. }
  87317. if (this.plane) {
  87318. this.plane.flip();
  87319. }
  87320. if (this.front) {
  87321. this.front.invert();
  87322. }
  87323. if (this.back) {
  87324. this.back.invert();
  87325. }
  87326. var temp = this.front;
  87327. this.front = this.back;
  87328. this.back = temp;
  87329. };
  87330. // Recursively remove all polygons in `polygons` that are inside this BSP
  87331. // tree.
  87332. Node.prototype.clipPolygons = function (polygons) {
  87333. if (!this.plane)
  87334. return polygons.slice();
  87335. var front = new Array(), back = new Array();
  87336. for (var i = 0; i < polygons.length; i++) {
  87337. this.plane.splitPolygon(polygons[i], front, back, front, back);
  87338. }
  87339. if (this.front) {
  87340. front = this.front.clipPolygons(front);
  87341. }
  87342. if (this.back) {
  87343. back = this.back.clipPolygons(back);
  87344. }
  87345. else {
  87346. back = [];
  87347. }
  87348. return front.concat(back);
  87349. };
  87350. // Remove all polygons in this BSP tree that are inside the other BSP tree
  87351. // `bsp`.
  87352. Node.prototype.clipTo = function (bsp) {
  87353. this.polygons = bsp.clipPolygons(this.polygons);
  87354. if (this.front)
  87355. this.front.clipTo(bsp);
  87356. if (this.back)
  87357. this.back.clipTo(bsp);
  87358. };
  87359. // Return a list of all polygons in this BSP tree.
  87360. Node.prototype.allPolygons = function () {
  87361. var polygons = this.polygons.slice();
  87362. if (this.front)
  87363. polygons = polygons.concat(this.front.allPolygons());
  87364. if (this.back)
  87365. polygons = polygons.concat(this.back.allPolygons());
  87366. return polygons;
  87367. };
  87368. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  87369. // new polygons are filtered down to the bottom of the tree and become new
  87370. // nodes there. Each set of polygons is partitioned using the first polygon
  87371. // (no heuristic is used to pick a good split).
  87372. Node.prototype.build = function (polygons) {
  87373. if (!polygons.length)
  87374. return;
  87375. if (!this.plane)
  87376. this.plane = polygons[0].plane.clone();
  87377. var front = new Array(), back = new Array();
  87378. for (var i = 0; i < polygons.length; i++) {
  87379. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  87380. }
  87381. if (front.length) {
  87382. if (!this.front)
  87383. this.front = new Node();
  87384. this.front.build(front);
  87385. }
  87386. if (back.length) {
  87387. if (!this.back)
  87388. this.back = new Node();
  87389. this.back.build(back);
  87390. }
  87391. };
  87392. return Node;
  87393. }());
  87394. var CSG = /** @class */ (function () {
  87395. function CSG() {
  87396. this.polygons = new Array();
  87397. }
  87398. // Convert BABYLON.Mesh to BABYLON.CSG
  87399. CSG.FromMesh = function (mesh) {
  87400. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  87401. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  87402. if (mesh instanceof BABYLON.Mesh) {
  87403. mesh.computeWorldMatrix(true);
  87404. matrix = mesh.getWorldMatrix();
  87405. meshPosition = mesh.position.clone();
  87406. meshRotation = mesh.rotation.clone();
  87407. if (mesh.rotationQuaternion) {
  87408. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  87409. }
  87410. meshScaling = mesh.scaling.clone();
  87411. }
  87412. else {
  87413. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  87414. }
  87415. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  87416. var subMeshes = mesh.subMeshes;
  87417. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  87418. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  87419. vertices = [];
  87420. for (var j = 0; j < 3; j++) {
  87421. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  87422. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  87423. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  87424. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  87425. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  87426. vertex = new Vertex(position, normal, uv);
  87427. vertices.push(vertex);
  87428. }
  87429. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  87430. // To handle the case of degenerated triangle
  87431. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  87432. if (polygon.plane)
  87433. polygons.push(polygon);
  87434. }
  87435. }
  87436. var csg = CSG.FromPolygons(polygons);
  87437. csg.matrix = matrix;
  87438. csg.position = meshPosition;
  87439. csg.rotation = meshRotation;
  87440. csg.scaling = meshScaling;
  87441. csg.rotationQuaternion = meshRotationQuaternion;
  87442. currentCSGMeshId++;
  87443. return csg;
  87444. };
  87445. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  87446. CSG.FromPolygons = function (polygons) {
  87447. var csg = new CSG();
  87448. csg.polygons = polygons;
  87449. return csg;
  87450. };
  87451. CSG.prototype.clone = function () {
  87452. var csg = new CSG();
  87453. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  87454. csg.copyTransformAttributes(this);
  87455. return csg;
  87456. };
  87457. CSG.prototype.union = function (csg) {
  87458. var a = new Node(this.clone().polygons);
  87459. var b = new Node(csg.clone().polygons);
  87460. a.clipTo(b);
  87461. b.clipTo(a);
  87462. b.invert();
  87463. b.clipTo(a);
  87464. b.invert();
  87465. a.build(b.allPolygons());
  87466. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87467. };
  87468. CSG.prototype.unionInPlace = function (csg) {
  87469. var a = new Node(this.polygons);
  87470. var b = new Node(csg.polygons);
  87471. a.clipTo(b);
  87472. b.clipTo(a);
  87473. b.invert();
  87474. b.clipTo(a);
  87475. b.invert();
  87476. a.build(b.allPolygons());
  87477. this.polygons = a.allPolygons();
  87478. };
  87479. CSG.prototype.subtract = function (csg) {
  87480. var a = new Node(this.clone().polygons);
  87481. var b = new Node(csg.clone().polygons);
  87482. a.invert();
  87483. a.clipTo(b);
  87484. b.clipTo(a);
  87485. b.invert();
  87486. b.clipTo(a);
  87487. b.invert();
  87488. a.build(b.allPolygons());
  87489. a.invert();
  87490. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87491. };
  87492. CSG.prototype.subtractInPlace = function (csg) {
  87493. var a = new Node(this.polygons);
  87494. var b = new Node(csg.polygons);
  87495. a.invert();
  87496. a.clipTo(b);
  87497. b.clipTo(a);
  87498. b.invert();
  87499. b.clipTo(a);
  87500. b.invert();
  87501. a.build(b.allPolygons());
  87502. a.invert();
  87503. this.polygons = a.allPolygons();
  87504. };
  87505. CSG.prototype.intersect = function (csg) {
  87506. var a = new Node(this.clone().polygons);
  87507. var b = new Node(csg.clone().polygons);
  87508. a.invert();
  87509. b.clipTo(a);
  87510. b.invert();
  87511. a.clipTo(b);
  87512. b.clipTo(a);
  87513. a.build(b.allPolygons());
  87514. a.invert();
  87515. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87516. };
  87517. CSG.prototype.intersectInPlace = function (csg) {
  87518. var a = new Node(this.polygons);
  87519. var b = new Node(csg.polygons);
  87520. a.invert();
  87521. b.clipTo(a);
  87522. b.invert();
  87523. a.clipTo(b);
  87524. b.clipTo(a);
  87525. a.build(b.allPolygons());
  87526. a.invert();
  87527. this.polygons = a.allPolygons();
  87528. };
  87529. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  87530. // not modified.
  87531. CSG.prototype.inverse = function () {
  87532. var csg = this.clone();
  87533. csg.inverseInPlace();
  87534. return csg;
  87535. };
  87536. CSG.prototype.inverseInPlace = function () {
  87537. this.polygons.map(function (p) { p.flip(); });
  87538. };
  87539. // This is used to keep meshes transformations so they can be restored
  87540. // when we build back a Babylon Mesh
  87541. // NB : All CSG operations are performed in world coordinates
  87542. CSG.prototype.copyTransformAttributes = function (csg) {
  87543. this.matrix = csg.matrix;
  87544. this.position = csg.position;
  87545. this.rotation = csg.rotation;
  87546. this.scaling = csg.scaling;
  87547. this.rotationQuaternion = csg.rotationQuaternion;
  87548. return this;
  87549. };
  87550. // Build Raw mesh from CSG
  87551. // Coordinates here are in world space
  87552. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  87553. var matrix = this.matrix.clone();
  87554. matrix.invert();
  87555. 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;
  87556. if (keepSubMeshes) {
  87557. // Sort Polygons, since subMeshes are indices range
  87558. polygons.sort(function (a, b) {
  87559. if (a.shared.meshId === b.shared.meshId) {
  87560. return a.shared.subMeshId - b.shared.subMeshId;
  87561. }
  87562. else {
  87563. return a.shared.meshId - b.shared.meshId;
  87564. }
  87565. });
  87566. }
  87567. for (var i = 0, il = polygons.length; i < il; i++) {
  87568. polygon = polygons[i];
  87569. // Building SubMeshes
  87570. if (!subMesh_dict[polygon.shared.meshId]) {
  87571. subMesh_dict[polygon.shared.meshId] = {};
  87572. }
  87573. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  87574. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  87575. indexStart: +Infinity,
  87576. indexEnd: -Infinity,
  87577. materialIndex: polygon.shared.materialIndex
  87578. };
  87579. }
  87580. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  87581. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  87582. polygonIndices[0] = 0;
  87583. polygonIndices[1] = j - 1;
  87584. polygonIndices[2] = j;
  87585. for (var k = 0; k < 3; k++) {
  87586. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  87587. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  87588. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  87589. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  87590. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  87591. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  87592. // Check if 2 points can be merged
  87593. if (!(typeof vertex_idx !== 'undefined' &&
  87594. normals[vertex_idx * 3] === localNormal.x &&
  87595. normals[vertex_idx * 3 + 1] === localNormal.y &&
  87596. normals[vertex_idx * 3 + 2] === localNormal.z &&
  87597. uvs[vertex_idx * 2] === uv.x &&
  87598. uvs[vertex_idx * 2 + 1] === uv.y)) {
  87599. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  87600. uvs.push(uv.x, uv.y);
  87601. normals.push(normal.x, normal.y, normal.z);
  87602. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  87603. }
  87604. indices.push(vertex_idx);
  87605. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  87606. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  87607. currentIndex++;
  87608. }
  87609. }
  87610. }
  87611. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  87612. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  87613. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  87614. mesh.setIndices(indices, null);
  87615. if (keepSubMeshes) {
  87616. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  87617. var materialIndexOffset = 0, materialMaxIndex;
  87618. mesh.subMeshes = new Array();
  87619. for (var m in subMesh_dict) {
  87620. materialMaxIndex = -1;
  87621. for (var sm in subMesh_dict[m]) {
  87622. subMesh_obj = subMesh_dict[m][sm];
  87623. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  87624. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  87625. }
  87626. materialIndexOffset += ++materialMaxIndex;
  87627. }
  87628. }
  87629. return mesh;
  87630. };
  87631. // Build Mesh from CSG taking material and transforms into account
  87632. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  87633. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  87634. mesh.material = material;
  87635. mesh.position.copyFrom(this.position);
  87636. mesh.rotation.copyFrom(this.rotation);
  87637. if (this.rotationQuaternion) {
  87638. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  87639. }
  87640. mesh.scaling.copyFrom(this.scaling);
  87641. mesh.computeWorldMatrix(true);
  87642. return mesh;
  87643. };
  87644. return CSG;
  87645. }());
  87646. BABYLON.CSG = CSG;
  87647. })(BABYLON || (BABYLON = {}));
  87648. //# sourceMappingURL=babylon.csg.js.map
  87649. var BABYLON;
  87650. (function (BABYLON) {
  87651. var LensFlare = /** @class */ (function () {
  87652. function LensFlare(size, position, color, imgUrl, system) {
  87653. this.size = size;
  87654. this.position = position;
  87655. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  87656. this.color = color || new BABYLON.Color3(1, 1, 1);
  87657. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  87658. this._system = system;
  87659. system.lensFlares.push(this);
  87660. }
  87661. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  87662. return new LensFlare(size, position, color, imgUrl, system);
  87663. };
  87664. LensFlare.prototype.dispose = function () {
  87665. if (this.texture) {
  87666. this.texture.dispose();
  87667. }
  87668. // Remove from scene
  87669. var index = this._system.lensFlares.indexOf(this);
  87670. this._system.lensFlares.splice(index, 1);
  87671. };
  87672. ;
  87673. return LensFlare;
  87674. }());
  87675. BABYLON.LensFlare = LensFlare;
  87676. })(BABYLON || (BABYLON = {}));
  87677. //# sourceMappingURL=babylon.lensFlare.js.map
  87678. var BABYLON;
  87679. (function (BABYLON) {
  87680. // Adds the parser to the scene parsers.
  87681. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  87682. // Lens flares
  87683. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  87684. if (!container.lensFlareSystems) {
  87685. container.lensFlareSystems = new Array();
  87686. }
  87687. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  87688. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  87689. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  87690. container.lensFlareSystems.push(lf);
  87691. }
  87692. }
  87693. });
  87694. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  87695. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  87696. if (this.lensFlareSystems[index].name === name) {
  87697. return this.lensFlareSystems[index];
  87698. }
  87699. }
  87700. return null;
  87701. };
  87702. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  87703. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  87704. if (this.lensFlareSystems[index].id === id) {
  87705. return this.lensFlareSystems[index];
  87706. }
  87707. }
  87708. return null;
  87709. };
  87710. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  87711. var index = this.lensFlareSystems.indexOf(toRemove);
  87712. if (index !== -1) {
  87713. this.lensFlareSystems.splice(index, 1);
  87714. }
  87715. return index;
  87716. };
  87717. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  87718. this.lensFlareSystems.push(newLensFlareSystem);
  87719. };
  87720. /**
  87721. * Defines the lens flare scene component responsible to manage any lens flares
  87722. * in a given scene.
  87723. */
  87724. var LensFlareSystemSceneComponent = /** @class */ (function () {
  87725. /**
  87726. * Creates a new instance of the component for the given scene
  87727. * @param scene Defines the scene to register the component in
  87728. */
  87729. function LensFlareSystemSceneComponent(scene) {
  87730. /**
  87731. * The component name helpfull to identify the component in the list of scene components.
  87732. */
  87733. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  87734. this.scene = scene;
  87735. scene.lensFlareSystems = new Array();
  87736. }
  87737. /**
  87738. * Registers the component in a given scene
  87739. */
  87740. LensFlareSystemSceneComponent.prototype.register = function () {
  87741. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  87742. };
  87743. /**
  87744. * Rebuilds the elements related to this component in case of
  87745. * context lost for instance.
  87746. */
  87747. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  87748. // Nothing to do for lens flare
  87749. };
  87750. /**
  87751. * Adds all the element from the container to the scene
  87752. * @param container the container holding the elements
  87753. */
  87754. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  87755. var _this = this;
  87756. if (!container.lensFlareSystems) {
  87757. return;
  87758. }
  87759. container.lensFlareSystems.forEach(function (o) {
  87760. _this.scene.addLensFlareSystem(o);
  87761. });
  87762. };
  87763. /**
  87764. * Removes all the elements in the container from the scene
  87765. * @param container contains the elements to remove
  87766. */
  87767. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  87768. var _this = this;
  87769. if (!container.lensFlareSystems) {
  87770. return;
  87771. }
  87772. container.lensFlareSystems.forEach(function (o) {
  87773. _this.scene.removeLensFlareSystem(o);
  87774. });
  87775. };
  87776. /**
  87777. * Serializes the component data to the specified json object
  87778. * @param serializationObject The object to serialize to
  87779. */
  87780. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  87781. // Lens flares
  87782. serializationObject.lensFlareSystems = [];
  87783. var lensFlareSystems = this.scene.lensFlareSystems;
  87784. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  87785. var lensFlareSystem = lensFlareSystems_1[_i];
  87786. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  87787. }
  87788. };
  87789. /**
  87790. * Disposes the component and the associated ressources.
  87791. */
  87792. LensFlareSystemSceneComponent.prototype.dispose = function () {
  87793. var lensFlareSystems = this.scene.lensFlareSystems;
  87794. while (lensFlareSystems.length) {
  87795. lensFlareSystems[0].dispose();
  87796. }
  87797. };
  87798. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  87799. // Lens flares
  87800. if (this.scene.lensFlaresEnabled) {
  87801. var lensFlareSystems = this.scene.lensFlareSystems;
  87802. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  87803. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  87804. var lensFlareSystem = lensFlareSystems_2[_i];
  87805. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  87806. lensFlareSystem.render();
  87807. }
  87808. }
  87809. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  87810. }
  87811. };
  87812. return LensFlareSystemSceneComponent;
  87813. }());
  87814. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  87815. })(BABYLON || (BABYLON = {}));
  87816. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  87817. var BABYLON;
  87818. (function (BABYLON) {
  87819. var LensFlareSystem = /** @class */ (function () {
  87820. function LensFlareSystem(name, emitter, scene) {
  87821. this.name = name;
  87822. this.lensFlares = new Array();
  87823. this.borderLimit = 300;
  87824. this.viewportBorder = 0;
  87825. this.layerMask = 0x0FFFFFFF;
  87826. this._vertexBuffers = {};
  87827. this._isEnabled = true;
  87828. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87829. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  87830. if (!component) {
  87831. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  87832. scene._addComponent(component);
  87833. }
  87834. this._emitter = emitter;
  87835. this.id = name;
  87836. scene.lensFlareSystems.push(this);
  87837. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  87838. var engine = scene.getEngine();
  87839. // VBO
  87840. var vertices = [];
  87841. vertices.push(1, 1);
  87842. vertices.push(-1, 1);
  87843. vertices.push(-1, -1);
  87844. vertices.push(1, -1);
  87845. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87846. // Indices
  87847. var indices = [];
  87848. indices.push(0);
  87849. indices.push(1);
  87850. indices.push(2);
  87851. indices.push(0);
  87852. indices.push(2);
  87853. indices.push(3);
  87854. this._indexBuffer = engine.createIndexBuffer(indices);
  87855. // Effects
  87856. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  87857. }
  87858. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  87859. get: function () {
  87860. return this._isEnabled;
  87861. },
  87862. set: function (value) {
  87863. this._isEnabled = value;
  87864. },
  87865. enumerable: true,
  87866. configurable: true
  87867. });
  87868. LensFlareSystem.prototype.getScene = function () {
  87869. return this._scene;
  87870. };
  87871. LensFlareSystem.prototype.getEmitter = function () {
  87872. return this._emitter;
  87873. };
  87874. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  87875. this._emitter = newEmitter;
  87876. };
  87877. LensFlareSystem.prototype.getEmitterPosition = function () {
  87878. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  87879. };
  87880. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  87881. var position = this.getEmitterPosition();
  87882. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  87883. this._positionX = position.x;
  87884. this._positionY = position.y;
  87885. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  87886. if (this.viewportBorder > 0) {
  87887. globalViewport.x -= this.viewportBorder;
  87888. globalViewport.y -= this.viewportBorder;
  87889. globalViewport.width += this.viewportBorder * 2;
  87890. globalViewport.height += this.viewportBorder * 2;
  87891. position.x += this.viewportBorder;
  87892. position.y += this.viewportBorder;
  87893. this._positionX += this.viewportBorder;
  87894. this._positionY += this.viewportBorder;
  87895. }
  87896. if (position.z > 0) {
  87897. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  87898. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  87899. return true;
  87900. }
  87901. return true;
  87902. }
  87903. return false;
  87904. };
  87905. /** @hidden */
  87906. LensFlareSystem.prototype._isVisible = function () {
  87907. if (!this._isEnabled || !this._scene.activeCamera) {
  87908. return false;
  87909. }
  87910. var emitterPosition = this.getEmitterPosition();
  87911. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  87912. var distance = direction.length();
  87913. direction.normalize();
  87914. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  87915. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  87916. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  87917. };
  87918. LensFlareSystem.prototype.render = function () {
  87919. if (!this._effect.isReady() || !this._scene.activeCamera)
  87920. return false;
  87921. var engine = this._scene.getEngine();
  87922. var viewport = this._scene.activeCamera.viewport;
  87923. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  87924. // Position
  87925. if (!this.computeEffectivePosition(globalViewport)) {
  87926. return false;
  87927. }
  87928. // Visibility
  87929. if (!this._isVisible()) {
  87930. return false;
  87931. }
  87932. // Intensity
  87933. var awayX;
  87934. var awayY;
  87935. if (this._positionX < this.borderLimit + globalViewport.x) {
  87936. awayX = this.borderLimit + globalViewport.x - this._positionX;
  87937. }
  87938. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  87939. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  87940. }
  87941. else {
  87942. awayX = 0;
  87943. }
  87944. if (this._positionY < this.borderLimit + globalViewport.y) {
  87945. awayY = this.borderLimit + globalViewport.y - this._positionY;
  87946. }
  87947. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  87948. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  87949. }
  87950. else {
  87951. awayY = 0;
  87952. }
  87953. var away = (awayX > awayY) ? awayX : awayY;
  87954. away -= this.viewportBorder;
  87955. if (away > this.borderLimit) {
  87956. away = this.borderLimit;
  87957. }
  87958. var intensity = 1.0 - (away / this.borderLimit);
  87959. if (intensity < 0) {
  87960. return false;
  87961. }
  87962. if (intensity > 1.0) {
  87963. intensity = 1.0;
  87964. }
  87965. if (this.viewportBorder > 0) {
  87966. globalViewport.x += this.viewportBorder;
  87967. globalViewport.y += this.viewportBorder;
  87968. globalViewport.width -= this.viewportBorder * 2;
  87969. globalViewport.height -= this.viewportBorder * 2;
  87970. this._positionX -= this.viewportBorder;
  87971. this._positionY -= this.viewportBorder;
  87972. }
  87973. // Position
  87974. var centerX = globalViewport.x + globalViewport.width / 2;
  87975. var centerY = globalViewport.y + globalViewport.height / 2;
  87976. var distX = centerX - this._positionX;
  87977. var distY = centerY - this._positionY;
  87978. // Effects
  87979. engine.enableEffect(this._effect);
  87980. engine.setState(false);
  87981. engine.setDepthBuffer(false);
  87982. // VBOs
  87983. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  87984. // Flares
  87985. for (var index = 0; index < this.lensFlares.length; index++) {
  87986. var flare = this.lensFlares[index];
  87987. engine.setAlphaMode(flare.alphaMode);
  87988. var x = centerX - (distX * flare.position);
  87989. var y = centerY - (distY * flare.position);
  87990. var cw = flare.size;
  87991. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  87992. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  87993. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  87994. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  87995. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  87996. // Texture
  87997. this._effect.setTexture("textureSampler", flare.texture);
  87998. // Color
  87999. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  88000. // Draw order
  88001. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88002. }
  88003. engine.setDepthBuffer(true);
  88004. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88005. return true;
  88006. };
  88007. LensFlareSystem.prototype.dispose = function () {
  88008. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88009. if (vertexBuffer) {
  88010. vertexBuffer.dispose();
  88011. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88012. }
  88013. if (this._indexBuffer) {
  88014. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88015. this._indexBuffer = null;
  88016. }
  88017. while (this.lensFlares.length) {
  88018. this.lensFlares[0].dispose();
  88019. }
  88020. // Remove from scene
  88021. var index = this._scene.lensFlareSystems.indexOf(this);
  88022. this._scene.lensFlareSystems.splice(index, 1);
  88023. };
  88024. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  88025. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  88026. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  88027. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  88028. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  88029. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  88030. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  88031. var parsedFlare = parsedLensFlareSystem.flares[index];
  88032. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  88033. }
  88034. return lensFlareSystem;
  88035. };
  88036. LensFlareSystem.prototype.serialize = function () {
  88037. var serializationObject = {};
  88038. serializationObject.id = this.id;
  88039. serializationObject.name = this.name;
  88040. serializationObject.emitterId = this.getEmitter().id;
  88041. serializationObject.borderLimit = this.borderLimit;
  88042. serializationObject.flares = [];
  88043. for (var index = 0; index < this.lensFlares.length; index++) {
  88044. var flare = this.lensFlares[index];
  88045. serializationObject.flares.push({
  88046. size: flare.size,
  88047. position: flare.position,
  88048. color: flare.color.asArray(),
  88049. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  88050. });
  88051. }
  88052. return serializationObject;
  88053. };
  88054. return LensFlareSystem;
  88055. }());
  88056. BABYLON.LensFlareSystem = LensFlareSystem;
  88057. })(BABYLON || (BABYLON = {}));
  88058. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  88059. var BABYLON;
  88060. (function (BABYLON) {
  88061. /**
  88062. * This is a holder class for the physics joint created by the physics plugin.
  88063. * It holds a set of functions to control the underlying joint.
  88064. */
  88065. var PhysicsJoint = /** @class */ (function () {
  88066. function PhysicsJoint(type, jointData) {
  88067. this.type = type;
  88068. this.jointData = jointData;
  88069. jointData.nativeParams = jointData.nativeParams || {};
  88070. }
  88071. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  88072. get: function () {
  88073. return this._physicsJoint;
  88074. },
  88075. set: function (newJoint) {
  88076. if (this._physicsJoint) {
  88077. //remove from the wolrd
  88078. }
  88079. this._physicsJoint = newJoint;
  88080. },
  88081. enumerable: true,
  88082. configurable: true
  88083. });
  88084. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  88085. set: function (physicsPlugin) {
  88086. this._physicsPlugin = physicsPlugin;
  88087. },
  88088. enumerable: true,
  88089. configurable: true
  88090. });
  88091. /**
  88092. * Execute a function that is physics-plugin specific.
  88093. * @param {Function} func the function that will be executed.
  88094. * It accepts two parameters: the physics world and the physics joint.
  88095. */
  88096. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  88097. func(this._physicsPlugin.world, this._physicsJoint);
  88098. };
  88099. //TODO check if the native joints are the same
  88100. //Joint Types
  88101. PhysicsJoint.DistanceJoint = 0;
  88102. PhysicsJoint.HingeJoint = 1;
  88103. PhysicsJoint.BallAndSocketJoint = 2;
  88104. PhysicsJoint.WheelJoint = 3;
  88105. PhysicsJoint.SliderJoint = 4;
  88106. //OIMO
  88107. PhysicsJoint.PrismaticJoint = 5;
  88108. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  88109. PhysicsJoint.UniversalJoint = 6;
  88110. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  88111. //Cannon
  88112. //Similar to a Ball-Joint. Different in params
  88113. PhysicsJoint.PointToPointJoint = 8;
  88114. //Cannon only at the moment
  88115. PhysicsJoint.SpringJoint = 9;
  88116. PhysicsJoint.LockJoint = 10;
  88117. return PhysicsJoint;
  88118. }());
  88119. BABYLON.PhysicsJoint = PhysicsJoint;
  88120. /**
  88121. * A class representing a physics distance joint.
  88122. */
  88123. var DistanceJoint = /** @class */ (function (_super) {
  88124. __extends(DistanceJoint, _super);
  88125. function DistanceJoint(jointData) {
  88126. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  88127. }
  88128. /**
  88129. * Update the predefined distance.
  88130. */
  88131. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  88132. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  88133. };
  88134. return DistanceJoint;
  88135. }(PhysicsJoint));
  88136. BABYLON.DistanceJoint = DistanceJoint;
  88137. var MotorEnabledJoint = /** @class */ (function (_super) {
  88138. __extends(MotorEnabledJoint, _super);
  88139. function MotorEnabledJoint(type, jointData) {
  88140. return _super.call(this, type, jointData) || this;
  88141. }
  88142. /**
  88143. * Set the motor values.
  88144. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88145. * @param {number} force the force to apply
  88146. * @param {number} maxForce max force for this motor.
  88147. */
  88148. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  88149. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88150. };
  88151. /**
  88152. * Set the motor's limits.
  88153. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88154. */
  88155. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88156. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88157. };
  88158. return MotorEnabledJoint;
  88159. }(PhysicsJoint));
  88160. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  88161. /**
  88162. * This class represents a single hinge physics joint
  88163. */
  88164. var HingeJoint = /** @class */ (function (_super) {
  88165. __extends(HingeJoint, _super);
  88166. function HingeJoint(jointData) {
  88167. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  88168. }
  88169. /**
  88170. * Set the motor values.
  88171. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88172. * @param {number} force the force to apply
  88173. * @param {number} maxForce max force for this motor.
  88174. */
  88175. HingeJoint.prototype.setMotor = function (force, maxForce) {
  88176. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88177. };
  88178. /**
  88179. * Set the motor's limits.
  88180. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88181. */
  88182. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88183. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88184. };
  88185. return HingeJoint;
  88186. }(MotorEnabledJoint));
  88187. BABYLON.HingeJoint = HingeJoint;
  88188. /**
  88189. * This class represents a dual hinge physics joint (same as wheel joint)
  88190. */
  88191. var Hinge2Joint = /** @class */ (function (_super) {
  88192. __extends(Hinge2Joint, _super);
  88193. function Hinge2Joint(jointData) {
  88194. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  88195. }
  88196. /**
  88197. * Set the motor values.
  88198. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88199. * @param {number} force the force to apply
  88200. * @param {number} maxForce max force for this motor.
  88201. * @param {motorIndex} the motor's index, 0 or 1.
  88202. */
  88203. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  88204. if (motorIndex === void 0) { motorIndex = 0; }
  88205. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  88206. };
  88207. /**
  88208. * Set the motor limits.
  88209. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88210. * @param {number} upperLimit the upper limit
  88211. * @param {number} lowerLimit lower limit
  88212. * @param {motorIndex} the motor's index, 0 or 1.
  88213. */
  88214. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  88215. if (motorIndex === void 0) { motorIndex = 0; }
  88216. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  88217. };
  88218. return Hinge2Joint;
  88219. }(MotorEnabledJoint));
  88220. BABYLON.Hinge2Joint = Hinge2Joint;
  88221. })(BABYLON || (BABYLON = {}));
  88222. //# sourceMappingURL=babylon.physicsJoint.js.map
  88223. var BABYLON;
  88224. (function (BABYLON) {
  88225. var PhysicsImpostor = /** @class */ (function () {
  88226. function PhysicsImpostor(object, type, _options, _scene) {
  88227. if (_options === void 0) { _options = { mass: 0 }; }
  88228. var _this = this;
  88229. this.object = object;
  88230. this.type = type;
  88231. this._options = _options;
  88232. this._scene = _scene;
  88233. this._bodyUpdateRequired = false;
  88234. this._onBeforePhysicsStepCallbacks = new Array();
  88235. this._onAfterPhysicsStepCallbacks = new Array();
  88236. this._onPhysicsCollideCallbacks = [];
  88237. this._deltaPosition = BABYLON.Vector3.Zero();
  88238. this._isDisposed = false;
  88239. //temp variables for parent rotation calculations
  88240. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  88241. this._tmpQuat = new BABYLON.Quaternion();
  88242. this._tmpQuat2 = new BABYLON.Quaternion();
  88243. /**
  88244. * this function is executed by the physics engine.
  88245. */
  88246. this.beforeStep = function () {
  88247. if (!_this._physicsEngine) {
  88248. return;
  88249. }
  88250. _this.object.translate(_this._deltaPosition, -1);
  88251. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  88252. _this.object.computeWorldMatrix(false);
  88253. if (_this.object.parent && _this.object.rotationQuaternion) {
  88254. _this.getParentsRotation();
  88255. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  88256. }
  88257. else {
  88258. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  88259. }
  88260. if (!_this._options.disableBidirectionalTransformation) {
  88261. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  88262. }
  88263. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  88264. func(_this);
  88265. });
  88266. };
  88267. /**
  88268. * this function is executed by the physics engine.
  88269. */
  88270. this.afterStep = function () {
  88271. if (!_this._physicsEngine) {
  88272. return;
  88273. }
  88274. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  88275. func(_this);
  88276. });
  88277. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  88278. // object has now its world rotation. needs to be converted to local.
  88279. if (_this.object.parent && _this.object.rotationQuaternion) {
  88280. _this.getParentsRotation();
  88281. _this._tmpQuat.conjugateInPlace();
  88282. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  88283. }
  88284. // take the position set and make it the absolute position of this object.
  88285. _this.object.setAbsolutePosition(_this.object.position);
  88286. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  88287. _this.object.translate(_this._deltaPosition, 1);
  88288. };
  88289. /**
  88290. * Legacy collision detection event support
  88291. */
  88292. this.onCollideEvent = null;
  88293. //event and body object due to cannon's event-based architecture.
  88294. this.onCollide = function (e) {
  88295. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  88296. return;
  88297. }
  88298. if (!_this._physicsEngine) {
  88299. return;
  88300. }
  88301. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  88302. if (otherImpostor) {
  88303. // Legacy collision detection event support
  88304. if (_this.onCollideEvent) {
  88305. _this.onCollideEvent(_this, otherImpostor);
  88306. }
  88307. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  88308. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  88309. }).forEach(function (obj) {
  88310. obj.callback(_this, otherImpostor);
  88311. });
  88312. }
  88313. };
  88314. //sanity check!
  88315. if (!this.object) {
  88316. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  88317. return;
  88318. }
  88319. //legacy support for old syntax.
  88320. if (!this._scene && object.getScene) {
  88321. this._scene = object.getScene();
  88322. }
  88323. if (!this._scene) {
  88324. return;
  88325. }
  88326. this._physicsEngine = this._scene.getPhysicsEngine();
  88327. if (!this._physicsEngine) {
  88328. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  88329. }
  88330. else {
  88331. //set the object's quaternion, if not set
  88332. if (!this.object.rotationQuaternion) {
  88333. if (this.object.rotation) {
  88334. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  88335. }
  88336. else {
  88337. this.object.rotationQuaternion = new BABYLON.Quaternion();
  88338. }
  88339. }
  88340. //default options params
  88341. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  88342. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  88343. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  88344. this._joints = [];
  88345. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  88346. if (!this.object.parent || this._options.ignoreParent) {
  88347. this._init();
  88348. }
  88349. else if (this.object.parent.physicsImpostor) {
  88350. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  88351. }
  88352. }
  88353. }
  88354. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  88355. get: function () {
  88356. return this._isDisposed;
  88357. },
  88358. enumerable: true,
  88359. configurable: true
  88360. });
  88361. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  88362. get: function () {
  88363. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  88364. },
  88365. set: function (value) {
  88366. this.setMass(value);
  88367. },
  88368. enumerable: true,
  88369. configurable: true
  88370. });
  88371. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  88372. get: function () {
  88373. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  88374. },
  88375. set: function (value) {
  88376. if (!this._physicsEngine) {
  88377. return;
  88378. }
  88379. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  88380. },
  88381. enumerable: true,
  88382. configurable: true
  88383. });
  88384. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  88385. get: function () {
  88386. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  88387. },
  88388. set: function (value) {
  88389. if (!this._physicsEngine) {
  88390. return;
  88391. }
  88392. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  88393. },
  88394. enumerable: true,
  88395. configurable: true
  88396. });
  88397. /**
  88398. * This function will completly initialize this impostor.
  88399. * It will create a new body - but only if this mesh has no parent.
  88400. * If it has, this impostor will not be used other than to define the impostor
  88401. * of the child mesh.
  88402. * @hidden
  88403. */
  88404. PhysicsImpostor.prototype._init = function () {
  88405. if (!this._physicsEngine) {
  88406. return;
  88407. }
  88408. this._physicsEngine.removeImpostor(this);
  88409. this.physicsBody = null;
  88410. this._parent = this._parent || this._getPhysicsParent();
  88411. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  88412. this._physicsEngine.addImpostor(this);
  88413. }
  88414. };
  88415. PhysicsImpostor.prototype._getPhysicsParent = function () {
  88416. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  88417. var parentMesh = this.object.parent;
  88418. return parentMesh.physicsImpostor;
  88419. }
  88420. return null;
  88421. };
  88422. /**
  88423. * Should a new body be generated.
  88424. */
  88425. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  88426. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  88427. };
  88428. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  88429. this.forceUpdate();
  88430. };
  88431. /**
  88432. * Force a regeneration of this or the parent's impostor's body.
  88433. * Use under cautious - This will remove all joints already implemented.
  88434. */
  88435. PhysicsImpostor.prototype.forceUpdate = function () {
  88436. this._init();
  88437. if (this.parent && !this._options.ignoreParent) {
  88438. this.parent.forceUpdate();
  88439. }
  88440. };
  88441. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  88442. /*public get mesh(): AbstractMesh {
  88443. return this._mesh;
  88444. }*/
  88445. /**
  88446. * Gets the body that holds this impostor. Either its own, or its parent.
  88447. */
  88448. get: function () {
  88449. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  88450. },
  88451. /**
  88452. * Set the physics body. Used mainly by the physics engine/plugin
  88453. */
  88454. set: function (physicsBody) {
  88455. if (this._physicsBody && this._physicsEngine) {
  88456. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  88457. }
  88458. this._physicsBody = physicsBody;
  88459. this.resetUpdateFlags();
  88460. },
  88461. enumerable: true,
  88462. configurable: true
  88463. });
  88464. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  88465. get: function () {
  88466. return !this._options.ignoreParent && this._parent ? this._parent : null;
  88467. },
  88468. set: function (value) {
  88469. this._parent = value;
  88470. },
  88471. enumerable: true,
  88472. configurable: true
  88473. });
  88474. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  88475. this._bodyUpdateRequired = false;
  88476. };
  88477. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  88478. if (this.object.getBoundingInfo) {
  88479. var q = this.object.rotationQuaternion;
  88480. //reset rotation
  88481. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  88482. //calculate the world matrix with no rotation
  88483. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  88484. var boundingInfo = this.object.getBoundingInfo();
  88485. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  88486. //bring back the rotation
  88487. this.object.rotationQuaternion = q;
  88488. //calculate the world matrix with the new rotation
  88489. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  88490. return size;
  88491. }
  88492. else {
  88493. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  88494. }
  88495. };
  88496. PhysicsImpostor.prototype.getObjectCenter = function () {
  88497. if (this.object.getBoundingInfo) {
  88498. var boundingInfo = this.object.getBoundingInfo();
  88499. return boundingInfo.boundingBox.centerWorld;
  88500. }
  88501. else {
  88502. return this.object.position;
  88503. }
  88504. };
  88505. /**
  88506. * Get a specific parametes from the options parameter.
  88507. */
  88508. PhysicsImpostor.prototype.getParam = function (paramName) {
  88509. return this._options[paramName];
  88510. };
  88511. /**
  88512. * Sets a specific parameter in the options given to the physics plugin
  88513. */
  88514. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  88515. this._options[paramName] = value;
  88516. this._bodyUpdateRequired = true;
  88517. };
  88518. /**
  88519. * Specifically change the body's mass option. Won't recreate the physics body object
  88520. */
  88521. PhysicsImpostor.prototype.setMass = function (mass) {
  88522. if (this.getParam("mass") !== mass) {
  88523. this.setParam("mass", mass);
  88524. }
  88525. if (this._physicsEngine) {
  88526. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  88527. }
  88528. };
  88529. PhysicsImpostor.prototype.getLinearVelocity = function () {
  88530. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  88531. };
  88532. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  88533. if (this._physicsEngine) {
  88534. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  88535. }
  88536. };
  88537. PhysicsImpostor.prototype.getAngularVelocity = function () {
  88538. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  88539. };
  88540. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  88541. if (this._physicsEngine) {
  88542. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  88543. }
  88544. };
  88545. /**
  88546. * Execute a function with the physics plugin native code.
  88547. * Provide a function the will have two variables - the world object and the physics body object.
  88548. */
  88549. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  88550. if (this._physicsEngine) {
  88551. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  88552. }
  88553. };
  88554. /**
  88555. * Register a function that will be executed before the physics world is stepping forward.
  88556. */
  88557. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  88558. this._onBeforePhysicsStepCallbacks.push(func);
  88559. };
  88560. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  88561. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  88562. if (index > -1) {
  88563. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  88564. }
  88565. else {
  88566. BABYLON.Tools.Warn("Function to remove was not found");
  88567. }
  88568. };
  88569. /**
  88570. * Register a function that will be executed after the physics step
  88571. */
  88572. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  88573. this._onAfterPhysicsStepCallbacks.push(func);
  88574. };
  88575. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  88576. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  88577. if (index > -1) {
  88578. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  88579. }
  88580. else {
  88581. BABYLON.Tools.Warn("Function to remove was not found");
  88582. }
  88583. };
  88584. /**
  88585. * register a function that will be executed when this impostor collides against a different body.
  88586. */
  88587. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  88588. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  88589. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  88590. };
  88591. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  88592. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  88593. var index = -1;
  88594. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  88595. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  88596. // chcek the arrays match
  88597. var sameList = cbDef.otherImpostors.every(function (impostor) {
  88598. return collidedAgainstList.indexOf(impostor) > -1;
  88599. });
  88600. if (sameList) {
  88601. index = idx;
  88602. }
  88603. return sameList;
  88604. }
  88605. return false;
  88606. });
  88607. if (found) {
  88608. this._onPhysicsCollideCallbacks.splice(index, 1);
  88609. }
  88610. else {
  88611. BABYLON.Tools.Warn("Function to remove was not found");
  88612. }
  88613. };
  88614. PhysicsImpostor.prototype.getParentsRotation = function () {
  88615. var parent = this.object.parent;
  88616. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  88617. while (parent) {
  88618. if (parent.rotationQuaternion) {
  88619. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  88620. }
  88621. else {
  88622. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  88623. }
  88624. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  88625. parent = parent.parent;
  88626. }
  88627. return this._tmpQuat;
  88628. };
  88629. /**
  88630. * Apply a force
  88631. */
  88632. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  88633. if (this._physicsEngine) {
  88634. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  88635. }
  88636. return this;
  88637. };
  88638. /**
  88639. * Apply an impulse
  88640. */
  88641. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  88642. if (this._physicsEngine) {
  88643. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  88644. }
  88645. return this;
  88646. };
  88647. /**
  88648. * A help function to create a joint.
  88649. */
  88650. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  88651. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  88652. this.addJoint(otherImpostor, joint);
  88653. return this;
  88654. };
  88655. /**
  88656. * Add a joint to this impostor with a different impostor.
  88657. */
  88658. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  88659. this._joints.push({
  88660. otherImpostor: otherImpostor,
  88661. joint: joint
  88662. });
  88663. if (this._physicsEngine) {
  88664. this._physicsEngine.addJoint(this, otherImpostor, joint);
  88665. }
  88666. return this;
  88667. };
  88668. /**
  88669. * Will keep this body still, in a sleep mode.
  88670. */
  88671. PhysicsImpostor.prototype.sleep = function () {
  88672. if (this._physicsEngine) {
  88673. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  88674. }
  88675. return this;
  88676. };
  88677. /**
  88678. * Wake the body up.
  88679. */
  88680. PhysicsImpostor.prototype.wakeUp = function () {
  88681. if (this._physicsEngine) {
  88682. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  88683. }
  88684. return this;
  88685. };
  88686. PhysicsImpostor.prototype.clone = function (newObject) {
  88687. if (!newObject)
  88688. return null;
  88689. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  88690. };
  88691. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  88692. var _this = this;
  88693. //no dispose if no physics engine is available.
  88694. if (!this._physicsEngine) {
  88695. return;
  88696. }
  88697. this._joints.forEach(function (j) {
  88698. if (_this._physicsEngine) {
  88699. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  88700. }
  88701. });
  88702. //dispose the physics body
  88703. this._physicsEngine.removeImpostor(this);
  88704. if (this.parent) {
  88705. this.parent.forceUpdate();
  88706. }
  88707. else {
  88708. /*this._object.getChildMeshes().forEach(function(mesh) {
  88709. if (mesh.physicsImpostor) {
  88710. if (disposeChildren) {
  88711. mesh.physicsImpostor.dispose();
  88712. mesh.physicsImpostor = null;
  88713. }
  88714. }
  88715. })*/
  88716. }
  88717. this._isDisposed = true;
  88718. };
  88719. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  88720. this._deltaPosition.copyFrom(position);
  88721. };
  88722. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  88723. if (!this._deltaRotation) {
  88724. this._deltaRotation = new BABYLON.Quaternion();
  88725. }
  88726. this._deltaRotation.copyFrom(rotation);
  88727. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  88728. };
  88729. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  88730. if (this._physicsEngine) {
  88731. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  88732. }
  88733. return this;
  88734. };
  88735. PhysicsImpostor.prototype.getRadius = function () {
  88736. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  88737. };
  88738. /**
  88739. * Sync a bone with this impostor
  88740. * @param bone The bone to sync to the impostor.
  88741. * @param boneMesh The mesh that the bone is influencing.
  88742. * @param jointPivot The pivot of the joint / bone in local space.
  88743. * @param distToJoint Optional distance from the impostor to the joint.
  88744. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  88745. */
  88746. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  88747. var tempVec = PhysicsImpostor._tmpVecs[0];
  88748. var mesh = this.object;
  88749. if (mesh.rotationQuaternion) {
  88750. if (adjustRotation) {
  88751. var tempQuat = PhysicsImpostor._tmpQuat;
  88752. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  88753. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  88754. }
  88755. else {
  88756. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  88757. }
  88758. }
  88759. tempVec.x = 0;
  88760. tempVec.y = 0;
  88761. tempVec.z = 0;
  88762. if (jointPivot) {
  88763. tempVec.x = jointPivot.x;
  88764. tempVec.y = jointPivot.y;
  88765. tempVec.z = jointPivot.z;
  88766. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  88767. if (distToJoint === undefined || distToJoint === null) {
  88768. distToJoint = jointPivot.length();
  88769. }
  88770. tempVec.x *= distToJoint;
  88771. tempVec.y *= distToJoint;
  88772. tempVec.z *= distToJoint;
  88773. }
  88774. if (bone.getParent()) {
  88775. tempVec.addInPlace(mesh.getAbsolutePosition());
  88776. bone.setAbsolutePosition(tempVec, boneMesh);
  88777. }
  88778. else {
  88779. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  88780. boneMesh.position.x -= tempVec.x;
  88781. boneMesh.position.y -= tempVec.y;
  88782. boneMesh.position.z -= tempVec.z;
  88783. }
  88784. };
  88785. /**
  88786. * Sync impostor to a bone
  88787. * @param bone The bone that the impostor will be synced to.
  88788. * @param boneMesh The mesh that the bone is influencing.
  88789. * @param jointPivot The pivot of the joint / bone in local space.
  88790. * @param distToJoint Optional distance from the impostor to the joint.
  88791. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  88792. * @param boneAxis Optional vector3 axis the bone is aligned with
  88793. */
  88794. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  88795. var mesh = this.object;
  88796. if (mesh.rotationQuaternion) {
  88797. if (adjustRotation) {
  88798. var tempQuat = PhysicsImpostor._tmpQuat;
  88799. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  88800. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  88801. }
  88802. else {
  88803. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  88804. }
  88805. }
  88806. var pos = PhysicsImpostor._tmpVecs[0];
  88807. var boneDir = PhysicsImpostor._tmpVecs[1];
  88808. if (!boneAxis) {
  88809. boneAxis = PhysicsImpostor._tmpVecs[2];
  88810. boneAxis.x = 0;
  88811. boneAxis.y = 1;
  88812. boneAxis.z = 0;
  88813. }
  88814. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  88815. bone.getAbsolutePositionToRef(boneMesh, pos);
  88816. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  88817. distToJoint = jointPivot.length();
  88818. }
  88819. if (distToJoint !== undefined && distToJoint !== null) {
  88820. pos.x += boneDir.x * distToJoint;
  88821. pos.y += boneDir.y * distToJoint;
  88822. pos.z += boneDir.z * distToJoint;
  88823. }
  88824. mesh.setAbsolutePosition(pos);
  88825. };
  88826. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  88827. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  88828. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88829. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  88830. //Impostor types
  88831. PhysicsImpostor.NoImpostor = 0;
  88832. PhysicsImpostor.SphereImpostor = 1;
  88833. PhysicsImpostor.BoxImpostor = 2;
  88834. PhysicsImpostor.PlaneImpostor = 3;
  88835. PhysicsImpostor.MeshImpostor = 4;
  88836. PhysicsImpostor.CylinderImpostor = 7;
  88837. PhysicsImpostor.ParticleImpostor = 8;
  88838. PhysicsImpostor.HeightmapImpostor = 9;
  88839. return PhysicsImpostor;
  88840. }());
  88841. BABYLON.PhysicsImpostor = PhysicsImpostor;
  88842. })(BABYLON || (BABYLON = {}));
  88843. //# sourceMappingURL=babylon.physicsImpostor.js.map
  88844. var BABYLON;
  88845. (function (BABYLON) {
  88846. var PhysicsEngine = /** @class */ (function () {
  88847. function PhysicsEngine(gravity, _physicsPlugin) {
  88848. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  88849. this._physicsPlugin = _physicsPlugin;
  88850. //new methods and parameters
  88851. this._impostors = [];
  88852. this._joints = [];
  88853. if (!this._physicsPlugin.isSupported()) {
  88854. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  88855. + "Please make sure it is included.");
  88856. }
  88857. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  88858. this.setGravity(gravity);
  88859. this.setTimeStep();
  88860. }
  88861. PhysicsEngine.prototype.setGravity = function (gravity) {
  88862. this.gravity = gravity;
  88863. this._physicsPlugin.setGravity(this.gravity);
  88864. };
  88865. /**
  88866. * Set the time step of the physics engine.
  88867. * default is 1/60.
  88868. * To slow it down, enter 1/600 for example.
  88869. * To speed it up, 1/30
  88870. * @param {number} newTimeStep the new timestep to apply to this world.
  88871. */
  88872. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  88873. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  88874. this._physicsPlugin.setTimeStep(newTimeStep);
  88875. };
  88876. /**
  88877. * Get the time step of the physics engine.
  88878. */
  88879. PhysicsEngine.prototype.getTimeStep = function () {
  88880. return this._physicsPlugin.getTimeStep();
  88881. };
  88882. PhysicsEngine.prototype.dispose = function () {
  88883. this._impostors.forEach(function (impostor) {
  88884. impostor.dispose();
  88885. });
  88886. this._physicsPlugin.dispose();
  88887. };
  88888. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  88889. return this._physicsPlugin.name;
  88890. };
  88891. /**
  88892. * Adding a new impostor for the impostor tracking.
  88893. * This will be done by the impostor itself.
  88894. * @param {PhysicsImpostor} impostor the impostor to add
  88895. */
  88896. PhysicsEngine.prototype.addImpostor = function (impostor) {
  88897. impostor.uniqueId = this._impostors.push(impostor);
  88898. //if no parent, generate the body
  88899. if (!impostor.parent) {
  88900. this._physicsPlugin.generatePhysicsBody(impostor);
  88901. }
  88902. };
  88903. /**
  88904. * Remove an impostor from the engine.
  88905. * This impostor and its mesh will not longer be updated by the physics engine.
  88906. * @param {PhysicsImpostor} impostor the impostor to remove
  88907. */
  88908. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  88909. var index = this._impostors.indexOf(impostor);
  88910. if (index > -1) {
  88911. var removed = this._impostors.splice(index, 1);
  88912. //Is it needed?
  88913. if (removed.length) {
  88914. //this will also remove it from the world.
  88915. removed[0].physicsBody = null;
  88916. }
  88917. }
  88918. };
  88919. /**
  88920. * Add a joint to the physics engine
  88921. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  88922. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  88923. * @param {PhysicsJoint} the joint that will connect both impostors.
  88924. */
  88925. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  88926. var impostorJoint = {
  88927. mainImpostor: mainImpostor,
  88928. connectedImpostor: connectedImpostor,
  88929. joint: joint
  88930. };
  88931. joint.physicsPlugin = this._physicsPlugin;
  88932. this._joints.push(impostorJoint);
  88933. this._physicsPlugin.generateJoint(impostorJoint);
  88934. };
  88935. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  88936. var matchingJoints = this._joints.filter(function (impostorJoint) {
  88937. return (impostorJoint.connectedImpostor === connectedImpostor
  88938. && impostorJoint.joint === joint
  88939. && impostorJoint.mainImpostor === mainImpostor);
  88940. });
  88941. if (matchingJoints.length) {
  88942. this._physicsPlugin.removeJoint(matchingJoints[0]);
  88943. //TODO remove it from the list as well
  88944. }
  88945. };
  88946. /**
  88947. * Called by the scene. no need to call it.
  88948. * @hidden
  88949. */
  88950. PhysicsEngine.prototype._step = function (delta) {
  88951. var _this = this;
  88952. //check if any mesh has no body / requires an update
  88953. this._impostors.forEach(function (impostor) {
  88954. if (impostor.isBodyInitRequired()) {
  88955. _this._physicsPlugin.generatePhysicsBody(impostor);
  88956. }
  88957. });
  88958. if (delta > 0.1) {
  88959. delta = 0.1;
  88960. }
  88961. else if (delta <= 0) {
  88962. delta = 1.0 / 60.0;
  88963. }
  88964. this._physicsPlugin.executeStep(delta, this._impostors);
  88965. };
  88966. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  88967. return this._physicsPlugin;
  88968. };
  88969. PhysicsEngine.prototype.getImpostors = function () {
  88970. return this._impostors;
  88971. };
  88972. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  88973. for (var i = 0; i < this._impostors.length; ++i) {
  88974. if (this._impostors[i].object === object) {
  88975. return this._impostors[i];
  88976. }
  88977. }
  88978. return null;
  88979. };
  88980. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  88981. for (var i = 0; i < this._impostors.length; ++i) {
  88982. if (this._impostors[i].physicsBody === body) {
  88983. return this._impostors[i];
  88984. }
  88985. }
  88986. return null;
  88987. };
  88988. // Statics
  88989. PhysicsEngine.Epsilon = 0.001;
  88990. return PhysicsEngine;
  88991. }());
  88992. BABYLON.PhysicsEngine = PhysicsEngine;
  88993. })(BABYLON || (BABYLON = {}));
  88994. //# sourceMappingURL=babylon.physicsEngine.js.map
  88995. var BABYLON;
  88996. (function (BABYLON) {
  88997. var PhysicsHelper = /** @class */ (function () {
  88998. function PhysicsHelper(scene) {
  88999. this._scene = scene;
  89000. this._physicsEngine = this._scene.getPhysicsEngine();
  89001. if (!this._physicsEngine) {
  89002. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  89003. }
  89004. }
  89005. /**
  89006. * @param {Vector3} origin the origin of the explosion
  89007. * @param {number} radius the explosion radius
  89008. * @param {number} strength the explosion strength
  89009. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89010. */
  89011. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  89012. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89013. if (!this._physicsEngine) {
  89014. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  89015. return null;
  89016. }
  89017. var impostors = this._physicsEngine.getImpostors();
  89018. if (impostors.length === 0) {
  89019. return null;
  89020. }
  89021. var event = new PhysicsRadialExplosionEvent(this._scene);
  89022. impostors.forEach(function (impostor) {
  89023. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  89024. if (!impostorForceAndContactPoint) {
  89025. return;
  89026. }
  89027. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89028. });
  89029. event.dispose(false);
  89030. return event;
  89031. };
  89032. /**
  89033. * @param {Vector3} origin the origin of the explosion
  89034. * @param {number} radius the explosion radius
  89035. * @param {number} strength the explosion strength
  89036. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89037. */
  89038. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  89039. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89040. if (!this._physicsEngine) {
  89041. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89042. return null;
  89043. }
  89044. var impostors = this._physicsEngine.getImpostors();
  89045. if (impostors.length === 0) {
  89046. return null;
  89047. }
  89048. var event = new PhysicsRadialExplosionEvent(this._scene);
  89049. impostors.forEach(function (impostor) {
  89050. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  89051. if (!impostorForceAndContactPoint) {
  89052. return;
  89053. }
  89054. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89055. });
  89056. event.dispose(false);
  89057. return event;
  89058. };
  89059. /**
  89060. * @param {Vector3} origin the origin of the explosion
  89061. * @param {number} radius the explosion radius
  89062. * @param {number} strength the explosion strength
  89063. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89064. */
  89065. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  89066. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89067. if (!this._physicsEngine) {
  89068. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89069. return null;
  89070. }
  89071. var impostors = this._physicsEngine.getImpostors();
  89072. if (impostors.length === 0) {
  89073. return null;
  89074. }
  89075. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  89076. event.dispose(false);
  89077. return event;
  89078. };
  89079. /**
  89080. * @param {Vector3} origin the origin of the updraft
  89081. * @param {number} radius the radius of the updraft
  89082. * @param {number} strength the strength of the updraft
  89083. * @param {number} height the height of the updraft
  89084. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  89085. */
  89086. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  89087. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  89088. if (!this._physicsEngine) {
  89089. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89090. return null;
  89091. }
  89092. if (this._physicsEngine.getImpostors().length === 0) {
  89093. return null;
  89094. }
  89095. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  89096. event.dispose(false);
  89097. return event;
  89098. };
  89099. /**
  89100. * @param {Vector3} origin the of the vortex
  89101. * @param {number} radius the radius of the vortex
  89102. * @param {number} strength the strength of the vortex
  89103. * @param {number} height the height of the vortex
  89104. */
  89105. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  89106. if (!this._physicsEngine) {
  89107. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89108. return null;
  89109. }
  89110. if (this._physicsEngine.getImpostors().length === 0) {
  89111. return null;
  89112. }
  89113. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  89114. event.dispose(false);
  89115. return event;
  89116. };
  89117. return PhysicsHelper;
  89118. }());
  89119. BABYLON.PhysicsHelper = PhysicsHelper;
  89120. /***** Radial explosion *****/
  89121. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  89122. function PhysicsRadialExplosionEvent(scene) {
  89123. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  89124. this._rays = [];
  89125. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  89126. this._scene = scene;
  89127. }
  89128. /**
  89129. * Returns the data related to the radial explosion event (sphere & rays).
  89130. * @returns {PhysicsRadialExplosionEventData}
  89131. */
  89132. PhysicsRadialExplosionEvent.prototype.getData = function () {
  89133. this._dataFetched = true;
  89134. return {
  89135. sphere: this._sphere,
  89136. rays: this._rays,
  89137. };
  89138. };
  89139. /**
  89140. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  89141. * @param impostor
  89142. * @param {Vector3} origin the origin of the explosion
  89143. * @param {number} radius the explosion radius
  89144. * @param {number} strength the explosion strength
  89145. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  89146. * @returns {Nullable<PhysicsForceAndContactPoint>}
  89147. */
  89148. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  89149. if (impostor.mass === 0) {
  89150. return null;
  89151. }
  89152. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  89153. return null;
  89154. }
  89155. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  89156. return null;
  89157. }
  89158. var impostorObjectCenter = impostor.getObjectCenter();
  89159. var direction = impostorObjectCenter.subtract(origin);
  89160. var ray = new BABYLON.Ray(origin, direction, radius);
  89161. this._rays.push(ray);
  89162. var hit = ray.intersectsMesh(impostor.object);
  89163. var contactPoint = hit.pickedPoint;
  89164. if (!contactPoint) {
  89165. return null;
  89166. }
  89167. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  89168. if (distanceFromOrigin > radius) {
  89169. return null;
  89170. }
  89171. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  89172. ? strength
  89173. : strength * (1 - (distanceFromOrigin / radius));
  89174. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89175. return { force: force, contactPoint: contactPoint };
  89176. };
  89177. /**
  89178. * Disposes the sphere.
  89179. * @param {bolean} force
  89180. */
  89181. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  89182. var _this = this;
  89183. if (force === void 0) { force = true; }
  89184. if (force) {
  89185. this._sphere.dispose();
  89186. }
  89187. else {
  89188. setTimeout(function () {
  89189. if (!_this._dataFetched) {
  89190. _this._sphere.dispose();
  89191. }
  89192. }, 0);
  89193. }
  89194. };
  89195. /*** Helpers ***/
  89196. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  89197. if (!this._sphere) {
  89198. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  89199. this._sphere.isVisible = false;
  89200. }
  89201. };
  89202. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  89203. var impostorObject = impostor.object;
  89204. this._prepareSphere();
  89205. this._sphere.position = origin;
  89206. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  89207. this._sphere._updateBoundingInfo();
  89208. this._sphere.computeWorldMatrix(true);
  89209. return this._sphere.intersectsMesh(impostorObject, true);
  89210. };
  89211. return PhysicsRadialExplosionEvent;
  89212. }());
  89213. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  89214. /***** Gravitational Field *****/
  89215. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  89216. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  89217. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89218. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89219. this._physicsHelper = physicsHelper;
  89220. this._scene = scene;
  89221. this._origin = origin;
  89222. this._radius = radius;
  89223. this._strength = strength;
  89224. this._falloff = falloff;
  89225. this._tickCallback = this._tick.bind(this);
  89226. }
  89227. /**
  89228. * Returns the data related to the gravitational field event (sphere).
  89229. * @returns {PhysicsGravitationalFieldEventData}
  89230. */
  89231. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  89232. this._dataFetched = true;
  89233. return {
  89234. sphere: this._sphere,
  89235. };
  89236. };
  89237. /**
  89238. * Enables the gravitational field.
  89239. */
  89240. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  89241. this._tickCallback.call(this);
  89242. this._scene.registerBeforeRender(this._tickCallback);
  89243. };
  89244. /**
  89245. * Disables the gravitational field.
  89246. */
  89247. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  89248. this._scene.unregisterBeforeRender(this._tickCallback);
  89249. };
  89250. /**
  89251. * Disposes the sphere.
  89252. * @param {bolean} force
  89253. */
  89254. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  89255. var _this = this;
  89256. if (force === void 0) { force = true; }
  89257. if (force) {
  89258. this._sphere.dispose();
  89259. }
  89260. else {
  89261. setTimeout(function () {
  89262. if (!_this._dataFetched) {
  89263. _this._sphere.dispose();
  89264. }
  89265. }, 0);
  89266. }
  89267. };
  89268. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  89269. // Since the params won't change, we fetch the event only once
  89270. if (this._sphere) {
  89271. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89272. }
  89273. else {
  89274. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89275. if (radialExplosionEvent) {
  89276. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  89277. }
  89278. }
  89279. };
  89280. return PhysicsGravitationalFieldEvent;
  89281. }());
  89282. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  89283. /***** Updraft *****/
  89284. var PhysicsUpdraftEvent = /** @class */ (function () {
  89285. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  89286. this._scene = _scene;
  89287. this._origin = _origin;
  89288. this._radius = _radius;
  89289. this._strength = _strength;
  89290. this._height = _height;
  89291. this._updraftMode = _updraftMode;
  89292. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  89293. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  89294. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  89295. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89296. this._physicsEngine = this._scene.getPhysicsEngine();
  89297. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  89298. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  89299. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89300. this._originDirection = this._origin.subtract(this._originTop).normalize();
  89301. }
  89302. this._tickCallback = this._tick.bind(this);
  89303. }
  89304. /**
  89305. * Returns the data related to the updraft event (cylinder).
  89306. * @returns {PhysicsUpdraftEventData}
  89307. */
  89308. PhysicsUpdraftEvent.prototype.getData = function () {
  89309. this._dataFetched = true;
  89310. return {
  89311. cylinder: this._cylinder,
  89312. };
  89313. };
  89314. /**
  89315. * Enables the updraft.
  89316. */
  89317. PhysicsUpdraftEvent.prototype.enable = function () {
  89318. this._tickCallback.call(this);
  89319. this._scene.registerBeforeRender(this._tickCallback);
  89320. };
  89321. /**
  89322. * Disables the cortex.
  89323. */
  89324. PhysicsUpdraftEvent.prototype.disable = function () {
  89325. this._scene.unregisterBeforeRender(this._tickCallback);
  89326. };
  89327. /**
  89328. * Disposes the sphere.
  89329. * @param {bolean} force
  89330. */
  89331. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  89332. var _this = this;
  89333. if (force === void 0) { force = true; }
  89334. if (force) {
  89335. this._cylinder.dispose();
  89336. }
  89337. else {
  89338. setTimeout(function () {
  89339. if (!_this._dataFetched) {
  89340. _this._cylinder.dispose();
  89341. }
  89342. }, 0);
  89343. }
  89344. };
  89345. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  89346. if (impostor.mass === 0) {
  89347. return null;
  89348. }
  89349. if (!this._intersectsWithCylinder(impostor)) {
  89350. return null;
  89351. }
  89352. var impostorObjectCenter = impostor.getObjectCenter();
  89353. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89354. var direction = this._originDirection;
  89355. }
  89356. else {
  89357. var direction = impostorObjectCenter.subtract(this._originTop);
  89358. }
  89359. var multiplier = this._strength * -1;
  89360. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89361. return { force: force, contactPoint: impostorObjectCenter };
  89362. };
  89363. PhysicsUpdraftEvent.prototype._tick = function () {
  89364. var _this = this;
  89365. this._physicsEngine.getImpostors().forEach(function (impostor) {
  89366. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  89367. if (!impostorForceAndContactPoint) {
  89368. return;
  89369. }
  89370. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89371. });
  89372. };
  89373. /*** Helpers ***/
  89374. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  89375. if (!this._cylinder) {
  89376. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  89377. height: this._height,
  89378. diameter: this._radius * 2,
  89379. }, this._scene);
  89380. this._cylinder.isVisible = false;
  89381. }
  89382. };
  89383. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  89384. var impostorObject = impostor.object;
  89385. this._prepareCylinder();
  89386. this._cylinder.position = this._cylinderPosition;
  89387. return this._cylinder.intersectsMesh(impostorObject, true);
  89388. };
  89389. return PhysicsUpdraftEvent;
  89390. }());
  89391. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  89392. /***** Vortex *****/
  89393. var PhysicsVortexEvent = /** @class */ (function () {
  89394. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  89395. this._scene = _scene;
  89396. this._origin = _origin;
  89397. this._radius = _radius;
  89398. this._strength = _strength;
  89399. this._height = _height;
  89400. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  89401. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  89402. this._updraftMultiplier = 0.02;
  89403. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  89404. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89405. this._physicsEngine = this._scene.getPhysicsEngine();
  89406. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  89407. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  89408. this._tickCallback = this._tick.bind(this);
  89409. }
  89410. /**
  89411. * Returns the data related to the vortex event (cylinder).
  89412. * @returns {PhysicsVortexEventData}
  89413. */
  89414. PhysicsVortexEvent.prototype.getData = function () {
  89415. this._dataFetched = true;
  89416. return {
  89417. cylinder: this._cylinder,
  89418. };
  89419. };
  89420. /**
  89421. * Enables the vortex.
  89422. */
  89423. PhysicsVortexEvent.prototype.enable = function () {
  89424. this._tickCallback.call(this);
  89425. this._scene.registerBeforeRender(this._tickCallback);
  89426. };
  89427. /**
  89428. * Disables the cortex.
  89429. */
  89430. PhysicsVortexEvent.prototype.disable = function () {
  89431. this._scene.unregisterBeforeRender(this._tickCallback);
  89432. };
  89433. /**
  89434. * Disposes the sphere.
  89435. * @param {bolean} force
  89436. */
  89437. PhysicsVortexEvent.prototype.dispose = function (force) {
  89438. var _this = this;
  89439. if (force === void 0) { force = true; }
  89440. if (force) {
  89441. this._cylinder.dispose();
  89442. }
  89443. else {
  89444. setTimeout(function () {
  89445. if (!_this._dataFetched) {
  89446. _this._cylinder.dispose();
  89447. }
  89448. }, 0);
  89449. }
  89450. };
  89451. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  89452. if (impostor.mass === 0) {
  89453. return null;
  89454. }
  89455. if (!this._intersectsWithCylinder(impostor)) {
  89456. return null;
  89457. }
  89458. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  89459. return null;
  89460. }
  89461. var impostorObjectCenter = impostor.getObjectCenter();
  89462. 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)
  89463. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  89464. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  89465. var hit = ray.intersectsMesh(impostor.object);
  89466. var contactPoint = hit.pickedPoint;
  89467. if (!contactPoint) {
  89468. return null;
  89469. }
  89470. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  89471. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  89472. var directionToOrigin = contactPoint.normalize();
  89473. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  89474. directionToOrigin = directionToOrigin.negate();
  89475. }
  89476. // TODO: find a more physically based solution
  89477. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  89478. var forceX = directionToOrigin.x * this._strength / 8;
  89479. var forceY = directionToOrigin.y * this._updraftMultiplier;
  89480. var forceZ = directionToOrigin.z * this._strength / 8;
  89481. }
  89482. else {
  89483. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  89484. var forceY = this._originTop.y * this._updraftMultiplier;
  89485. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  89486. }
  89487. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  89488. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  89489. return { force: force, contactPoint: impostorObjectCenter };
  89490. };
  89491. PhysicsVortexEvent.prototype._tick = function () {
  89492. var _this = this;
  89493. this._physicsEngine.getImpostors().forEach(function (impostor) {
  89494. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  89495. if (!impostorForceAndContactPoint) {
  89496. return;
  89497. }
  89498. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89499. });
  89500. };
  89501. /*** Helpers ***/
  89502. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  89503. if (!this._cylinder) {
  89504. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  89505. height: this._height,
  89506. diameter: this._radius * 2,
  89507. }, this._scene);
  89508. this._cylinder.isVisible = false;
  89509. }
  89510. };
  89511. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  89512. var impostorObject = impostor.object;
  89513. this._prepareCylinder();
  89514. this._cylinder.position = this._cylinderPosition;
  89515. return this._cylinder.intersectsMesh(impostorObject, true);
  89516. };
  89517. return PhysicsVortexEvent;
  89518. }());
  89519. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  89520. /***** Enums *****/
  89521. /**
  89522. * The strenght of the force in correspondence to the distance of the affected object
  89523. */
  89524. var PhysicsRadialImpulseFalloff;
  89525. (function (PhysicsRadialImpulseFalloff) {
  89526. /** Defines that impulse is constant in strength across it's whole radius */
  89527. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  89528. /** DEfines that impulse gets weaker if it's further from the origin */
  89529. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  89530. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  89531. /**
  89532. * The strenght of the force in correspondence to the distance of the affected object
  89533. */
  89534. var PhysicsUpdraftMode;
  89535. (function (PhysicsUpdraftMode) {
  89536. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  89537. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  89538. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  89539. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  89540. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  89541. })(BABYLON || (BABYLON = {}));
  89542. //# sourceMappingURL=babylon.physicsHelper.js.map
  89543. var BABYLON;
  89544. (function (BABYLON) {
  89545. var CannonJSPlugin = /** @class */ (function () {
  89546. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  89547. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  89548. if (iterations === void 0) { iterations = 10; }
  89549. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  89550. this.name = "CannonJSPlugin";
  89551. this._physicsMaterials = new Array();
  89552. this._fixedTimeStep = 1 / 60;
  89553. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  89554. this.BJSCANNON = CANNON;
  89555. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  89556. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  89557. this._tmpPosition = BABYLON.Vector3.Zero();
  89558. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  89559. this._tmpUnityRotation = new BABYLON.Quaternion();
  89560. if (!this.isSupported()) {
  89561. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  89562. return;
  89563. }
  89564. this._extendNamespace();
  89565. this.world = new this.BJSCANNON.World();
  89566. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  89567. this.world.solver.iterations = iterations;
  89568. }
  89569. CannonJSPlugin.prototype.setGravity = function (gravity) {
  89570. this.world.gravity.copy(gravity);
  89571. };
  89572. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  89573. this._fixedTimeStep = timeStep;
  89574. };
  89575. CannonJSPlugin.prototype.getTimeStep = function () {
  89576. return this._fixedTimeStep;
  89577. };
  89578. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  89579. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  89580. };
  89581. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  89582. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  89583. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  89584. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  89585. };
  89586. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  89587. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  89588. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  89589. impostor.physicsBody.applyForce(impulse, worldPoint);
  89590. };
  89591. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  89592. //parent-child relationship. Does this impostor has a parent impostor?
  89593. if (impostor.parent) {
  89594. if (impostor.physicsBody) {
  89595. this.removePhysicsBody(impostor);
  89596. //TODO is that needed?
  89597. impostor.forceUpdate();
  89598. }
  89599. return;
  89600. }
  89601. //should a new body be created for this impostor?
  89602. if (impostor.isBodyInitRequired()) {
  89603. var shape = this._createShape(impostor);
  89604. //unregister events, if body is being changed
  89605. var oldBody = impostor.physicsBody;
  89606. if (oldBody) {
  89607. this.removePhysicsBody(impostor);
  89608. }
  89609. //create the body and material
  89610. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  89611. var bodyCreationObject = {
  89612. mass: impostor.getParam("mass"),
  89613. material: material
  89614. };
  89615. // A simple extend, in case native options were used.
  89616. var nativeOptions = impostor.getParam("nativeOptions");
  89617. for (var key in nativeOptions) {
  89618. if (nativeOptions.hasOwnProperty(key)) {
  89619. bodyCreationObject[key] = nativeOptions[key];
  89620. }
  89621. }
  89622. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  89623. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  89624. this.world.addEventListener("preStep", impostor.beforeStep);
  89625. this.world.addEventListener("postStep", impostor.afterStep);
  89626. impostor.physicsBody.addShape(shape);
  89627. this.world.add(impostor.physicsBody);
  89628. //try to keep the body moving in the right direction by taking old properties.
  89629. //Should be tested!
  89630. if (oldBody) {
  89631. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  89632. impostor.physicsBody[param].copy(oldBody[param]);
  89633. });
  89634. }
  89635. this._processChildMeshes(impostor);
  89636. }
  89637. //now update the body's transformation
  89638. this._updatePhysicsBodyTransformation(impostor);
  89639. };
  89640. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  89641. var _this = this;
  89642. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  89643. var currentRotation = mainImpostor.object.rotationQuaternion;
  89644. if (meshChildren.length) {
  89645. var processMesh = function (localPosition, mesh) {
  89646. if (!currentRotation || !mesh.rotationQuaternion) {
  89647. return;
  89648. }
  89649. var childImpostor = mesh.getPhysicsImpostor();
  89650. if (childImpostor) {
  89651. var parent = childImpostor.parent;
  89652. if (parent !== mainImpostor) {
  89653. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  89654. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  89655. if (childImpostor.physicsBody) {
  89656. _this.removePhysicsBody(childImpostor);
  89657. childImpostor.physicsBody = null;
  89658. }
  89659. childImpostor.parent = mainImpostor;
  89660. childImpostor.resetUpdateFlags();
  89661. 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));
  89662. //Add the mass of the children.
  89663. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  89664. }
  89665. }
  89666. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  89667. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  89668. };
  89669. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  89670. }
  89671. };
  89672. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  89673. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  89674. this.world.removeEventListener("preStep", impostor.beforeStep);
  89675. this.world.removeEventListener("postStep", impostor.afterStep);
  89676. this.world.remove(impostor.physicsBody);
  89677. };
  89678. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  89679. var mainBody = impostorJoint.mainImpostor.physicsBody;
  89680. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  89681. if (!mainBody || !connectedBody) {
  89682. return;
  89683. }
  89684. var constraint;
  89685. var jointData = impostorJoint.joint.jointData;
  89686. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  89687. var constraintData = {
  89688. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  89689. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  89690. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  89691. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  89692. maxForce: jointData.nativeParams.maxForce,
  89693. collideConnected: !!jointData.collision
  89694. };
  89695. switch (impostorJoint.joint.type) {
  89696. case BABYLON.PhysicsJoint.HingeJoint:
  89697. case BABYLON.PhysicsJoint.Hinge2Joint:
  89698. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  89699. break;
  89700. case BABYLON.PhysicsJoint.DistanceJoint:
  89701. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  89702. break;
  89703. case BABYLON.PhysicsJoint.SpringJoint:
  89704. var springData = jointData;
  89705. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  89706. restLength: springData.length,
  89707. stiffness: springData.stiffness,
  89708. damping: springData.damping,
  89709. localAnchorA: constraintData.pivotA,
  89710. localAnchorB: constraintData.pivotB
  89711. });
  89712. break;
  89713. case BABYLON.PhysicsJoint.LockJoint:
  89714. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  89715. break;
  89716. case BABYLON.PhysicsJoint.PointToPointJoint:
  89717. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  89718. default:
  89719. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  89720. break;
  89721. }
  89722. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  89723. constraint.collideConnected = !!jointData.collision;
  89724. impostorJoint.joint.physicsJoint = constraint;
  89725. //don't add spring as constraint, as it is not one.
  89726. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  89727. this.world.addConstraint(constraint);
  89728. }
  89729. else {
  89730. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  89731. constraint.applyForce();
  89732. };
  89733. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  89734. }
  89735. };
  89736. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  89737. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  89738. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  89739. }
  89740. else {
  89741. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  89742. }
  89743. };
  89744. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  89745. var index;
  89746. var mat;
  89747. for (index = 0; index < this._physicsMaterials.length; index++) {
  89748. mat = this._physicsMaterials[index];
  89749. if (mat.friction === friction && mat.restitution === restitution) {
  89750. return mat;
  89751. }
  89752. }
  89753. var currentMat = new this.BJSCANNON.Material(name);
  89754. currentMat.friction = friction;
  89755. currentMat.restitution = restitution;
  89756. this._physicsMaterials.push(currentMat);
  89757. return currentMat;
  89758. };
  89759. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  89760. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  89761. };
  89762. CannonJSPlugin.prototype._createShape = function (impostor) {
  89763. var object = impostor.object;
  89764. var returnValue;
  89765. var extendSize = impostor.getObjectExtendSize();
  89766. switch (impostor.type) {
  89767. case BABYLON.PhysicsImpostor.SphereImpostor:
  89768. var radiusX = extendSize.x;
  89769. var radiusY = extendSize.y;
  89770. var radiusZ = extendSize.z;
  89771. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  89772. break;
  89773. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  89774. case BABYLON.PhysicsImpostor.CylinderImpostor:
  89775. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  89776. break;
  89777. case BABYLON.PhysicsImpostor.BoxImpostor:
  89778. var box = extendSize.scale(0.5);
  89779. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  89780. break;
  89781. case BABYLON.PhysicsImpostor.PlaneImpostor:
  89782. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  89783. returnValue = new this.BJSCANNON.Plane();
  89784. break;
  89785. case BABYLON.PhysicsImpostor.MeshImpostor:
  89786. // should transform the vertex data to world coordinates!!
  89787. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  89788. var rawFaces = object.getIndices ? object.getIndices() : [];
  89789. if (!rawVerts)
  89790. return;
  89791. // get only scale! so the object could transform correctly.
  89792. var oldPosition = object.position.clone();
  89793. var oldRotation = object.rotation && object.rotation.clone();
  89794. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  89795. object.position.copyFromFloats(0, 0, 0);
  89796. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  89797. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  89798. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  89799. var transform = object.computeWorldMatrix(true);
  89800. // convert rawVerts to object space
  89801. var temp = new Array();
  89802. var index;
  89803. for (index = 0; index < rawVerts.length; index += 3) {
  89804. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  89805. }
  89806. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  89807. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  89808. //now set back the transformation!
  89809. object.position.copyFrom(oldPosition);
  89810. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  89811. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  89812. break;
  89813. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  89814. var oldPosition2 = object.position.clone();
  89815. var oldRotation2 = object.rotation && object.rotation.clone();
  89816. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  89817. object.position.copyFromFloats(0, 0, 0);
  89818. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  89819. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  89820. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  89821. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  89822. returnValue = this._createHeightmap(object);
  89823. object.position.copyFrom(oldPosition2);
  89824. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  89825. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  89826. object.computeWorldMatrix(true);
  89827. break;
  89828. case BABYLON.PhysicsImpostor.ParticleImpostor:
  89829. returnValue = new this.BJSCANNON.Particle();
  89830. break;
  89831. }
  89832. return returnValue;
  89833. };
  89834. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  89835. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  89836. var transform = object.computeWorldMatrix(true);
  89837. // convert rawVerts to object space
  89838. var temp = new Array();
  89839. var index;
  89840. for (index = 0; index < pos.length; index += 3) {
  89841. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  89842. }
  89843. pos = temp;
  89844. var matrix = new Array();
  89845. //For now pointDepth will not be used and will be automatically calculated.
  89846. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  89847. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  89848. var boundingInfo = object.getBoundingInfo();
  89849. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  89850. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  89851. var elementSize = dim * 2 / arraySize;
  89852. for (var i = 0; i < pos.length; i = i + 3) {
  89853. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  89854. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  89855. var y = -pos[i + 2] + minY;
  89856. if (!matrix[x]) {
  89857. matrix[x] = [];
  89858. }
  89859. if (!matrix[x][z]) {
  89860. matrix[x][z] = y;
  89861. }
  89862. matrix[x][z] = Math.max(y, matrix[x][z]);
  89863. }
  89864. for (var x = 0; x <= arraySize; ++x) {
  89865. if (!matrix[x]) {
  89866. var loc = 1;
  89867. while (!matrix[(x + loc) % arraySize]) {
  89868. loc++;
  89869. }
  89870. matrix[x] = matrix[(x + loc) % arraySize].slice();
  89871. //console.log("missing x", x);
  89872. }
  89873. for (var z = 0; z <= arraySize; ++z) {
  89874. if (!matrix[x][z]) {
  89875. var loc = 1;
  89876. var newValue;
  89877. while (newValue === undefined) {
  89878. newValue = matrix[x][(z + loc++) % arraySize];
  89879. }
  89880. matrix[x][z] = newValue;
  89881. }
  89882. }
  89883. }
  89884. var shape = new this.BJSCANNON.Heightfield(matrix, {
  89885. elementSize: elementSize
  89886. });
  89887. //For future reference, needed for body transformation
  89888. shape.minY = minY;
  89889. return shape;
  89890. };
  89891. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  89892. var object = impostor.object;
  89893. //make sure it is updated...
  89894. object.computeWorldMatrix && object.computeWorldMatrix(true);
  89895. // The delta between the mesh position and the mesh bounding box center
  89896. var bInfo = object.getBoundingInfo();
  89897. if (!bInfo)
  89898. return;
  89899. var center = impostor.getObjectCenter();
  89900. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  89901. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  89902. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  89903. this._tmpPosition.copyFrom(center);
  89904. var quaternion = object.rotationQuaternion;
  89905. if (!quaternion) {
  89906. return;
  89907. }
  89908. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  89909. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  89910. //-90 DEG in X, precalculated
  89911. quaternion = quaternion.multiply(this._minus90X);
  89912. //Invert! (Precalculated, 90 deg in X)
  89913. //No need to clone. this will never change.
  89914. impostor.setDeltaRotation(this._plus90X);
  89915. }
  89916. //If it is a heightfield, if should be centered.
  89917. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  89918. var mesh = object;
  89919. var boundingInfo = mesh.getBoundingInfo();
  89920. //calculate the correct body position:
  89921. var rotationQuaternion = mesh.rotationQuaternion;
  89922. mesh.rotationQuaternion = this._tmpUnityRotation;
  89923. mesh.computeWorldMatrix(true);
  89924. //get original center with no rotation
  89925. var c = center.clone();
  89926. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  89927. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  89928. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  89929. mesh.setPreTransformMatrix(p);
  89930. mesh.computeWorldMatrix(true);
  89931. //calculate the translation
  89932. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  89933. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  89934. //add it inverted to the delta
  89935. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  89936. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  89937. //rotation is back
  89938. mesh.rotationQuaternion = rotationQuaternion;
  89939. mesh.setPreTransformMatrix(oldPivot);
  89940. mesh.computeWorldMatrix(true);
  89941. }
  89942. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  89943. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  89944. //this._tmpPosition.copyFrom(object.position);
  89945. }
  89946. impostor.setDeltaPosition(this._tmpDeltaPosition);
  89947. //Now update the impostor object
  89948. impostor.physicsBody.position.copy(this._tmpPosition);
  89949. impostor.physicsBody.quaternion.copy(quaternion);
  89950. };
  89951. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  89952. impostor.object.position.copyFrom(impostor.physicsBody.position);
  89953. if (impostor.object.rotationQuaternion) {
  89954. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  89955. }
  89956. };
  89957. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  89958. impostor.physicsBody.position.copy(newPosition);
  89959. impostor.physicsBody.quaternion.copy(newRotation);
  89960. };
  89961. CannonJSPlugin.prototype.isSupported = function () {
  89962. return this.BJSCANNON !== undefined;
  89963. };
  89964. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  89965. impostor.physicsBody.velocity.copy(velocity);
  89966. };
  89967. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  89968. impostor.physicsBody.angularVelocity.copy(velocity);
  89969. };
  89970. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  89971. var v = impostor.physicsBody.velocity;
  89972. if (!v) {
  89973. return null;
  89974. }
  89975. return new BABYLON.Vector3(v.x, v.y, v.z);
  89976. };
  89977. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  89978. var v = impostor.physicsBody.angularVelocity;
  89979. if (!v) {
  89980. return null;
  89981. }
  89982. return new BABYLON.Vector3(v.x, v.y, v.z);
  89983. };
  89984. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  89985. impostor.physicsBody.mass = mass;
  89986. impostor.physicsBody.updateMassProperties();
  89987. };
  89988. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  89989. return impostor.physicsBody.mass;
  89990. };
  89991. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  89992. return impostor.physicsBody.material.friction;
  89993. };
  89994. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  89995. impostor.physicsBody.material.friction = friction;
  89996. };
  89997. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  89998. return impostor.physicsBody.material.restitution;
  89999. };
  90000. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  90001. impostor.physicsBody.material.restitution = restitution;
  90002. };
  90003. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  90004. impostor.physicsBody.sleep();
  90005. };
  90006. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  90007. impostor.physicsBody.wakeUp();
  90008. };
  90009. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  90010. joint.physicsJoint.distance = maxDistance;
  90011. };
  90012. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  90013. // if (!motorIndex) {
  90014. // joint.physicsJoint.enableMotor();
  90015. // }
  90016. // }
  90017. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  90018. // if (!motorIndex) {
  90019. // joint.physicsJoint.disableMotor();
  90020. // }
  90021. // }
  90022. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  90023. if (!motorIndex) {
  90024. joint.physicsJoint.enableMotor();
  90025. joint.physicsJoint.setMotorSpeed(speed);
  90026. if (maxForce) {
  90027. this.setLimit(joint, maxForce);
  90028. }
  90029. }
  90030. };
  90031. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  90032. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  90033. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  90034. };
  90035. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  90036. var body = impostor.physicsBody;
  90037. mesh.position.x = body.position.x;
  90038. mesh.position.y = body.position.y;
  90039. mesh.position.z = body.position.z;
  90040. if (mesh.rotationQuaternion) {
  90041. mesh.rotationQuaternion.x = body.quaternion.x;
  90042. mesh.rotationQuaternion.y = body.quaternion.y;
  90043. mesh.rotationQuaternion.z = body.quaternion.z;
  90044. mesh.rotationQuaternion.w = body.quaternion.w;
  90045. }
  90046. };
  90047. CannonJSPlugin.prototype.getRadius = function (impostor) {
  90048. var shape = impostor.physicsBody.shapes[0];
  90049. return shape.boundingSphereRadius;
  90050. };
  90051. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  90052. var shape = impostor.physicsBody.shapes[0];
  90053. result.x = shape.halfExtents.x * 2;
  90054. result.y = shape.halfExtents.y * 2;
  90055. result.z = shape.halfExtents.z * 2;
  90056. };
  90057. CannonJSPlugin.prototype.dispose = function () {
  90058. };
  90059. CannonJSPlugin.prototype._extendNamespace = function () {
  90060. //this will force cannon to execute at least one step when using interpolation
  90061. var step_tmp1 = new this.BJSCANNON.Vec3();
  90062. var Engine = this.BJSCANNON;
  90063. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  90064. maxSubSteps = maxSubSteps || 10;
  90065. timeSinceLastCalled = timeSinceLastCalled || 0;
  90066. if (timeSinceLastCalled === 0) {
  90067. this.internalStep(dt);
  90068. this.time += dt;
  90069. }
  90070. else {
  90071. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  90072. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  90073. var t0 = performance.now();
  90074. for (var i = 0; i !== internalSteps; i++) {
  90075. this.internalStep(dt);
  90076. if (performance.now() - t0 > dt * 1000) {
  90077. break;
  90078. }
  90079. }
  90080. this.time += timeSinceLastCalled;
  90081. var h = this.time % dt;
  90082. var h_div_dt = h / dt;
  90083. var interpvelo = step_tmp1;
  90084. var bodies = this.bodies;
  90085. for (var j = 0; j !== bodies.length; j++) {
  90086. var b = bodies[j];
  90087. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  90088. b.position.vsub(b.previousPosition, interpvelo);
  90089. interpvelo.scale(h_div_dt, interpvelo);
  90090. b.position.vadd(interpvelo, b.interpolatedPosition);
  90091. }
  90092. else {
  90093. b.interpolatedPosition.copy(b.position);
  90094. b.interpolatedQuaternion.copy(b.quaternion);
  90095. }
  90096. }
  90097. }
  90098. };
  90099. };
  90100. return CannonJSPlugin;
  90101. }());
  90102. BABYLON.CannonJSPlugin = CannonJSPlugin;
  90103. })(BABYLON || (BABYLON = {}));
  90104. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  90105. var BABYLON;
  90106. (function (BABYLON) {
  90107. var OimoJSPlugin = /** @class */ (function () {
  90108. function OimoJSPlugin(iterations) {
  90109. this.name = "OimoJSPlugin";
  90110. this._tmpImpostorsArray = [];
  90111. this._tmpPositionVector = BABYLON.Vector3.Zero();
  90112. this.BJSOIMO = OIMO;
  90113. this.world = new this.BJSOIMO.World({
  90114. iterations: iterations
  90115. });
  90116. this.world.clear();
  90117. }
  90118. OimoJSPlugin.prototype.setGravity = function (gravity) {
  90119. this.world.gravity.copy(gravity);
  90120. };
  90121. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  90122. this.world.timeStep = timeStep;
  90123. };
  90124. OimoJSPlugin.prototype.getTimeStep = function () {
  90125. return this.world.timeStep;
  90126. };
  90127. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  90128. var _this = this;
  90129. impostors.forEach(function (impostor) {
  90130. impostor.beforeStep();
  90131. });
  90132. this.world.step();
  90133. impostors.forEach(function (impostor) {
  90134. impostor.afterStep();
  90135. //update the ordered impostors array
  90136. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  90137. });
  90138. //check for collisions
  90139. var contact = this.world.contacts;
  90140. while (contact !== null) {
  90141. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  90142. contact = contact.next;
  90143. continue;
  90144. }
  90145. //is this body colliding with any other? get the impostor
  90146. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  90147. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  90148. if (!mainImpostor || !collidingImpostor) {
  90149. contact = contact.next;
  90150. continue;
  90151. }
  90152. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  90153. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  90154. contact = contact.next;
  90155. }
  90156. };
  90157. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  90158. var mass = impostor.physicsBody.mass;
  90159. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  90160. };
  90161. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  90162. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  90163. this.applyImpulse(impostor, force, contactPoint);
  90164. };
  90165. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  90166. var _this = this;
  90167. //parent-child relationship. Does this impostor has a parent impostor?
  90168. if (impostor.parent) {
  90169. if (impostor.physicsBody) {
  90170. this.removePhysicsBody(impostor);
  90171. //TODO is that needed?
  90172. impostor.forceUpdate();
  90173. }
  90174. return;
  90175. }
  90176. if (impostor.isBodyInitRequired()) {
  90177. var bodyConfig = {
  90178. name: impostor.uniqueId,
  90179. //Oimo must have mass, also for static objects.
  90180. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  90181. size: [],
  90182. type: [],
  90183. pos: [],
  90184. posShape: [],
  90185. rot: [],
  90186. rotShape: [],
  90187. move: impostor.getParam("mass") !== 0,
  90188. density: impostor.getParam("mass"),
  90189. friction: impostor.getParam("friction"),
  90190. restitution: impostor.getParam("restitution"),
  90191. //Supporting older versions of Oimo
  90192. world: this.world
  90193. };
  90194. var impostors = [impostor];
  90195. var addToArray = function (parent) {
  90196. if (!parent.getChildMeshes)
  90197. return;
  90198. parent.getChildMeshes().forEach(function (m) {
  90199. if (m.physicsImpostor) {
  90200. impostors.push(m.physicsImpostor);
  90201. //m.physicsImpostor._init();
  90202. }
  90203. });
  90204. };
  90205. addToArray(impostor.object);
  90206. var checkWithEpsilon_1 = function (value) {
  90207. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  90208. };
  90209. var globalQuaternion_1 = new BABYLON.Quaternion();
  90210. impostors.forEach(function (i) {
  90211. if (!i.object.rotationQuaternion) {
  90212. return;
  90213. }
  90214. //get the correct bounding box
  90215. var oldQuaternion = i.object.rotationQuaternion;
  90216. globalQuaternion_1 = oldQuaternion.clone();
  90217. var rot = oldQuaternion.toEulerAngles();
  90218. var extendSize = i.getObjectExtendSize();
  90219. var radToDeg = 57.295779513082320876;
  90220. if (i === impostor) {
  90221. var center = impostor.getObjectCenter();
  90222. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  90223. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  90224. //Can also use Array.prototype.push.apply
  90225. bodyConfig.pos.push(center.x);
  90226. bodyConfig.pos.push(center.y);
  90227. bodyConfig.pos.push(center.z);
  90228. bodyConfig.posShape.push(0, 0, 0);
  90229. //tmp solution
  90230. bodyConfig.rot.push(0);
  90231. bodyConfig.rot.push(0);
  90232. bodyConfig.rot.push(0);
  90233. bodyConfig.rotShape.push(0, 0, 0);
  90234. }
  90235. else {
  90236. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  90237. bodyConfig.posShape.push(localPosition.x);
  90238. bodyConfig.posShape.push(localPosition.y);
  90239. bodyConfig.posShape.push(localPosition.z);
  90240. bodyConfig.pos.push(0, 0, 0);
  90241. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  90242. bodyConfig.rot.push(0);
  90243. bodyConfig.rot.push(0);
  90244. bodyConfig.rot.push(0);
  90245. bodyConfig.rotShape.push(rot.x * radToDeg);
  90246. bodyConfig.rotShape.push(rot.y * radToDeg);
  90247. bodyConfig.rotShape.push(rot.z * radToDeg);
  90248. }
  90249. // register mesh
  90250. switch (i.type) {
  90251. case BABYLON.PhysicsImpostor.ParticleImpostor:
  90252. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  90253. case BABYLON.PhysicsImpostor.SphereImpostor:
  90254. var radiusX = extendSize.x;
  90255. var radiusY = extendSize.y;
  90256. var radiusZ = extendSize.z;
  90257. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  90258. bodyConfig.type.push('sphere');
  90259. //due to the way oimo works with compounds, add 3 times
  90260. bodyConfig.size.push(size);
  90261. bodyConfig.size.push(size);
  90262. bodyConfig.size.push(size);
  90263. break;
  90264. case BABYLON.PhysicsImpostor.CylinderImpostor:
  90265. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  90266. var sizeY = checkWithEpsilon_1(extendSize.y);
  90267. bodyConfig.type.push('cylinder');
  90268. bodyConfig.size.push(sizeX);
  90269. bodyConfig.size.push(sizeY);
  90270. //due to the way oimo works with compounds, add one more value.
  90271. bodyConfig.size.push(sizeY);
  90272. break;
  90273. case BABYLON.PhysicsImpostor.PlaneImpostor:
  90274. case BABYLON.PhysicsImpostor.BoxImpostor:
  90275. default:
  90276. var sizeX = checkWithEpsilon_1(extendSize.x);
  90277. var sizeY = checkWithEpsilon_1(extendSize.y);
  90278. var sizeZ = checkWithEpsilon_1(extendSize.z);
  90279. bodyConfig.type.push('box');
  90280. //if (i === impostor) {
  90281. bodyConfig.size.push(sizeX);
  90282. bodyConfig.size.push(sizeY);
  90283. bodyConfig.size.push(sizeZ);
  90284. //} else {
  90285. // bodyConfig.size.push(0,0,0);
  90286. //}
  90287. break;
  90288. }
  90289. //actually not needed, but hey...
  90290. i.object.rotationQuaternion = oldQuaternion;
  90291. });
  90292. impostor.physicsBody = this.world.add(bodyConfig);
  90293. // set the quaternion, ignoring the previously defined (euler) rotation
  90294. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  90295. // update with delta 0, so the body will reveive the new rotation.
  90296. impostor.physicsBody.updatePosition(0);
  90297. }
  90298. else {
  90299. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  90300. }
  90301. impostor.setDeltaPosition(this._tmpPositionVector);
  90302. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  90303. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  90304. };
  90305. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  90306. //impostor.physicsBody.dispose();
  90307. //Same as : (older oimo versions)
  90308. this.world.removeRigidBody(impostor.physicsBody);
  90309. };
  90310. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  90311. var mainBody = impostorJoint.mainImpostor.physicsBody;
  90312. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  90313. if (!mainBody || !connectedBody) {
  90314. return;
  90315. }
  90316. var jointData = impostorJoint.joint.jointData;
  90317. var options = jointData.nativeParams || {};
  90318. var type;
  90319. var nativeJointData = {
  90320. body1: mainBody,
  90321. body2: connectedBody,
  90322. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  90323. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  90324. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  90325. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  90326. min: options.min,
  90327. max: options.max,
  90328. collision: options.collision || jointData.collision,
  90329. spring: options.spring,
  90330. //supporting older version of Oimo
  90331. world: this.world
  90332. };
  90333. switch (impostorJoint.joint.type) {
  90334. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  90335. type = "jointBall";
  90336. break;
  90337. case BABYLON.PhysicsJoint.SpringJoint:
  90338. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  90339. var springData = jointData;
  90340. nativeJointData.min = springData.length || nativeJointData.min;
  90341. //Max should also be set, just make sure it is at least min
  90342. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  90343. case BABYLON.PhysicsJoint.DistanceJoint:
  90344. type = "jointDistance";
  90345. nativeJointData.max = jointData.maxDistance;
  90346. break;
  90347. case BABYLON.PhysicsJoint.PrismaticJoint:
  90348. type = "jointPrisme";
  90349. break;
  90350. case BABYLON.PhysicsJoint.SliderJoint:
  90351. type = "jointSlide";
  90352. break;
  90353. case BABYLON.PhysicsJoint.WheelJoint:
  90354. type = "jointWheel";
  90355. break;
  90356. case BABYLON.PhysicsJoint.HingeJoint:
  90357. default:
  90358. type = "jointHinge";
  90359. break;
  90360. }
  90361. nativeJointData.type = type;
  90362. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  90363. };
  90364. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  90365. //Bug in Oimo prevents us from disposing a joint in the playground
  90366. //joint.joint.physicsJoint.dispose();
  90367. //So we will bruteforce it!
  90368. try {
  90369. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  90370. }
  90371. catch (e) {
  90372. BABYLON.Tools.Warn(e);
  90373. }
  90374. };
  90375. OimoJSPlugin.prototype.isSupported = function () {
  90376. return this.BJSOIMO !== undefined;
  90377. };
  90378. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  90379. if (!impostor.physicsBody.sleeping) {
  90380. //TODO check that
  90381. /*if (impostor.physicsBody.shapes.next) {
  90382. var parentShape = this._getLastShape(impostor.physicsBody);
  90383. impostor.object.position.copyFrom(parentShape.position);
  90384. console.log(parentShape.position);
  90385. } else {*/
  90386. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  90387. //}
  90388. if (impostor.object.rotationQuaternion) {
  90389. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  90390. }
  90391. }
  90392. };
  90393. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  90394. var body = impostor.physicsBody;
  90395. body.position.copy(newPosition);
  90396. body.orientation.copy(newRotation);
  90397. body.syncShapes();
  90398. body.awake();
  90399. };
  90400. /*private _getLastShape(body: any): any {
  90401. var lastShape = body.shapes;
  90402. while (lastShape.next) {
  90403. lastShape = lastShape.next;
  90404. }
  90405. return lastShape;
  90406. }*/
  90407. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  90408. impostor.physicsBody.linearVelocity.copy(velocity);
  90409. };
  90410. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  90411. impostor.physicsBody.angularVelocity.copy(velocity);
  90412. };
  90413. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  90414. var v = impostor.physicsBody.linearVelocity;
  90415. if (!v) {
  90416. return null;
  90417. }
  90418. return new BABYLON.Vector3(v.x, v.y, v.z);
  90419. };
  90420. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  90421. var v = impostor.physicsBody.angularVelocity;
  90422. if (!v) {
  90423. return null;
  90424. }
  90425. return new BABYLON.Vector3(v.x, v.y, v.z);
  90426. };
  90427. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  90428. var staticBody = mass === 0;
  90429. //this will actually set the body's density and not its mass.
  90430. //But this is how oimo treats the mass variable.
  90431. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  90432. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  90433. };
  90434. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  90435. return impostor.physicsBody.shapes.density;
  90436. };
  90437. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  90438. return impostor.physicsBody.shapes.friction;
  90439. };
  90440. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  90441. impostor.physicsBody.shapes.friction = friction;
  90442. };
  90443. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  90444. return impostor.physicsBody.shapes.restitution;
  90445. };
  90446. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  90447. impostor.physicsBody.shapes.restitution = restitution;
  90448. };
  90449. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  90450. impostor.physicsBody.sleep();
  90451. };
  90452. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  90453. impostor.physicsBody.awake();
  90454. };
  90455. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  90456. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  90457. if (minDistance !== void 0) {
  90458. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  90459. }
  90460. };
  90461. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  90462. //TODO separate rotational and transational motors.
  90463. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  90464. if (motor) {
  90465. motor.setMotor(speed, maxForce);
  90466. }
  90467. };
  90468. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  90469. //TODO separate rotational and transational motors.
  90470. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  90471. if (motor) {
  90472. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  90473. }
  90474. };
  90475. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  90476. var body = impostor.physicsBody;
  90477. mesh.position.x = body.position.x;
  90478. mesh.position.y = body.position.y;
  90479. mesh.position.z = body.position.z;
  90480. if (mesh.rotationQuaternion) {
  90481. mesh.rotationQuaternion.x = body.orientation.x;
  90482. mesh.rotationQuaternion.y = body.orientation.y;
  90483. mesh.rotationQuaternion.z = body.orientation.z;
  90484. mesh.rotationQuaternion.w = body.orientation.s;
  90485. }
  90486. };
  90487. OimoJSPlugin.prototype.getRadius = function (impostor) {
  90488. return impostor.physicsBody.shapes.radius;
  90489. };
  90490. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  90491. var shape = impostor.physicsBody.shapes;
  90492. result.x = shape.halfWidth * 2;
  90493. result.y = shape.halfHeight * 2;
  90494. result.z = shape.halfDepth * 2;
  90495. };
  90496. OimoJSPlugin.prototype.dispose = function () {
  90497. this.world.clear();
  90498. };
  90499. return OimoJSPlugin;
  90500. }());
  90501. BABYLON.OimoJSPlugin = OimoJSPlugin;
  90502. })(BABYLON || (BABYLON = {}));
  90503. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  90504. var BABYLON;
  90505. (function (BABYLON) {
  90506. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  90507. // All values and structures referenced from:
  90508. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  90509. var DDS_MAGIC = 0x20534444;
  90510. var
  90511. //DDSD_CAPS = 0x1,
  90512. //DDSD_HEIGHT = 0x2,
  90513. //DDSD_WIDTH = 0x4,
  90514. //DDSD_PITCH = 0x8,
  90515. //DDSD_PIXELFORMAT = 0x1000,
  90516. DDSD_MIPMAPCOUNT = 0x20000;
  90517. //DDSD_LINEARSIZE = 0x80000,
  90518. //DDSD_DEPTH = 0x800000;
  90519. // var DDSCAPS_COMPLEX = 0x8,
  90520. // DDSCAPS_MIPMAP = 0x400000,
  90521. // DDSCAPS_TEXTURE = 0x1000;
  90522. var DDSCAPS2_CUBEMAP = 0x200;
  90523. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  90524. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  90525. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  90526. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  90527. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  90528. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  90529. // DDSCAPS2_VOLUME = 0x200000;
  90530. var
  90531. //DDPF_ALPHAPIXELS = 0x1,
  90532. //DDPF_ALPHA = 0x2,
  90533. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  90534. //DDPF_YUV = 0x200,
  90535. DDPF_LUMINANCE = 0x20000;
  90536. function FourCCToInt32(value) {
  90537. return value.charCodeAt(0) +
  90538. (value.charCodeAt(1) << 8) +
  90539. (value.charCodeAt(2) << 16) +
  90540. (value.charCodeAt(3) << 24);
  90541. }
  90542. function Int32ToFourCC(value) {
  90543. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  90544. }
  90545. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  90546. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  90547. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  90548. var FOURCC_DX10 = FourCCToInt32("DX10");
  90549. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  90550. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  90551. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  90552. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  90553. var headerLengthInt = 31; // The header length in 32 bit ints
  90554. // Offsets into the header array
  90555. var off_magic = 0;
  90556. var off_size = 1;
  90557. var off_flags = 2;
  90558. var off_height = 3;
  90559. var off_width = 4;
  90560. var off_mipmapCount = 7;
  90561. var off_pfFlags = 20;
  90562. var off_pfFourCC = 21;
  90563. var off_RGBbpp = 22;
  90564. var off_RMask = 23;
  90565. var off_GMask = 24;
  90566. var off_BMask = 25;
  90567. var off_AMask = 26;
  90568. // var off_caps1 = 27;
  90569. var off_caps2 = 28;
  90570. // var off_caps3 = 29;
  90571. // var off_caps4 = 30;
  90572. var off_dxgiFormat = 32;
  90573. ;
  90574. var DDSTools = /** @class */ (function () {
  90575. function DDSTools() {
  90576. }
  90577. DDSTools.GetDDSInfo = function (arrayBuffer) {
  90578. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  90579. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  90580. var mipmapCount = 1;
  90581. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  90582. mipmapCount = Math.max(1, header[off_mipmapCount]);
  90583. }
  90584. var fourCC = header[off_pfFourCC];
  90585. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  90586. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90587. switch (fourCC) {
  90588. case FOURCC_D3DFMT_R16G16B16A16F:
  90589. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90590. break;
  90591. case FOURCC_D3DFMT_R32G32B32A32F:
  90592. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90593. break;
  90594. case FOURCC_DX10:
  90595. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  90596. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90597. break;
  90598. }
  90599. }
  90600. return {
  90601. width: header[off_width],
  90602. height: header[off_height],
  90603. mipmapCount: mipmapCount,
  90604. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  90605. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  90606. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  90607. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  90608. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  90609. dxgiFormat: dxgiFormat,
  90610. textureType: textureType
  90611. };
  90612. };
  90613. DDSTools._ToHalfFloat = function (value) {
  90614. if (!DDSTools._FloatView) {
  90615. DDSTools._FloatView = new Float32Array(1);
  90616. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  90617. }
  90618. DDSTools._FloatView[0] = value;
  90619. var x = DDSTools._Int32View[0];
  90620. var bits = (x >> 16) & 0x8000; /* Get the sign */
  90621. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  90622. var e = (x >> 23) & 0xff; /* Using int is faster here */
  90623. /* If zero, or denormal, or exponent underflows too much for a denormal
  90624. * half, return signed zero. */
  90625. if (e < 103) {
  90626. return bits;
  90627. }
  90628. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  90629. if (e > 142) {
  90630. bits |= 0x7c00;
  90631. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  90632. * not Inf, so make sure we set one mantissa bit too. */
  90633. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  90634. return bits;
  90635. }
  90636. /* If exponent underflows but not too much, return a denormal */
  90637. if (e < 113) {
  90638. m |= 0x0800;
  90639. /* Extra rounding may overflow and set mantissa to 0 and exponent
  90640. * to 1, which is OK. */
  90641. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  90642. return bits;
  90643. }
  90644. bits |= ((e - 112) << 10) | (m >> 1);
  90645. bits += m & 1;
  90646. return bits;
  90647. };
  90648. DDSTools._FromHalfFloat = function (value) {
  90649. var s = (value & 0x8000) >> 15;
  90650. var e = (value & 0x7C00) >> 10;
  90651. var f = value & 0x03FF;
  90652. if (e === 0) {
  90653. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  90654. }
  90655. else if (e == 0x1F) {
  90656. return f ? NaN : ((s ? -1 : 1) * Infinity);
  90657. }
  90658. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  90659. };
  90660. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90661. var destArray = new Float32Array(dataLength);
  90662. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  90663. var index = 0;
  90664. for (var y = 0; y < height; y++) {
  90665. for (var x = 0; x < width; x++) {
  90666. var srcPos = (x + y * width) * 4;
  90667. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  90668. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  90669. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  90670. if (DDSTools.StoreLODInAlphaChannel) {
  90671. destArray[index + 3] = lod;
  90672. }
  90673. else {
  90674. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  90675. }
  90676. index += 4;
  90677. }
  90678. }
  90679. return destArray;
  90680. };
  90681. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90682. if (DDSTools.StoreLODInAlphaChannel) {
  90683. var destArray = new Uint16Array(dataLength);
  90684. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  90685. var index = 0;
  90686. for (var y = 0; y < height; y++) {
  90687. for (var x = 0; x < width; x++) {
  90688. var srcPos = (x + y * width) * 4;
  90689. destArray[index] = srcData[srcPos];
  90690. destArray[index + 1] = srcData[srcPos + 1];
  90691. destArray[index + 2] = srcData[srcPos + 2];
  90692. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  90693. index += 4;
  90694. }
  90695. }
  90696. return destArray;
  90697. }
  90698. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  90699. };
  90700. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90701. if (DDSTools.StoreLODInAlphaChannel) {
  90702. var destArray = new Float32Array(dataLength);
  90703. var srcData = new Float32Array(arrayBuffer, dataOffset);
  90704. var index = 0;
  90705. for (var y = 0; y < height; y++) {
  90706. for (var x = 0; x < width; x++) {
  90707. var srcPos = (x + y * width) * 4;
  90708. destArray[index] = srcData[srcPos];
  90709. destArray[index + 1] = srcData[srcPos + 1];
  90710. destArray[index + 2] = srcData[srcPos + 2];
  90711. destArray[index + 3] = lod;
  90712. index += 4;
  90713. }
  90714. }
  90715. return destArray;
  90716. }
  90717. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  90718. };
  90719. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90720. var destArray = new Uint8Array(dataLength);
  90721. var srcData = new Float32Array(arrayBuffer, dataOffset);
  90722. var index = 0;
  90723. for (var y = 0; y < height; y++) {
  90724. for (var x = 0; x < width; x++) {
  90725. var srcPos = (x + y * width) * 4;
  90726. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  90727. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  90728. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  90729. if (DDSTools.StoreLODInAlphaChannel) {
  90730. destArray[index + 3] = lod;
  90731. }
  90732. else {
  90733. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  90734. }
  90735. index += 4;
  90736. }
  90737. }
  90738. return destArray;
  90739. };
  90740. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90741. var destArray = new Uint8Array(dataLength);
  90742. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  90743. var index = 0;
  90744. for (var y = 0; y < height; y++) {
  90745. for (var x = 0; x < width; x++) {
  90746. var srcPos = (x + y * width) * 4;
  90747. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  90748. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  90749. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  90750. if (DDSTools.StoreLODInAlphaChannel) {
  90751. destArray[index + 3] = lod;
  90752. }
  90753. else {
  90754. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  90755. }
  90756. index += 4;
  90757. }
  90758. }
  90759. return destArray;
  90760. };
  90761. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  90762. var byteArray = new Uint8Array(dataLength);
  90763. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90764. var index = 0;
  90765. for (var y = 0; y < height; y++) {
  90766. for (var x = 0; x < width; x++) {
  90767. var srcPos = (x + y * width) * 4;
  90768. byteArray[index] = srcData[srcPos + rOffset];
  90769. byteArray[index + 1] = srcData[srcPos + gOffset];
  90770. byteArray[index + 2] = srcData[srcPos + bOffset];
  90771. byteArray[index + 3] = srcData[srcPos + aOffset];
  90772. index += 4;
  90773. }
  90774. }
  90775. return byteArray;
  90776. };
  90777. DDSTools._ExtractLongWordOrder = function (value) {
  90778. if (value === 0 || value === 255 || value === -16777216) {
  90779. return 0;
  90780. }
  90781. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  90782. };
  90783. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  90784. var byteArray = new Uint8Array(dataLength);
  90785. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90786. var index = 0;
  90787. for (var y = 0; y < height; y++) {
  90788. for (var x = 0; x < width; x++) {
  90789. var srcPos = (x + y * width) * 3;
  90790. byteArray[index] = srcData[srcPos + rOffset];
  90791. byteArray[index + 1] = srcData[srcPos + gOffset];
  90792. byteArray[index + 2] = srcData[srcPos + bOffset];
  90793. index += 3;
  90794. }
  90795. }
  90796. return byteArray;
  90797. };
  90798. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  90799. var byteArray = new Uint8Array(dataLength);
  90800. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90801. var index = 0;
  90802. for (var y = 0; y < height; y++) {
  90803. for (var x = 0; x < width; x++) {
  90804. var srcPos = (x + y * width);
  90805. byteArray[index] = srcData[srcPos];
  90806. index++;
  90807. }
  90808. }
  90809. return byteArray;
  90810. };
  90811. /**
  90812. * Uploads DDS Levels to a Babylon Texture
  90813. * @hidden
  90814. */
  90815. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  90816. if (lodIndex === void 0) { lodIndex = -1; }
  90817. var sphericalPolynomialFaces = null;
  90818. if (info.sphericalPolynomial) {
  90819. sphericalPolynomialFaces = new Array();
  90820. }
  90821. var ext = engine.getCaps().s3tc;
  90822. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  90823. var fourCC, width, height, dataLength = 0, dataOffset;
  90824. var byteArray, mipmapCount, mip;
  90825. var internalCompressedFormat = 0;
  90826. var blockBytes = 1;
  90827. if (header[off_magic] !== DDS_MAGIC) {
  90828. BABYLON.Tools.Error("Invalid magic number in DDS header");
  90829. return;
  90830. }
  90831. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  90832. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  90833. return;
  90834. }
  90835. if (info.isCompressed && !ext) {
  90836. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  90837. return;
  90838. }
  90839. var bpp = header[off_RGBbpp];
  90840. dataOffset = header[off_size] + 4;
  90841. var computeFormats = false;
  90842. if (info.isFourCC) {
  90843. fourCC = header[off_pfFourCC];
  90844. switch (fourCC) {
  90845. case FOURCC_DXT1:
  90846. blockBytes = 8;
  90847. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  90848. break;
  90849. case FOURCC_DXT3:
  90850. blockBytes = 16;
  90851. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  90852. break;
  90853. case FOURCC_DXT5:
  90854. blockBytes = 16;
  90855. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  90856. break;
  90857. case FOURCC_D3DFMT_R16G16B16A16F:
  90858. computeFormats = true;
  90859. break;
  90860. case FOURCC_D3DFMT_R32G32B32A32F:
  90861. computeFormats = true;
  90862. break;
  90863. case FOURCC_DX10:
  90864. // There is an additionnal header so dataOffset need to be changed
  90865. dataOffset += 5 * 4; // 5 uints
  90866. var supported = false;
  90867. switch (info.dxgiFormat) {
  90868. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  90869. computeFormats = true;
  90870. supported = true;
  90871. break;
  90872. case DXGI_FORMAT_B8G8R8X8_UNORM:
  90873. info.isRGB = true;
  90874. info.isFourCC = false;
  90875. bpp = 32;
  90876. supported = true;
  90877. break;
  90878. }
  90879. if (supported) {
  90880. break;
  90881. }
  90882. default:
  90883. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  90884. return;
  90885. }
  90886. }
  90887. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  90888. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  90889. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  90890. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  90891. if (computeFormats) {
  90892. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  90893. }
  90894. mipmapCount = 1;
  90895. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  90896. mipmapCount = Math.max(1, header[off_mipmapCount]);
  90897. }
  90898. for (var face = 0; face < faces; face++) {
  90899. width = header[off_width];
  90900. height = header[off_height];
  90901. for (mip = 0; mip < mipmapCount; ++mip) {
  90902. if (lodIndex === -1 || lodIndex === mip) {
  90903. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  90904. var i = (lodIndex === -1) ? mip : 0;
  90905. if (!info.isCompressed && info.isFourCC) {
  90906. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90907. dataLength = width * height * 4;
  90908. var floatArray = null;
  90909. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  90910. if (bpp === 128) {
  90911. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90912. if (sphericalPolynomialFaces && i == 0) {
  90913. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90914. }
  90915. }
  90916. else if (bpp === 64) {
  90917. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90918. if (sphericalPolynomialFaces && i == 0) {
  90919. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90920. }
  90921. }
  90922. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90923. }
  90924. else {
  90925. if (bpp === 128) {
  90926. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90927. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90928. if (sphericalPolynomialFaces && i == 0) {
  90929. sphericalPolynomialFaces.push(floatArray);
  90930. }
  90931. }
  90932. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  90933. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90934. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90935. if (sphericalPolynomialFaces && i == 0) {
  90936. sphericalPolynomialFaces.push(floatArray);
  90937. }
  90938. }
  90939. else { // 64
  90940. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90941. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90942. if (sphericalPolynomialFaces && i == 0) {
  90943. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90944. }
  90945. }
  90946. }
  90947. if (floatArray) {
  90948. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  90949. }
  90950. }
  90951. else if (info.isRGB) {
  90952. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90953. if (bpp === 24) {
  90954. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  90955. dataLength = width * height * 3;
  90956. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  90957. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  90958. }
  90959. else { // 32
  90960. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90961. dataLength = width * height * 4;
  90962. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  90963. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  90964. }
  90965. }
  90966. else if (info.isLuminance) {
  90967. var unpackAlignment = engine._getUnpackAlignement();
  90968. var unpaddedRowSize = width;
  90969. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  90970. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  90971. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  90972. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  90973. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90974. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  90975. }
  90976. else {
  90977. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  90978. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  90979. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90980. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  90981. }
  90982. }
  90983. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  90984. width *= 0.5;
  90985. height *= 0.5;
  90986. width = Math.max(1.0, width);
  90987. height = Math.max(1.0, height);
  90988. }
  90989. if (currentFace !== undefined) {
  90990. // Loading a single face
  90991. break;
  90992. }
  90993. }
  90994. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  90995. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  90996. size: header[off_width],
  90997. right: sphericalPolynomialFaces[0],
  90998. left: sphericalPolynomialFaces[1],
  90999. up: sphericalPolynomialFaces[2],
  91000. down: sphericalPolynomialFaces[3],
  91001. front: sphericalPolynomialFaces[4],
  91002. back: sphericalPolynomialFaces[5],
  91003. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  91004. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  91005. gammaSpace: false,
  91006. });
  91007. }
  91008. else {
  91009. info.sphericalPolynomial = undefined;
  91010. }
  91011. };
  91012. DDSTools.StoreLODInAlphaChannel = false;
  91013. return DDSTools;
  91014. }());
  91015. BABYLON.DDSTools = DDSTools;
  91016. })(BABYLON || (BABYLON = {}));
  91017. //# sourceMappingURL=babylon.dds.js.map
  91018. var BABYLON;
  91019. (function (BABYLON) {
  91020. /**
  91021. * Implementation of the DDS Texture Loader.
  91022. */
  91023. var DDSTextureLoader = /** @class */ (function () {
  91024. function DDSTextureLoader() {
  91025. /**
  91026. * Defines wether the loader supports cascade loading the different faces.
  91027. */
  91028. this.supportCascades = true;
  91029. }
  91030. /**
  91031. * This returns if the loader support the current file information.
  91032. * @param extension defines the file extension of the file being loaded
  91033. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91034. * @param fallback defines the fallback internal texture if any
  91035. * @param isBase64 defines whether the texture is encoded as a base64
  91036. * @param isBuffer defines whether the texture data are stored as a buffer
  91037. * @returns true if the loader can load the specified file
  91038. */
  91039. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91040. return extension.indexOf(".dds") === 0;
  91041. };
  91042. /**
  91043. * Transform the url before loading if required.
  91044. * @param rootUrl the url of the texture
  91045. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91046. * @returns the transformed texture
  91047. */
  91048. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91049. return rootUrl;
  91050. };
  91051. /**
  91052. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91053. * @param rootUrl the url of the texture
  91054. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91055. * @returns the fallback texture
  91056. */
  91057. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91058. return null;
  91059. };
  91060. /**
  91061. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91062. * @param data contains the texture data
  91063. * @param texture defines the BabylonJS internal texture
  91064. * @param createPolynomials will be true if polynomials have been requested
  91065. * @param onLoad defines the callback to trigger once the texture is ready
  91066. * @param onError defines the callback to trigger in case of error
  91067. */
  91068. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  91069. var engine = texture.getEngine();
  91070. var info;
  91071. var loadMipmap = false;
  91072. if (Array.isArray(imgs)) {
  91073. for (var index = 0; index < imgs.length; index++) {
  91074. var data_1 = imgs[index];
  91075. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  91076. texture.width = info.width;
  91077. texture.height = info.height;
  91078. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91079. engine._unpackFlipY(info.isCompressed);
  91080. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  91081. if (!info.isFourCC && info.mipmapCount === 1) {
  91082. engine.generateMipMapsForCubemap(texture);
  91083. }
  91084. }
  91085. }
  91086. else {
  91087. var data = imgs;
  91088. info = BABYLON.DDSTools.GetDDSInfo(data);
  91089. texture.width = info.width;
  91090. texture.height = info.height;
  91091. if (createPolynomials) {
  91092. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  91093. }
  91094. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91095. engine._unpackFlipY(info.isCompressed);
  91096. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  91097. if (!info.isFourCC && info.mipmapCount === 1) {
  91098. engine.generateMipMapsForCubemap(texture);
  91099. }
  91100. }
  91101. engine._setCubeMapTextureParams(loadMipmap);
  91102. texture.isReady = true;
  91103. if (onLoad) {
  91104. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  91105. }
  91106. };
  91107. /**
  91108. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91109. * @param data contains the texture data
  91110. * @param texture defines the BabylonJS internal texture
  91111. * @param callback defines the method to call once ready to upload
  91112. */
  91113. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  91114. var info = BABYLON.DDSTools.GetDDSInfo(data);
  91115. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  91116. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  91117. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  91118. });
  91119. };
  91120. return DDSTextureLoader;
  91121. }());
  91122. // Register the loader.
  91123. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  91124. })(BABYLON || (BABYLON = {}));
  91125. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  91126. var BABYLON;
  91127. (function (BABYLON) {
  91128. /*
  91129. * Based on jsTGALoader - Javascript loader for TGA file
  91130. * By Vincent Thibault
  91131. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  91132. */
  91133. var TGATools = /** @class */ (function () {
  91134. function TGATools() {
  91135. }
  91136. TGATools.GetTGAHeader = function (data) {
  91137. var offset = 0;
  91138. var header = {
  91139. id_length: data[offset++],
  91140. colormap_type: data[offset++],
  91141. image_type: data[offset++],
  91142. colormap_index: data[offset++] | data[offset++] << 8,
  91143. colormap_length: data[offset++] | data[offset++] << 8,
  91144. colormap_size: data[offset++],
  91145. origin: [
  91146. data[offset++] | data[offset++] << 8,
  91147. data[offset++] | data[offset++] << 8
  91148. ],
  91149. width: data[offset++] | data[offset++] << 8,
  91150. height: data[offset++] | data[offset++] << 8,
  91151. pixel_size: data[offset++],
  91152. flags: data[offset++]
  91153. };
  91154. return header;
  91155. };
  91156. /**
  91157. * Uploads TGA content to a Babylon Texture
  91158. * @hidden
  91159. */
  91160. TGATools.UploadContent = function (texture, data) {
  91161. // Not enough data to contain header ?
  91162. if (data.length < 19) {
  91163. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  91164. return;
  91165. }
  91166. // Read Header
  91167. var offset = 18;
  91168. var header = TGATools.GetTGAHeader(data);
  91169. // Assume it's a valid Targa file.
  91170. if (header.id_length + offset > data.length) {
  91171. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  91172. return;
  91173. }
  91174. // Skip not needed data
  91175. offset += header.id_length;
  91176. var use_rle = false;
  91177. var use_pal = false;
  91178. var use_grey = false;
  91179. // Get some informations.
  91180. switch (header.image_type) {
  91181. case TGATools._TYPE_RLE_INDEXED:
  91182. use_rle = true;
  91183. case TGATools._TYPE_INDEXED:
  91184. use_pal = true;
  91185. break;
  91186. case TGATools._TYPE_RLE_RGB:
  91187. use_rle = true;
  91188. case TGATools._TYPE_RGB:
  91189. // use_rgb = true;
  91190. break;
  91191. case TGATools._TYPE_RLE_GREY:
  91192. use_rle = true;
  91193. case TGATools._TYPE_GREY:
  91194. use_grey = true;
  91195. break;
  91196. }
  91197. var pixel_data;
  91198. // var numAlphaBits = header.flags & 0xf;
  91199. var pixel_size = header.pixel_size >> 3;
  91200. var pixel_total = header.width * header.height * pixel_size;
  91201. // Read palettes
  91202. var palettes;
  91203. if (use_pal) {
  91204. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  91205. }
  91206. // Read LRE
  91207. if (use_rle) {
  91208. pixel_data = new Uint8Array(pixel_total);
  91209. var c, count, i;
  91210. var localOffset = 0;
  91211. var pixels = new Uint8Array(pixel_size);
  91212. while (offset < pixel_total && localOffset < pixel_total) {
  91213. c = data[offset++];
  91214. count = (c & 0x7f) + 1;
  91215. // RLE pixels
  91216. if (c & 0x80) {
  91217. // Bind pixel tmp array
  91218. for (i = 0; i < pixel_size; ++i) {
  91219. pixels[i] = data[offset++];
  91220. }
  91221. // Copy pixel array
  91222. for (i = 0; i < count; ++i) {
  91223. pixel_data.set(pixels, localOffset + i * pixel_size);
  91224. }
  91225. localOffset += pixel_size * count;
  91226. }
  91227. // Raw pixels
  91228. else {
  91229. count *= pixel_size;
  91230. for (i = 0; i < count; ++i) {
  91231. pixel_data[localOffset + i] = data[offset++];
  91232. }
  91233. localOffset += count;
  91234. }
  91235. }
  91236. }
  91237. // RAW Pixels
  91238. else {
  91239. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  91240. }
  91241. // Load to texture
  91242. var x_start, y_start, x_step, y_step, y_end, x_end;
  91243. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  91244. default:
  91245. case TGATools._ORIGIN_UL:
  91246. x_start = 0;
  91247. x_step = 1;
  91248. x_end = header.width;
  91249. y_start = 0;
  91250. y_step = 1;
  91251. y_end = header.height;
  91252. break;
  91253. case TGATools._ORIGIN_BL:
  91254. x_start = 0;
  91255. x_step = 1;
  91256. x_end = header.width;
  91257. y_start = header.height - 1;
  91258. y_step = -1;
  91259. y_end = -1;
  91260. break;
  91261. case TGATools._ORIGIN_UR:
  91262. x_start = header.width - 1;
  91263. x_step = -1;
  91264. x_end = -1;
  91265. y_start = 0;
  91266. y_step = 1;
  91267. y_end = header.height;
  91268. break;
  91269. case TGATools._ORIGIN_BR:
  91270. x_start = header.width - 1;
  91271. x_step = -1;
  91272. x_end = -1;
  91273. y_start = header.height - 1;
  91274. y_step = -1;
  91275. y_end = -1;
  91276. break;
  91277. }
  91278. // Load the specify method
  91279. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  91280. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  91281. var engine = texture.getEngine();
  91282. engine._uploadDataToTextureDirectly(texture, imageData);
  91283. };
  91284. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91285. var image = pixel_data, colormap = palettes;
  91286. var width = header.width, height = header.height;
  91287. var color, i = 0, x, y;
  91288. var imageData = new Uint8Array(width * height * 4);
  91289. for (y = y_start; y !== y_end; y += y_step) {
  91290. for (x = x_start; x !== x_end; x += x_step, i++) {
  91291. color = image[i];
  91292. imageData[(x + width * y) * 4 + 3] = 255;
  91293. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  91294. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  91295. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  91296. }
  91297. }
  91298. return imageData;
  91299. };
  91300. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91301. var image = pixel_data;
  91302. var width = header.width, height = header.height;
  91303. var color, i = 0, x, y;
  91304. var imageData = new Uint8Array(width * height * 4);
  91305. for (y = y_start; y !== y_end; y += y_step) {
  91306. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  91307. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  91308. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  91309. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  91310. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  91311. imageData[(x + width * y) * 4 + 0] = r;
  91312. imageData[(x + width * y) * 4 + 1] = g;
  91313. imageData[(x + width * y) * 4 + 2] = b;
  91314. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  91315. }
  91316. }
  91317. return imageData;
  91318. };
  91319. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91320. var image = pixel_data;
  91321. var width = header.width, height = header.height;
  91322. var i = 0, x, y;
  91323. var imageData = new Uint8Array(width * height * 4);
  91324. for (y = y_start; y !== y_end; y += y_step) {
  91325. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  91326. imageData[(x + width * y) * 4 + 3] = 255;
  91327. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91328. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  91329. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  91330. }
  91331. }
  91332. return imageData;
  91333. };
  91334. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91335. var image = pixel_data;
  91336. var width = header.width, height = header.height;
  91337. var i = 0, x, y;
  91338. var imageData = new Uint8Array(width * height * 4);
  91339. for (y = y_start; y !== y_end; y += y_step) {
  91340. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  91341. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91342. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  91343. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  91344. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  91345. }
  91346. }
  91347. return imageData;
  91348. };
  91349. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91350. var image = pixel_data;
  91351. var width = header.width, height = header.height;
  91352. var color, i = 0, x, y;
  91353. var imageData = new Uint8Array(width * height * 4);
  91354. for (y = y_start; y !== y_end; y += y_step) {
  91355. for (x = x_start; x !== x_end; x += x_step, i++) {
  91356. color = image[i];
  91357. imageData[(x + width * y) * 4 + 0] = color;
  91358. imageData[(x + width * y) * 4 + 1] = color;
  91359. imageData[(x + width * y) * 4 + 2] = color;
  91360. imageData[(x + width * y) * 4 + 3] = 255;
  91361. }
  91362. }
  91363. return imageData;
  91364. };
  91365. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91366. var image = pixel_data;
  91367. var width = header.width, height = header.height;
  91368. var i = 0, x, y;
  91369. var imageData = new Uint8Array(width * height * 4);
  91370. for (y = y_start; y !== y_end; y += y_step) {
  91371. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  91372. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  91373. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  91374. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91375. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  91376. }
  91377. }
  91378. return imageData;
  91379. };
  91380. //private static _TYPE_NO_DATA = 0;
  91381. TGATools._TYPE_INDEXED = 1;
  91382. TGATools._TYPE_RGB = 2;
  91383. TGATools._TYPE_GREY = 3;
  91384. TGATools._TYPE_RLE_INDEXED = 9;
  91385. TGATools._TYPE_RLE_RGB = 10;
  91386. TGATools._TYPE_RLE_GREY = 11;
  91387. TGATools._ORIGIN_MASK = 0x30;
  91388. TGATools._ORIGIN_SHIFT = 0x04;
  91389. TGATools._ORIGIN_BL = 0x00;
  91390. TGATools._ORIGIN_BR = 0x01;
  91391. TGATools._ORIGIN_UL = 0x02;
  91392. TGATools._ORIGIN_UR = 0x03;
  91393. return TGATools;
  91394. }());
  91395. BABYLON.TGATools = TGATools;
  91396. })(BABYLON || (BABYLON = {}));
  91397. //# sourceMappingURL=babylon.tga.js.map
  91398. var BABYLON;
  91399. (function (BABYLON) {
  91400. /**
  91401. * Implementation of the TGA Texture Loader.
  91402. */
  91403. var TGATextureLoader = /** @class */ (function () {
  91404. function TGATextureLoader() {
  91405. /**
  91406. * Defines wether the loader supports cascade loading the different faces.
  91407. */
  91408. this.supportCascades = false;
  91409. }
  91410. /**
  91411. * This returns if the loader support the current file information.
  91412. * @param extension defines the file extension of the file being loaded
  91413. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91414. * @param fallback defines the fallback internal texture if any
  91415. * @param isBase64 defines whether the texture is encoded as a base64
  91416. * @param isBuffer defines whether the texture data are stored as a buffer
  91417. * @returns true if the loader can load the specified file
  91418. */
  91419. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91420. return extension.indexOf(".tga") === 0;
  91421. };
  91422. /**
  91423. * Transform the url before loading if required.
  91424. * @param rootUrl the url of the texture
  91425. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91426. * @returns the transformed texture
  91427. */
  91428. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91429. return rootUrl;
  91430. };
  91431. /**
  91432. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91433. * @param rootUrl the url of the texture
  91434. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91435. * @returns the fallback texture
  91436. */
  91437. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91438. return null;
  91439. };
  91440. /**
  91441. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91442. * @param data contains the texture data
  91443. * @param texture defines the BabylonJS internal texture
  91444. * @param createPolynomials will be true if polynomials have been requested
  91445. * @param onLoad defines the callback to trigger once the texture is ready
  91446. * @param onError defines the callback to trigger in case of error
  91447. */
  91448. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  91449. throw ".env not supported in Cube.";
  91450. };
  91451. /**
  91452. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91453. * @param data contains the texture data
  91454. * @param texture defines the BabylonJS internal texture
  91455. * @param callback defines the method to call once ready to upload
  91456. */
  91457. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  91458. var uintData = new Uint8Array(data);
  91459. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  91460. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  91461. BABYLON.TGATools.UploadContent(texture, uintData);
  91462. });
  91463. };
  91464. return TGATextureLoader;
  91465. }());
  91466. // Register the loader.
  91467. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  91468. })(BABYLON || (BABYLON = {}));
  91469. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  91470. var BABYLON;
  91471. (function (BABYLON) {
  91472. /**
  91473. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  91474. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  91475. */
  91476. var KhronosTextureContainer = /** @class */ (function () {
  91477. /**
  91478. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  91479. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  91480. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  91481. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  91482. */
  91483. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  91484. this.arrayBuffer = arrayBuffer;
  91485. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  91486. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  91487. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  91488. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  91489. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  91490. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  91491. BABYLON.Tools.Error("texture missing KTX identifier");
  91492. return;
  91493. }
  91494. // load the reset of the header in native 32 bit int
  91495. var header = new Int32Array(this.arrayBuffer, 12, 13);
  91496. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  91497. var oppositeEndianess = header[0] === 0x01020304;
  91498. // read all the header elements in order they exist in the file, without modification (sans endainness)
  91499. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  91500. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  91501. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  91502. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  91503. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  91504. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  91505. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  91506. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  91507. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  91508. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  91509. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  91510. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  91511. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  91512. if (this.glType !== 0) {
  91513. BABYLON.Tools.Error("only compressed formats currently supported");
  91514. return;
  91515. }
  91516. else {
  91517. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  91518. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  91519. }
  91520. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  91521. BABYLON.Tools.Error("only 2D textures currently supported");
  91522. return;
  91523. }
  91524. if (this.numberOfArrayElements !== 0) {
  91525. BABYLON.Tools.Error("texture arrays not currently supported");
  91526. return;
  91527. }
  91528. if (this.numberOfFaces !== facesExpected) {
  91529. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  91530. return;
  91531. }
  91532. // we now have a completely validated file, so could use existence of loadType as success
  91533. // would need to make this more elaborate & adjust checks above to support more than one load type
  91534. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  91535. }
  91536. // not as fast hardware based, but will probably never need to use
  91537. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  91538. return ((val & 0xFF) << 24)
  91539. | ((val & 0xFF00) << 8)
  91540. | ((val >> 8) & 0xFF00)
  91541. | ((val >> 24) & 0xFF);
  91542. };
  91543. /**
  91544. * Uploads KTX content to a Babylon Texture.
  91545. * It is assumed that the texture has already been created & is currently bound
  91546. * @hidden
  91547. */
  91548. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  91549. switch (this.loadType) {
  91550. case KhronosTextureContainer.COMPRESSED_2D:
  91551. this._upload2DCompressedLevels(texture, loadMipmaps);
  91552. break;
  91553. case KhronosTextureContainer.TEX_2D:
  91554. case KhronosTextureContainer.COMPRESSED_3D:
  91555. case KhronosTextureContainer.TEX_3D:
  91556. }
  91557. };
  91558. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  91559. // initialize width & height for level 1
  91560. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  91561. var width = this.pixelWidth;
  91562. var height = this.pixelHeight;
  91563. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  91564. for (var level = 0; level < mipmapCount; level++) {
  91565. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  91566. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  91567. for (var face = 0; face < this.numberOfFaces; face++) {
  91568. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  91569. var engine = texture.getEngine();
  91570. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  91571. dataOffset += imageSize; // add size of the image for the next face/mipmap
  91572. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  91573. }
  91574. width = Math.max(1.0, width * 0.5);
  91575. height = Math.max(1.0, height * 0.5);
  91576. }
  91577. };
  91578. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  91579. // load types
  91580. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  91581. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  91582. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  91583. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  91584. return KhronosTextureContainer;
  91585. }());
  91586. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  91587. })(BABYLON || (BABYLON = {}));
  91588. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  91589. var BABYLON;
  91590. (function (BABYLON) {
  91591. /**
  91592. * Implementation of the KTX Texture Loader.
  91593. */
  91594. var KTXTextureLoader = /** @class */ (function () {
  91595. function KTXTextureLoader() {
  91596. /**
  91597. * Defines wether the loader supports cascade loading the different faces.
  91598. */
  91599. this.supportCascades = false;
  91600. }
  91601. /**
  91602. * This returns if the loader support the current file information.
  91603. * @param extension defines the file extension of the file being loaded
  91604. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91605. * @param fallback defines the fallback internal texture if any
  91606. * @param isBase64 defines whether the texture is encoded as a base64
  91607. * @param isBuffer defines whether the texture data are stored as a buffer
  91608. * @returns true if the loader can load the specified file
  91609. */
  91610. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91611. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  91612. return true;
  91613. }
  91614. return false;
  91615. };
  91616. /**
  91617. * Transform the url before loading if required.
  91618. * @param rootUrl the url of the texture
  91619. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91620. * @returns the transformed texture
  91621. */
  91622. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91623. var lastDot = rootUrl.lastIndexOf('.');
  91624. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  91625. };
  91626. /**
  91627. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91628. * @param rootUrl the url of the texture
  91629. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91630. * @returns the fallback texture
  91631. */
  91632. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91633. // remove the format appended to the rootUrl in the original createCubeTexture call.
  91634. var exp = new RegExp("" + textureFormatInUse + "$");
  91635. return rootUrl.replace(exp, "");
  91636. };
  91637. /**
  91638. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91639. * @param data contains the texture data
  91640. * @param texture defines the BabylonJS internal texture
  91641. * @param createPolynomials will be true if polynomials have been requested
  91642. * @param onLoad defines the callback to trigger once the texture is ready
  91643. * @param onError defines the callback to trigger in case of error
  91644. */
  91645. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  91646. if (Array.isArray(data)) {
  91647. return;
  91648. }
  91649. var engine = texture.getEngine();
  91650. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  91651. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  91652. engine._unpackFlipY(true);
  91653. ktx.uploadLevels(texture, texture.generateMipMaps);
  91654. texture.width = ktx.pixelWidth;
  91655. texture.height = ktx.pixelHeight;
  91656. engine._setCubeMapTextureParams(loadMipmap);
  91657. texture.isReady = true;
  91658. };
  91659. /**
  91660. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91661. * @param data contains the texture data
  91662. * @param texture defines the BabylonJS internal texture
  91663. * @param callback defines the method to call once ready to upload
  91664. */
  91665. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  91666. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  91667. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  91668. ktx.uploadLevels(texture, texture.generateMipMaps);
  91669. });
  91670. };
  91671. return KTXTextureLoader;
  91672. }());
  91673. // Register the loader.
  91674. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  91675. })(BABYLON || (BABYLON = {}));
  91676. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  91677. var BABYLON;
  91678. (function (BABYLON) {
  91679. /**
  91680. * Sets of helpers addressing the serialization and deserialization of environment texture
  91681. * stored in a BabylonJS env file.
  91682. * Those files are usually stored as .env files.
  91683. */
  91684. var EnvironmentTextureTools = /** @class */ (function () {
  91685. function EnvironmentTextureTools() {
  91686. }
  91687. /**
  91688. * Gets the environment info from an env file.
  91689. * @param data The array buffer containing the .env bytes.
  91690. * @returns the environment file info (the json header) if successfully parsed.
  91691. */
  91692. EnvironmentTextureTools.GetEnvInfo = function (data) {
  91693. var dataView = new DataView(data);
  91694. var pos = 0;
  91695. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  91696. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  91697. BABYLON.Tools.Error('Not a babylon environment map');
  91698. return null;
  91699. }
  91700. }
  91701. // Read json manifest - collect characters up to null terminator
  91702. var manifestString = '';
  91703. var charCode = 0x00;
  91704. while ((charCode = dataView.getUint8(pos++))) {
  91705. manifestString += String.fromCharCode(charCode);
  91706. }
  91707. var manifest = JSON.parse(manifestString);
  91708. if (manifest.specular) {
  91709. // Extend the header with the position of the payload.
  91710. manifest.specular.specularDataPosition = pos;
  91711. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  91712. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  91713. }
  91714. return manifest;
  91715. };
  91716. /**
  91717. * Creates an environment texture from a loaded cube texture.
  91718. * @param texture defines the cube texture to convert in env file
  91719. * @return a promise containing the environment data if succesfull.
  91720. */
  91721. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  91722. var _this = this;
  91723. var internalTexture = texture.getInternalTexture();
  91724. if (!internalTexture) {
  91725. return Promise.reject("The cube texture is invalid.");
  91726. }
  91727. if (!texture._prefiltered) {
  91728. return Promise.reject("The cube texture is invalid (not prefiltered).");
  91729. }
  91730. var engine = internalTexture.getEngine();
  91731. if (engine && engine.premultipliedAlpha) {
  91732. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  91733. }
  91734. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  91735. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  91736. }
  91737. var canvas = engine.getRenderingCanvas();
  91738. if (!canvas) {
  91739. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  91740. }
  91741. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91742. if (!engine.getCaps().textureFloatRender) {
  91743. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91744. if (!engine.getCaps().textureHalfFloatRender) {
  91745. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  91746. }
  91747. }
  91748. var cubeWidth = internalTexture.width;
  91749. var hostingScene = new BABYLON.Scene(engine);
  91750. var specularTextures = {};
  91751. var promises = [];
  91752. // Read and collect all mipmaps data from the cube.
  91753. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  91754. mipmapsCount = Math.round(mipmapsCount);
  91755. var _loop_1 = function (i) {
  91756. var faceWidth = Math.pow(2, mipmapsCount - i);
  91757. var _loop_2 = function (face) {
  91758. var data = texture.readPixels(face, i);
  91759. // Creates a temp texture with the face data.
  91760. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  91761. // And rgbdEncode them.
  91762. var promise = new Promise(function (resolve, reject) {
  91763. 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);
  91764. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  91765. rgbdPostProcess.onApply = function (effect) {
  91766. effect._bindTexture("textureSampler", tempTexture);
  91767. };
  91768. // As the process needs to happen on the main canvas, keep track of the current size
  91769. var currentW = engine.getRenderWidth();
  91770. var currentH = engine.getRenderHeight();
  91771. // Set the desired size for the texture
  91772. engine.setSize(faceWidth, faceWidth);
  91773. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  91774. // Reading datas from WebGL
  91775. BABYLON.Tools.ToBlob(canvas, function (blob) {
  91776. var fileReader = new FileReader();
  91777. fileReader.onload = function (event) {
  91778. var arrayBuffer = event.target.result;
  91779. specularTextures[i * 6 + face] = arrayBuffer;
  91780. resolve();
  91781. };
  91782. fileReader.readAsArrayBuffer(blob);
  91783. });
  91784. // Reapply the previous canvas size
  91785. engine.setSize(currentW, currentH);
  91786. });
  91787. });
  91788. promises.push(promise);
  91789. };
  91790. // All faces of the cube.
  91791. for (var face = 0; face < 6; face++) {
  91792. _loop_2(face);
  91793. }
  91794. };
  91795. for (var i = 0; i <= mipmapsCount; i++) {
  91796. _loop_1(i);
  91797. }
  91798. // Once all the textures haves been collected as RGBD stored in PNGs
  91799. return Promise.all(promises).then(function () {
  91800. // We can delete the hosting scene keeping track of all the creation objects
  91801. hostingScene.dispose();
  91802. // Creates the json header for the env texture
  91803. var info = {
  91804. version: 1,
  91805. width: cubeWidth,
  91806. irradiance: _this._CreateEnvTextureIrradiance(texture),
  91807. specular: {
  91808. mipmaps: [],
  91809. lodGenerationScale: texture.lodGenerationScale
  91810. }
  91811. };
  91812. // Sets the specular image data information
  91813. var position = 0;
  91814. for (var i = 0; i <= mipmapsCount; i++) {
  91815. for (var face = 0; face < 6; face++) {
  91816. var byteLength = specularTextures[i * 6 + face].byteLength;
  91817. info.specular.mipmaps.push({
  91818. length: byteLength,
  91819. position: position
  91820. });
  91821. position += byteLength;
  91822. }
  91823. }
  91824. // Encode the JSON as an array buffer
  91825. var infoString = JSON.stringify(info);
  91826. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  91827. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  91828. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  91829. infoView[i] = infoString.charCodeAt(i);
  91830. }
  91831. // Ends up with a null terminator for easier parsing
  91832. infoView[infoString.length] = 0x00;
  91833. // Computes the final required size and creates the storage
  91834. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  91835. var finalBuffer = new ArrayBuffer(totalSize);
  91836. var finalBufferView = new Uint8Array(finalBuffer);
  91837. var dataView = new DataView(finalBuffer);
  91838. // Copy the magic bytes identifying the file in
  91839. var pos = 0;
  91840. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  91841. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  91842. }
  91843. // Add the json info
  91844. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  91845. pos += infoBuffer.byteLength;
  91846. // Finally inserts the texture data
  91847. for (var i = 0; i <= mipmapsCount; i++) {
  91848. for (var face = 0; face < 6; face++) {
  91849. var dataBuffer = specularTextures[i * 6 + face];
  91850. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  91851. pos += dataBuffer.byteLength;
  91852. }
  91853. }
  91854. // Voila
  91855. return finalBuffer;
  91856. });
  91857. };
  91858. /**
  91859. * Creates a JSON representation of the spherical data.
  91860. * @param texture defines the texture containing the polynomials
  91861. * @return the JSON representation of the spherical info
  91862. */
  91863. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  91864. var polynmials = texture.sphericalPolynomial;
  91865. if (polynmials == null) {
  91866. return null;
  91867. }
  91868. return {
  91869. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  91870. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  91871. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  91872. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  91873. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  91874. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  91875. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  91876. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  91877. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  91878. };
  91879. };
  91880. /**
  91881. * Uploads the texture info contained in the env file to the GPU.
  91882. * @param texture defines the internal texture to upload to
  91883. * @param arrayBuffer defines the buffer cotaining the data to load
  91884. * @param info defines the texture info retrieved through the GetEnvInfo method
  91885. * @returns a promise
  91886. */
  91887. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  91888. if (info.version !== 1) {
  91889. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  91890. }
  91891. var specularInfo = info.specular;
  91892. if (!specularInfo) {
  91893. // Nothing else parsed so far
  91894. return Promise.resolve();
  91895. }
  91896. // Double checks the enclosed info
  91897. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  91898. mipmapsCount = Math.round(mipmapsCount) + 1;
  91899. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  91900. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  91901. }
  91902. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  91903. var imageData = new Array(mipmapsCount);
  91904. for (var i = 0; i < mipmapsCount; i++) {
  91905. imageData[i] = new Array(6);
  91906. for (var face = 0; face < 6; face++) {
  91907. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  91908. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  91909. }
  91910. }
  91911. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  91912. };
  91913. /**
  91914. * Uploads the levels of image data to the GPU.
  91915. * @param texture defines the internal texture to upload to
  91916. * @param imageData defines the array buffer views of image data [mipmap][face]
  91917. * @returns a promise
  91918. */
  91919. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  91920. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  91921. throw new Error("Texture size must be a power of two");
  91922. }
  91923. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  91924. // Gets everything ready.
  91925. var engine = texture.getEngine();
  91926. var expandTexture = false;
  91927. var generateNonLODTextures = false;
  91928. var rgbdPostProcess = null;
  91929. var cubeRtt = null;
  91930. var lodTextures = null;
  91931. var caps = engine.getCaps();
  91932. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91933. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91934. texture.generateMipMaps = true;
  91935. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  91936. // Add extra process if texture lod is not supported
  91937. if (!caps.textureLOD) {
  91938. expandTexture = false;
  91939. generateNonLODTextures = true;
  91940. lodTextures = {};
  91941. }
  91942. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  91943. else if (engine.webGLVersion < 2) {
  91944. expandTexture = false;
  91945. }
  91946. // If half float available we can uncompress the texture
  91947. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  91948. expandTexture = true;
  91949. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91950. }
  91951. // If full float available we can uncompress the texture
  91952. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  91953. expandTexture = true;
  91954. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91955. }
  91956. // Expand the texture if possible
  91957. if (expandTexture) {
  91958. // Simply run through the decode PP
  91959. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  91960. texture._isRGBD = false;
  91961. texture.invertY = false;
  91962. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  91963. generateDepthBuffer: false,
  91964. generateMipMaps: true,
  91965. generateStencilBuffer: false,
  91966. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  91967. type: texture.type,
  91968. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  91969. });
  91970. }
  91971. else {
  91972. texture._isRGBD = true;
  91973. texture.invertY = true;
  91974. // In case of missing support, applies the same patch than DDS files.
  91975. if (generateNonLODTextures) {
  91976. var mipSlices = 3;
  91977. var scale = texture._lodGenerationScale;
  91978. var offset = texture._lodGenerationOffset;
  91979. for (var i = 0; i < mipSlices; i++) {
  91980. //compute LOD from even spacing in smoothness (matching shader calculation)
  91981. var smoothness = i / (mipSlices - 1);
  91982. var roughness = 1 - smoothness;
  91983. var minLODIndex = offset; // roughness = 0
  91984. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  91985. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  91986. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  91987. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  91988. glTextureFromLod.isCube = true;
  91989. glTextureFromLod.invertY = true;
  91990. glTextureFromLod.generateMipMaps = false;
  91991. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  91992. // Wrap in a base texture for easy binding.
  91993. var lodTexture = new BABYLON.BaseTexture(null);
  91994. lodTexture.isCube = true;
  91995. lodTexture._texture = glTextureFromLod;
  91996. lodTextures[mipmapIndex] = lodTexture;
  91997. switch (i) {
  91998. case 0:
  91999. texture._lodTextureLow = lodTexture;
  92000. break;
  92001. case 1:
  92002. texture._lodTextureMid = lodTexture;
  92003. break;
  92004. case 2:
  92005. texture._lodTextureHigh = lodTexture;
  92006. break;
  92007. }
  92008. }
  92009. }
  92010. }
  92011. var promises = [];
  92012. var _loop_3 = function (i) {
  92013. var _loop_4 = function (face) {
  92014. // Constructs an image element from image data
  92015. var bytes = imageData[i][face];
  92016. var blob = new Blob([bytes], { type: 'image/png' });
  92017. var url = URL.createObjectURL(blob);
  92018. var image = new Image();
  92019. image.src = url;
  92020. // Enqueue promise to upload to the texture.
  92021. var promise = new Promise(function (resolve, reject) {
  92022. image.onload = function () {
  92023. if (expandTexture) {
  92024. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  92025. reject(message);
  92026. }, image);
  92027. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  92028. // Uncompress the data to a RTT
  92029. rgbdPostProcess.onApply = function (effect) {
  92030. effect._bindTexture("textureSampler", tempTexture_1);
  92031. effect.setFloat2("scale", 1, 1);
  92032. };
  92033. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  92034. // Cleanup
  92035. engine.restoreDefaultFramebuffer();
  92036. tempTexture_1.dispose();
  92037. window.URL.revokeObjectURL(url);
  92038. resolve();
  92039. });
  92040. }
  92041. else {
  92042. engine._uploadImageToTexture(texture, image, face, i);
  92043. // Upload the face to the non lod texture support
  92044. if (generateNonLODTextures) {
  92045. var lodTexture = lodTextures[i];
  92046. if (lodTexture) {
  92047. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  92048. }
  92049. }
  92050. resolve();
  92051. }
  92052. };
  92053. image.onerror = function (error) {
  92054. reject(error);
  92055. };
  92056. });
  92057. promises.push(promise);
  92058. };
  92059. // All faces
  92060. for (var face = 0; face < 6; face++) {
  92061. _loop_4(face);
  92062. }
  92063. };
  92064. // All mipmaps up to provided number of images
  92065. for (var i = 0; i < imageData.length; i++) {
  92066. _loop_3(i);
  92067. }
  92068. // Fill remaining mipmaps with black textures.
  92069. if (imageData.length < mipmapsCount) {
  92070. var data = void 0;
  92071. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  92072. var dataLength = size * size * 4;
  92073. switch (texture.type) {
  92074. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  92075. data = new Uint8Array(dataLength);
  92076. break;
  92077. }
  92078. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  92079. data = new Uint16Array(dataLength);
  92080. break;
  92081. }
  92082. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  92083. data = new Float32Array(dataLength);
  92084. break;
  92085. }
  92086. }
  92087. for (var i = imageData.length; i < mipmapsCount; i++) {
  92088. for (var face = 0; face < 6; face++) {
  92089. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  92090. }
  92091. }
  92092. }
  92093. // Once all done, finishes the cleanup and return
  92094. return Promise.all(promises).then(function () {
  92095. // Release temp RTT.
  92096. if (cubeRtt) {
  92097. engine._releaseFramebufferObjects(cubeRtt);
  92098. cubeRtt._swapAndDie(texture);
  92099. }
  92100. // Release temp Post Process.
  92101. if (rgbdPostProcess) {
  92102. rgbdPostProcess.dispose();
  92103. }
  92104. // Flag internal texture as ready in case they are in use.
  92105. if (generateNonLODTextures) {
  92106. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  92107. texture._lodTextureHigh._texture.isReady = true;
  92108. }
  92109. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  92110. texture._lodTextureMid._texture.isReady = true;
  92111. }
  92112. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  92113. texture._lodTextureLow._texture.isReady = true;
  92114. }
  92115. }
  92116. });
  92117. };
  92118. /**
  92119. * Uploads spherical polynomials information to the texture.
  92120. * @param texture defines the texture we are trying to upload the information to
  92121. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  92122. */
  92123. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  92124. if (info.version !== 1) {
  92125. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  92126. }
  92127. var irradianceInfo = info.irradiance;
  92128. if (!irradianceInfo) {
  92129. return;
  92130. }
  92131. var sp = new BABYLON.SphericalPolynomial();
  92132. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  92133. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  92134. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  92135. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  92136. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  92137. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  92138. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  92139. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  92140. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  92141. texture._sphericalPolynomial = sp;
  92142. };
  92143. /**
  92144. * Magic number identifying the env file.
  92145. */
  92146. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  92147. return EnvironmentTextureTools;
  92148. }());
  92149. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  92150. })(BABYLON || (BABYLON = {}));
  92151. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  92152. var BABYLON;
  92153. (function (BABYLON) {
  92154. /**
  92155. * Implementation of the ENV Texture Loader.
  92156. */
  92157. var ENVTextureLoader = /** @class */ (function () {
  92158. function ENVTextureLoader() {
  92159. /**
  92160. * Defines wether the loader supports cascade loading the different faces.
  92161. */
  92162. this.supportCascades = false;
  92163. }
  92164. /**
  92165. * This returns if the loader support the current file information.
  92166. * @param extension defines the file extension of the file being loaded
  92167. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92168. * @param fallback defines the fallback internal texture if any
  92169. * @param isBase64 defines whether the texture is encoded as a base64
  92170. * @param isBuffer defines whether the texture data are stored as a buffer
  92171. * @returns true if the loader can load the specified file
  92172. */
  92173. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  92174. return extension.indexOf(".env") === 0;
  92175. };
  92176. /**
  92177. * Transform the url before loading if required.
  92178. * @param rootUrl the url of the texture
  92179. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92180. * @returns the transformed texture
  92181. */
  92182. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  92183. return rootUrl;
  92184. };
  92185. /**
  92186. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  92187. * @param rootUrl the url of the texture
  92188. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92189. * @returns the fallback texture
  92190. */
  92191. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  92192. return null;
  92193. };
  92194. /**
  92195. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  92196. * @param data contains the texture data
  92197. * @param texture defines the BabylonJS internal texture
  92198. * @param createPolynomials will be true if polynomials have been requested
  92199. * @param onLoad defines the callback to trigger once the texture is ready
  92200. * @param onError defines the callback to trigger in case of error
  92201. */
  92202. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  92203. if (Array.isArray(data)) {
  92204. return;
  92205. }
  92206. data = data;
  92207. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  92208. if (info) {
  92209. texture.width = info.width;
  92210. texture.height = info.width;
  92211. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  92212. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  92213. texture.isReady = true;
  92214. if (onLoad) {
  92215. onLoad();
  92216. }
  92217. });
  92218. }
  92219. else if (onError) {
  92220. onError("Can not parse the environment file", null);
  92221. }
  92222. };
  92223. /**
  92224. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  92225. * @param data contains the texture data
  92226. * @param texture defines the BabylonJS internal texture
  92227. * @param callback defines the method to call once ready to upload
  92228. */
  92229. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  92230. throw ".env not supported in 2d.";
  92231. };
  92232. return ENVTextureLoader;
  92233. }());
  92234. // Register the loader.
  92235. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  92236. })(BABYLON || (BABYLON = {}));
  92237. //# sourceMappingURL=babylon.envTextureLoader.js.map
  92238. var BABYLON;
  92239. (function (BABYLON) {
  92240. /**
  92241. * Renders a layer on top of an existing scene
  92242. */
  92243. var UtilityLayerRenderer = /** @class */ (function () {
  92244. /**
  92245. * Instantiates a UtilityLayerRenderer
  92246. * @param originalScene the original scene that will be rendered on top of
  92247. */
  92248. function UtilityLayerRenderer(
  92249. /** the original scene that will be rendered on top of */
  92250. originalScene) {
  92251. var _this = this;
  92252. this.originalScene = originalScene;
  92253. this._pointerCaptures = {};
  92254. this._lastPointerEvents = {};
  92255. /**
  92256. * If the utility layer should automatically be rendered on top of existing scene
  92257. */
  92258. this.shouldRender = true;
  92259. /**
  92260. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  92261. */
  92262. this.onlyCheckPointerDownEvents = true;
  92263. /**
  92264. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  92265. */
  92266. this.processAllEvents = false;
  92267. /**
  92268. * Observable raised when the pointer move from the utility layer scene to the main scene
  92269. */
  92270. this.onPointerOutObservable = new BABYLON.Observable();
  92271. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  92272. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  92273. this.utilityLayerScene._allowPostProcessClearColor = false;
  92274. originalScene.getEngine().scenes.pop();
  92275. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  92276. this.utilityLayerScene.detachControl();
  92277. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  92278. if (!_this.processAllEvents) {
  92279. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  92280. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  92281. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  92282. return;
  92283. }
  92284. }
  92285. var pointerEvent = (prePointerInfo.event);
  92286. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  92287. _this._pointerCaptures[pointerEvent.pointerId] = false;
  92288. return;
  92289. }
  92290. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  92291. if (!prePointerInfo.ray && utilityScenePick) {
  92292. prePointerInfo.ray = utilityScenePick.ray;
  92293. }
  92294. // always fire the prepointer oversvable
  92295. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  92296. // allow every non pointer down event to flow to the utility layer
  92297. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  92298. if (!prePointerInfo.skipOnPointerObservable) {
  92299. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  92300. }
  92301. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  92302. _this._pointerCaptures[pointerEvent.pointerId] = false;
  92303. }
  92304. return;
  92305. }
  92306. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  92307. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  92308. if (utilityScenePick && utilityScenePick.hit) {
  92309. if (!prePointerInfo.skipOnPointerObservable) {
  92310. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  92311. }
  92312. prePointerInfo.skipOnPointerObservable = true;
  92313. }
  92314. }
  92315. else {
  92316. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  92317. var pointerEvent_1 = (prePointerInfo.event);
  92318. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  92319. if (originalScenePick && utilityScenePick) {
  92320. // No pick in utility scene
  92321. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  92322. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  92323. // We touched an utility mesh present in the main scene
  92324. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  92325. prePointerInfo.skipOnPointerObservable = true;
  92326. }
  92327. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92328. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  92329. }
  92330. }
  92331. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  92332. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  92333. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  92334. // If a previous utility layer set this, do not unset this
  92335. if (!prePointerInfo.skipOnPointerObservable) {
  92336. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  92337. }
  92338. }
  92339. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  92340. // We have a pick in both scenes but main is closer than utility
  92341. // We touched an utility mesh present in the main scene
  92342. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  92343. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  92344. prePointerInfo.skipOnPointerObservable = true;
  92345. }
  92346. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  92347. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  92348. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  92349. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  92350. }
  92351. }
  92352. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  92353. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  92354. }
  92355. }
  92356. }
  92357. });
  92358. // Render directly on top of existing scene without clearing
  92359. this.utilityLayerScene.autoClear = false;
  92360. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  92361. if (_this.shouldRender) {
  92362. _this.render();
  92363. }
  92364. });
  92365. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  92366. _this.dispose();
  92367. });
  92368. this._updateCamera();
  92369. }
  92370. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  92371. /**
  92372. * 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)
  92373. */
  92374. get: function () {
  92375. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  92376. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  92377. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  92378. UtilityLayerRenderer._DefaultUtilityLayer = null;
  92379. });
  92380. }
  92381. return UtilityLayerRenderer._DefaultUtilityLayer;
  92382. },
  92383. enumerable: true,
  92384. configurable: true
  92385. });
  92386. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  92387. /**
  92388. * 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)
  92389. */
  92390. get: function () {
  92391. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  92392. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  92393. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  92394. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  92395. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  92396. });
  92397. }
  92398. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  92399. },
  92400. enumerable: true,
  92401. configurable: true
  92402. });
  92403. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  92404. if (!prePointerInfo.skipOnPointerObservable) {
  92405. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  92406. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  92407. }
  92408. };
  92409. /**
  92410. * Renders the utility layers scene on top of the original scene
  92411. */
  92412. UtilityLayerRenderer.prototype.render = function () {
  92413. this._updateCamera();
  92414. if (this.utilityLayerScene.activeCamera) {
  92415. // Set the camera's scene to utility layers scene
  92416. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  92417. var camera = this.utilityLayerScene.activeCamera;
  92418. camera._scene = this.utilityLayerScene;
  92419. if (camera.leftCamera) {
  92420. camera.leftCamera._scene = this.utilityLayerScene;
  92421. }
  92422. if (camera.rightCamera) {
  92423. camera.rightCamera._scene = this.utilityLayerScene;
  92424. }
  92425. this.utilityLayerScene.render(false);
  92426. // Reset camera's scene back to original
  92427. camera._scene = oldScene;
  92428. if (camera.leftCamera) {
  92429. camera.leftCamera._scene = oldScene;
  92430. }
  92431. if (camera.rightCamera) {
  92432. camera.rightCamera._scene = oldScene;
  92433. }
  92434. }
  92435. };
  92436. /**
  92437. * Disposes of the renderer
  92438. */
  92439. UtilityLayerRenderer.prototype.dispose = function () {
  92440. this.onPointerOutObservable.clear();
  92441. if (this._afterRenderObserver) {
  92442. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  92443. }
  92444. if (this._sceneDisposeObserver) {
  92445. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  92446. }
  92447. if (this._originalPointerObserver) {
  92448. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  92449. }
  92450. this.utilityLayerScene.dispose();
  92451. };
  92452. UtilityLayerRenderer.prototype._updateCamera = function () {
  92453. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  92454. };
  92455. UtilityLayerRenderer._DefaultUtilityLayer = null;
  92456. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  92457. return UtilityLayerRenderer;
  92458. }());
  92459. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  92460. })(BABYLON || (BABYLON = {}));
  92461. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  92462. //# sourceMappingURL=babylon.behavior.js.map
  92463. var BABYLON;
  92464. (function (BABYLON) {
  92465. /**
  92466. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  92467. */
  92468. var PointerDragBehavior = /** @class */ (function () {
  92469. /**
  92470. * Creates a pointer drag behavior that can be attached to a mesh
  92471. * @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)
  92472. */
  92473. function PointerDragBehavior(options) {
  92474. /**
  92475. * 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)
  92476. */
  92477. this.maxDragAngle = 0;
  92478. /**
  92479. * @hidden
  92480. */
  92481. this._useAlternatePickedPointAboveMaxDragAngle = false;
  92482. /**
  92483. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  92484. */
  92485. this.currentDraggingPointerID = -1;
  92486. /**
  92487. * If the behavior is currently in a dragging state
  92488. */
  92489. this.dragging = false;
  92490. /**
  92491. * 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)
  92492. */
  92493. this.dragDeltaRatio = 0.2;
  92494. /**
  92495. * If the drag plane orientation should be updated during the dragging (Default: true)
  92496. */
  92497. this.updateDragPlane = true;
  92498. // Debug mode will display drag planes to help visualize behavior
  92499. this._debugMode = false;
  92500. this._moving = false;
  92501. /**
  92502. * Fires each time the attached mesh is dragged with the pointer
  92503. * * delta between last drag position and current drag position in world space
  92504. * * dragDistance along the drag axis
  92505. * * dragPlaneNormal normal of the current drag plane used during the drag
  92506. * * dragPlanePoint in world space where the drag intersects the drag plane
  92507. */
  92508. this.onDragObservable = new BABYLON.Observable();
  92509. /**
  92510. * Fires each time a drag begins (eg. mouse down on mesh)
  92511. */
  92512. this.onDragStartObservable = new BABYLON.Observable();
  92513. /**
  92514. * Fires each time a drag ends (eg. mouse release after drag)
  92515. */
  92516. this.onDragEndObservable = new BABYLON.Observable();
  92517. /**
  92518. * If the attached mesh should be moved when dragged
  92519. */
  92520. this.moveAttached = true;
  92521. /**
  92522. * If the drag behavior will react to drag events (Default: true)
  92523. */
  92524. this.enabled = true;
  92525. /**
  92526. * If camera controls should be detached during the drag
  92527. */
  92528. this.detachCameraControls = true;
  92529. /**
  92530. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  92531. */
  92532. this.useObjectOrienationForDragging = true;
  92533. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  92534. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  92535. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  92536. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  92537. this._attachedElement = null;
  92538. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  92539. this._lastPointerRay = {};
  92540. this._dragDelta = new BABYLON.Vector3();
  92541. // Variables to avoid instantiation in the below method
  92542. this._pointA = new BABYLON.Vector3(0, 0, 0);
  92543. this._pointB = new BABYLON.Vector3(0, 0, 0);
  92544. this._pointC = new BABYLON.Vector3(0, 0, 0);
  92545. this._lineA = new BABYLON.Vector3(0, 0, 0);
  92546. this._lineB = new BABYLON.Vector3(0, 0, 0);
  92547. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  92548. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  92549. this._options = options ? options : {};
  92550. var optionCount = 0;
  92551. if (this._options.dragAxis) {
  92552. optionCount++;
  92553. }
  92554. if (this._options.dragPlaneNormal) {
  92555. optionCount++;
  92556. }
  92557. if (optionCount > 1) {
  92558. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  92559. }
  92560. }
  92561. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  92562. /**
  92563. * The name of the behavior
  92564. */
  92565. get: function () {
  92566. return "PointerDrag";
  92567. },
  92568. enumerable: true,
  92569. configurable: true
  92570. });
  92571. /**
  92572. * Initializes the behavior
  92573. */
  92574. PointerDragBehavior.prototype.init = function () { };
  92575. /**
  92576. * Attaches the drag behavior the passed in mesh
  92577. * @param ownerNode The mesh that will be dragged around once attached
  92578. */
  92579. PointerDragBehavior.prototype.attach = function (ownerNode) {
  92580. var _this = this;
  92581. this._scene = ownerNode.getScene();
  92582. this._attachedNode = ownerNode;
  92583. // Initialize drag plane to not interfere with existing scene
  92584. if (!PointerDragBehavior._planeScene) {
  92585. if (this._debugMode) {
  92586. PointerDragBehavior._planeScene = this._scene;
  92587. }
  92588. else {
  92589. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  92590. PointerDragBehavior._planeScene.detachControl();
  92591. this._scene.getEngine().scenes.pop();
  92592. this._scene.onDisposeObservable.addOnce(function () {
  92593. PointerDragBehavior._planeScene.dispose();
  92594. PointerDragBehavior._planeScene = null;
  92595. });
  92596. }
  92597. }
  92598. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  92599. // State of the drag
  92600. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  92601. var pickPredicate = function (m) {
  92602. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  92603. };
  92604. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  92605. if (!_this.enabled) {
  92606. return;
  92607. }
  92608. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  92609. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  92610. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  92611. }
  92612. }
  92613. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  92614. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  92615. _this.releaseDrag();
  92616. }
  92617. }
  92618. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  92619. var pointerId = pointerInfo.event.pointerId;
  92620. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  92621. if (!_this._lastPointerRay[pointerId]) {
  92622. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  92623. }
  92624. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  92625. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  92626. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  92627. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  92628. _this._moveDrag(pointerInfo.pickInfo.ray);
  92629. }
  92630. }
  92631. }
  92632. });
  92633. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  92634. if (_this._moving && _this.moveAttached) {
  92635. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  92636. // Slowly move mesh to avoid jitter
  92637. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  92638. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  92639. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  92640. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  92641. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  92642. }
  92643. });
  92644. };
  92645. PointerDragBehavior.prototype.releaseDrag = function () {
  92646. this.dragging = false;
  92647. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  92648. this.currentDraggingPointerID = -1;
  92649. this._moving = false;
  92650. // Reattach camera controls
  92651. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  92652. this._scene.activeCamera.attachControl(this._attachedElement, true);
  92653. }
  92654. };
  92655. /**
  92656. * Simulates the start of a pointer drag event on the behavior
  92657. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  92658. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  92659. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  92660. */
  92661. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  92662. if (pointerId === void 0) { pointerId = 1; }
  92663. this._startDrag(pointerId, fromRay, startPickedPoint);
  92664. if (this._lastPointerRay[pointerId]) {
  92665. // if there was a last pointer ray drag the object there
  92666. this._moveDrag(this._lastPointerRay[pointerId]);
  92667. }
  92668. };
  92669. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  92670. if (pointerId === void 0) { pointerId = 1; }
  92671. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  92672. return;
  92673. }
  92674. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  92675. // Create start ray from the camera to the object
  92676. if (fromRay) {
  92677. this._startDragRay.direction.copyFrom(fromRay.direction);
  92678. this._startDragRay.origin.copyFrom(fromRay.origin);
  92679. }
  92680. else {
  92681. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  92682. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  92683. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  92684. }
  92685. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  92686. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  92687. if (pickedPoint) {
  92688. this.dragging = true;
  92689. this.currentDraggingPointerID = pointerId;
  92690. this.lastDragPosition.copyFrom(pickedPoint);
  92691. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  92692. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  92693. // Detatch camera controls
  92694. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  92695. if (this._scene.activeCamera.inputs.attachedElement) {
  92696. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  92697. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  92698. }
  92699. else {
  92700. this._attachedElement = null;
  92701. }
  92702. }
  92703. }
  92704. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  92705. };
  92706. PointerDragBehavior.prototype._moveDrag = function (ray) {
  92707. this._moving = true;
  92708. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  92709. if (pickedPoint) {
  92710. if (this.updateDragPlane) {
  92711. this._updateDragPlanePosition(ray, pickedPoint);
  92712. }
  92713. var dragLength = 0;
  92714. // depending on the drag mode option drag accordingly
  92715. if (this._options.dragAxis) {
  92716. // Convert local drag axis to world
  92717. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  92718. // Project delta drag from the drag plane onto the drag axis
  92719. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  92720. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  92721. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  92722. }
  92723. else {
  92724. dragLength = this._dragDelta.length();
  92725. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  92726. }
  92727. this._targetPosition.addInPlace(this._dragDelta);
  92728. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  92729. this.lastDragPosition.copyFrom(pickedPoint);
  92730. }
  92731. };
  92732. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  92733. var _this = this;
  92734. if (!ray) {
  92735. return null;
  92736. }
  92737. // Calculate angle between plane normal and ray
  92738. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  92739. // Correct if ray is casted from oposite side
  92740. if (angle > Math.PI / 2) {
  92741. angle = Math.PI - angle;
  92742. }
  92743. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  92744. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  92745. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  92746. // Invert ray direction along the towards object axis
  92747. this._tmpVector.copyFrom(ray.direction);
  92748. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  92749. this._alternatePickedPoint.normalize();
  92750. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  92751. this._tmpVector.addInPlace(this._alternatePickedPoint);
  92752. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  92753. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  92754. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  92755. this._alternatePickedPoint.addInPlace(this._tmpVector);
  92756. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  92757. return this._alternatePickedPoint;
  92758. }
  92759. else {
  92760. return null;
  92761. }
  92762. }
  92763. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  92764. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  92765. return pickResult.pickedPoint;
  92766. }
  92767. else {
  92768. return null;
  92769. }
  92770. };
  92771. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  92772. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  92773. this._pointA.copyFrom(dragPlanePosition);
  92774. if (this._options.dragAxis) {
  92775. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  92776. // Calculate plane normal in direction of camera but perpendicular to drag axis
  92777. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  92778. ray.origin.subtractToRef(this._pointA, this._pointC);
  92779. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  92780. // Get perpendicular line from direction to camera and drag axis
  92781. this._pointB.subtractToRef(this._pointA, this._lineA);
  92782. this._pointC.subtractToRef(this._pointA, this._lineB);
  92783. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  92784. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  92785. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  92786. this._lookAt.normalize();
  92787. this._dragPlane.position.copyFrom(this._pointA);
  92788. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  92789. this._dragPlane.lookAt(this._lookAt);
  92790. }
  92791. else if (this._options.dragPlaneNormal) {
  92792. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  92793. this._dragPlane.position.copyFrom(this._pointA);
  92794. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  92795. this._dragPlane.lookAt(this._lookAt);
  92796. }
  92797. else {
  92798. this._dragPlane.position.copyFrom(this._pointA);
  92799. this._dragPlane.lookAt(ray.origin);
  92800. }
  92801. this._dragPlane.computeWorldMatrix(true);
  92802. };
  92803. /**
  92804. * Detaches the behavior from the mesh
  92805. */
  92806. PointerDragBehavior.prototype.detach = function () {
  92807. if (this._pointerObserver) {
  92808. this._scene.onPointerObservable.remove(this._pointerObserver);
  92809. }
  92810. if (this._beforeRenderObserver) {
  92811. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  92812. }
  92813. };
  92814. return PointerDragBehavior;
  92815. }());
  92816. BABYLON.PointerDragBehavior = PointerDragBehavior;
  92817. })(BABYLON || (BABYLON = {}));
  92818. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  92819. var BABYLON;
  92820. (function (BABYLON) {
  92821. /**
  92822. * A behavior that when attached to a mesh will allow the mesh to be scaled
  92823. */
  92824. var MultiPointerScaleBehavior = /** @class */ (function () {
  92825. function MultiPointerScaleBehavior() {
  92826. this._startDistance = 0;
  92827. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  92828. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  92829. this._sceneRenderObserver = null;
  92830. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  92831. this._dragBehaviorA.moveAttached = false;
  92832. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  92833. this._dragBehaviorB.moveAttached = false;
  92834. }
  92835. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  92836. /**
  92837. * The name of the behavior
  92838. */
  92839. get: function () {
  92840. return "MultiPointerScale";
  92841. },
  92842. enumerable: true,
  92843. configurable: true
  92844. });
  92845. /**
  92846. * Initializes the behavior
  92847. */
  92848. MultiPointerScaleBehavior.prototype.init = function () { };
  92849. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  92850. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  92851. };
  92852. /**
  92853. * Attaches the scale behavior the passed in mesh
  92854. * @param ownerNode The mesh that will be scaled around once attached
  92855. */
  92856. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  92857. var _this = this;
  92858. this._ownerNode = ownerNode;
  92859. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  92860. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  92861. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92862. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  92863. _this._dragBehaviorA.releaseDrag();
  92864. }
  92865. else {
  92866. _this._initialScale.copyFrom(ownerNode.scaling);
  92867. _this._startDistance = _this._getCurrentDistance();
  92868. }
  92869. }
  92870. });
  92871. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  92872. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92873. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  92874. _this._dragBehaviorB.releaseDrag();
  92875. }
  92876. else {
  92877. _this._initialScale.copyFrom(ownerNode.scaling);
  92878. _this._startDistance = _this._getCurrentDistance();
  92879. }
  92880. }
  92881. });
  92882. // Once both drag behaviors are active scale based on the distance between the two pointers
  92883. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  92884. behavior.onDragObservable.add(function () {
  92885. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92886. var ratio = _this._getCurrentDistance() / _this._startDistance;
  92887. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  92888. }
  92889. });
  92890. });
  92891. ownerNode.addBehavior(this._dragBehaviorA);
  92892. ownerNode.addBehavior(this._dragBehaviorB);
  92893. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  92894. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  92895. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92896. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  92897. if (change.length() > 0.01) {
  92898. ownerNode.scaling.addInPlace(change);
  92899. }
  92900. }
  92901. });
  92902. };
  92903. /**
  92904. * Detaches the behavior from the mesh
  92905. */
  92906. MultiPointerScaleBehavior.prototype.detach = function () {
  92907. var _this = this;
  92908. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  92909. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  92910. behavior.onDragStartObservable.clear();
  92911. behavior.onDragObservable.clear();
  92912. _this._ownerNode.removeBehavior(behavior);
  92913. });
  92914. };
  92915. return MultiPointerScaleBehavior;
  92916. }());
  92917. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  92918. })(BABYLON || (BABYLON = {}));
  92919. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  92920. var BABYLON;
  92921. (function (BABYLON) {
  92922. /**
  92923. * 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
  92924. */
  92925. var SixDofDragBehavior = /** @class */ (function () {
  92926. function SixDofDragBehavior() {
  92927. this._sceneRenderObserver = null;
  92928. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  92929. this._moving = false;
  92930. this._startingOrientation = new BABYLON.Quaternion();
  92931. /**
  92932. * 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)
  92933. */
  92934. this.zDragFactor = 3;
  92935. /**
  92936. * If the behavior is currently in a dragging state
  92937. */
  92938. this.dragging = false;
  92939. /**
  92940. * 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)
  92941. */
  92942. this.dragDeltaRatio = 0.2;
  92943. /**
  92944. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  92945. */
  92946. this.currentDraggingPointerID = -1;
  92947. /**
  92948. * If camera controls should be detached during the drag
  92949. */
  92950. this.detachCameraControls = true;
  92951. }
  92952. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  92953. /**
  92954. * The name of the behavior
  92955. */
  92956. get: function () {
  92957. return "SixDofDrag";
  92958. },
  92959. enumerable: true,
  92960. configurable: true
  92961. });
  92962. /**
  92963. * Initializes the behavior
  92964. */
  92965. SixDofDragBehavior.prototype.init = function () { };
  92966. /**
  92967. * Attaches the scale behavior the passed in mesh
  92968. * @param ownerNode The mesh that will be scaled around once attached
  92969. */
  92970. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  92971. var _this = this;
  92972. this._ownerNode = ownerNode;
  92973. this._scene = this._ownerNode.getScene();
  92974. if (!SixDofDragBehavior._virtualScene) {
  92975. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  92976. this._scene.getEngine().scenes.pop();
  92977. }
  92978. var pickedMesh = null;
  92979. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  92980. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  92981. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  92982. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  92983. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  92984. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  92985. var pickPredicate = function (m) {
  92986. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  92987. };
  92988. var attachedElement = null;
  92989. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  92990. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  92991. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  92992. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  92993. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  92994. }
  92995. pickedMesh = _this._ownerNode;
  92996. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  92997. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  92998. // Set position and orientation of the controller
  92999. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  93000. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  93001. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  93002. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93003. pickedMesh.computeWorldMatrix();
  93004. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  93005. if (!pickedMesh.rotationQuaternion) {
  93006. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  93007. }
  93008. var oldParent = pickedMesh.parent;
  93009. pickedMesh.setParent(null);
  93010. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  93011. pickedMesh.setParent(oldParent);
  93012. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  93013. // Update state
  93014. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  93015. _this.dragging = true;
  93016. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  93017. // Detatch camera controls
  93018. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  93019. if (_this._scene.activeCamera.inputs.attachedElement) {
  93020. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  93021. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  93022. }
  93023. else {
  93024. attachedElement = null;
  93025. }
  93026. }
  93027. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  93028. }
  93029. }
  93030. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  93031. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  93032. _this.dragging = false;
  93033. _this._moving = false;
  93034. _this.currentDraggingPointerID = -1;
  93035. pickedMesh = null;
  93036. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93037. // Reattach camera controls
  93038. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  93039. _this._scene.activeCamera.attachControl(attachedElement, true);
  93040. }
  93041. }
  93042. }
  93043. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  93044. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  93045. var zDragFactor = _this.zDragFactor;
  93046. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  93047. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  93048. zDragFactor = 0;
  93049. }
  93050. // Calculate controller drag distance in controller space
  93051. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  93052. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  93053. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  93054. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  93055. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  93056. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  93057. if (_this._virtualDragMesh.position.z < 0) {
  93058. _this._virtualDragMesh.position.z = 0;
  93059. }
  93060. // Update the controller position
  93061. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  93062. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  93063. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93064. // Move the virtualObjectsPosition into the picked mesh's space if needed
  93065. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  93066. if (pickedMesh.parent) {
  93067. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  93068. }
  93069. if (!_this._moving) {
  93070. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  93071. }
  93072. _this._moving = true;
  93073. }
  93074. }
  93075. });
  93076. var tmpQuaternion = new BABYLON.Quaternion();
  93077. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  93078. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  93079. if (_this.dragging && _this._moving && pickedMesh) {
  93080. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  93081. // Slowly move mesh to avoid jitter
  93082. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  93083. // Get change in rotation
  93084. tmpQuaternion.copyFrom(_this._startingOrientation);
  93085. tmpQuaternion.x = -tmpQuaternion.x;
  93086. tmpQuaternion.y = -tmpQuaternion.y;
  93087. tmpQuaternion.z = -tmpQuaternion.z;
  93088. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  93089. // Convert change in rotation to only y axis rotation
  93090. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  93091. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  93092. // Slowly move mesh to avoid jitter
  93093. var oldParent = pickedMesh.parent;
  93094. pickedMesh.setParent(null);
  93095. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  93096. pickedMesh.setParent(oldParent);
  93097. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  93098. }
  93099. });
  93100. };
  93101. /**
  93102. * Detaches the behavior from the mesh
  93103. */
  93104. SixDofDragBehavior.prototype.detach = function () {
  93105. if (this._scene) {
  93106. this._scene.onPointerObservable.remove(this._pointerObserver);
  93107. }
  93108. if (this._ownerNode) {
  93109. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  93110. }
  93111. if (this._virtualOriginMesh) {
  93112. this._virtualOriginMesh.dispose();
  93113. }
  93114. if (this._virtualDragMesh) {
  93115. this._virtualDragMesh.dispose();
  93116. }
  93117. };
  93118. return SixDofDragBehavior;
  93119. }());
  93120. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  93121. })(BABYLON || (BABYLON = {}));
  93122. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  93123. var BABYLON;
  93124. (function (BABYLON) {
  93125. /**
  93126. * @hidden
  93127. */
  93128. var FaceDirectionInfo = /** @class */ (function () {
  93129. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  93130. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  93131. if (diff === void 0) { diff = 0; }
  93132. if (ignore === void 0) { ignore = false; }
  93133. this.direction = direction;
  93134. this.rotatedDirection = rotatedDirection;
  93135. this.diff = diff;
  93136. this.ignore = ignore;
  93137. }
  93138. return FaceDirectionInfo;
  93139. }());
  93140. /**
  93141. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  93142. */
  93143. var AttachToBoxBehavior = /** @class */ (function () {
  93144. /**
  93145. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  93146. * @param ui The transform node that should be attched to the mesh
  93147. */
  93148. function AttachToBoxBehavior(ui) {
  93149. this.ui = ui;
  93150. /**
  93151. * The name of the behavior
  93152. */
  93153. this.name = "AttachToBoxBehavior";
  93154. /**
  93155. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  93156. */
  93157. this.distanceAwayFromFace = 0.15;
  93158. /**
  93159. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  93160. */
  93161. this.distanceAwayFromBottomOfFace = 0.15;
  93162. 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))];
  93163. this._tmpMatrix = new BABYLON.Matrix();
  93164. this._tmpVector = new BABYLON.Vector3();
  93165. this._zeroVector = BABYLON.Vector3.Zero();
  93166. this._lookAtTmpMatrix = new BABYLON.Matrix();
  93167. /* Does nothing */
  93168. }
  93169. /**
  93170. * Initializes the behavior
  93171. */
  93172. AttachToBoxBehavior.prototype.init = function () {
  93173. /* Does nothing */
  93174. };
  93175. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  93176. var _this = this;
  93177. // Go over each face and calculate the angle between the face's normal and targetDirection
  93178. this._faceVectors.forEach(function (v) {
  93179. if (!_this._target.rotationQuaternion) {
  93180. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  93181. }
  93182. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  93183. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  93184. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  93185. });
  93186. // Return the face information of the one with the normal closeset to target direction
  93187. return this._faceVectors.reduce(function (min, p) {
  93188. if (min.ignore) {
  93189. return p;
  93190. }
  93191. else if (p.ignore) {
  93192. return min;
  93193. }
  93194. else {
  93195. return min.diff < p.diff ? min : p;
  93196. }
  93197. }, this._faceVectors[0]);
  93198. };
  93199. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  93200. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  93201. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  93202. this._lookAtTmpMatrix.invert();
  93203. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  93204. };
  93205. /**
  93206. * Attaches the AttachToBoxBehavior to the passed in mesh
  93207. * @param target The mesh that the specified node will be attached to
  93208. */
  93209. AttachToBoxBehavior.prototype.attach = function (target) {
  93210. var _this = this;
  93211. this._target = target;
  93212. this._scene = this._target.getScene();
  93213. // Every frame, update the app bars position
  93214. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  93215. if (!_this._scene.activeCamera) {
  93216. return;
  93217. }
  93218. // Find the face closest to the cameras position
  93219. var cameraPos = _this._scene.activeCamera.position;
  93220. if (_this._scene.activeCamera.devicePosition) {
  93221. cameraPos = _this._scene.activeCamera.devicePosition;
  93222. }
  93223. var facing = _this._closestFace(cameraPos.subtract(target.position));
  93224. if (_this._scene.activeCamera.leftCamera) {
  93225. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  93226. }
  93227. else {
  93228. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  93229. }
  93230. // Get camera up direction
  93231. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  93232. // Ignore faces to not select a parrelel face for the up vector of the UI
  93233. _this._faceVectors.forEach(function (v) {
  93234. if (facing.direction.x && v.direction.x) {
  93235. v.ignore = true;
  93236. }
  93237. if (facing.direction.y && v.direction.y) {
  93238. v.ignore = true;
  93239. }
  93240. if (facing.direction.z && v.direction.z) {
  93241. v.ignore = true;
  93242. }
  93243. });
  93244. var facingUp = _this._closestFace(_this._tmpVector);
  93245. // Unignore faces
  93246. _this._faceVectors.forEach(function (v) {
  93247. v.ignore = false;
  93248. });
  93249. // Position the app bar on that face
  93250. _this.ui.position.copyFrom(target.position);
  93251. if (facing.direction.x) {
  93252. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93253. _this.ui.position.addInPlace(_this._tmpVector);
  93254. }
  93255. if (facing.direction.y) {
  93256. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93257. _this.ui.position.addInPlace(_this._tmpVector);
  93258. }
  93259. if (facing.direction.z) {
  93260. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93261. _this.ui.position.addInPlace(_this._tmpVector);
  93262. }
  93263. // Rotate to be oriented properly to the camera
  93264. if (!_this.ui.rotationQuaternion) {
  93265. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  93266. }
  93267. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  93268. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  93269. // Place ui the correct distance from the bottom of the mesh
  93270. if (facingUp.direction.x) {
  93271. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  93272. }
  93273. if (facingUp.direction.y) {
  93274. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  93275. }
  93276. if (facingUp.direction.z) {
  93277. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  93278. }
  93279. _this.ui.position.addInPlace(_this._tmpVector);
  93280. });
  93281. };
  93282. /**
  93283. * Detaches the behavior from the mesh
  93284. */
  93285. AttachToBoxBehavior.prototype.detach = function () {
  93286. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  93287. };
  93288. return AttachToBoxBehavior;
  93289. }());
  93290. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  93291. })(BABYLON || (BABYLON = {}));
  93292. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  93293. var BABYLON;
  93294. (function (BABYLON) {
  93295. /**
  93296. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  93297. */
  93298. var FadeInOutBehavior = /** @class */ (function () {
  93299. /**
  93300. * Instatiates the FadeInOutBehavior
  93301. */
  93302. function FadeInOutBehavior() {
  93303. var _this = this;
  93304. /**
  93305. * Time in milliseconds to delay before fading in (Default: 0)
  93306. */
  93307. this.delay = 0;
  93308. /**
  93309. * Time in milliseconds for the mesh to fade in (Default: 300)
  93310. */
  93311. this.fadeInTime = 300;
  93312. this._millisecondsPerFrame = 1000 / 60;
  93313. this._hovered = false;
  93314. this._hoverValue = 0;
  93315. this._ownerNode = null;
  93316. this._update = function () {
  93317. if (_this._ownerNode) {
  93318. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  93319. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  93320. if (_this._ownerNode.visibility > 1) {
  93321. _this._setAllVisibility(_this._ownerNode, 1);
  93322. _this._hoverValue = _this.fadeInTime + _this.delay;
  93323. return;
  93324. }
  93325. else if (_this._ownerNode.visibility < 0) {
  93326. _this._setAllVisibility(_this._ownerNode, 0);
  93327. if (_this._hoverValue < 0) {
  93328. _this._hoverValue = 0;
  93329. return;
  93330. }
  93331. }
  93332. setTimeout(_this._update, _this._millisecondsPerFrame);
  93333. }
  93334. };
  93335. }
  93336. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  93337. /**
  93338. * The name of the behavior
  93339. */
  93340. get: function () {
  93341. return "FadeInOut";
  93342. },
  93343. enumerable: true,
  93344. configurable: true
  93345. });
  93346. /**
  93347. * Initializes the behavior
  93348. */
  93349. FadeInOutBehavior.prototype.init = function () {
  93350. };
  93351. /**
  93352. * Attaches the fade behavior on the passed in mesh
  93353. * @param ownerNode The mesh that will be faded in/out once attached
  93354. */
  93355. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  93356. this._ownerNode = ownerNode;
  93357. this._setAllVisibility(this._ownerNode, 0);
  93358. };
  93359. /**
  93360. * Detaches the behavior from the mesh
  93361. */
  93362. FadeInOutBehavior.prototype.detach = function () {
  93363. this._ownerNode = null;
  93364. };
  93365. /**
  93366. * Triggers the mesh to begin fading in or out
  93367. * @param value if the object should fade in or out (true to fade in)
  93368. */
  93369. FadeInOutBehavior.prototype.fadeIn = function (value) {
  93370. this._hovered = value;
  93371. this._update();
  93372. };
  93373. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  93374. var _this = this;
  93375. mesh.visibility = value;
  93376. mesh.getChildMeshes().forEach(function (c) {
  93377. _this._setAllVisibility(c, value);
  93378. });
  93379. };
  93380. return FadeInOutBehavior;
  93381. }());
  93382. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  93383. })(BABYLON || (BABYLON = {}));
  93384. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  93385. var BABYLON;
  93386. (function (BABYLON) {
  93387. /**
  93388. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  93389. */
  93390. var Gizmo = /** @class */ (function () {
  93391. /**
  93392. * Creates a gizmo
  93393. * @param gizmoLayer The utility layer the gizmo will be added to
  93394. */
  93395. function Gizmo(
  93396. /** The utility layer the gizmo will be added to */
  93397. gizmoLayer) {
  93398. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93399. var _this = this;
  93400. this.gizmoLayer = gizmoLayer;
  93401. /**
  93402. * Ratio for the scale of the gizmo (Default: 1)
  93403. */
  93404. this.scaleRatio = 1;
  93405. this._tmpMatrix = new BABYLON.Matrix();
  93406. /**
  93407. * If a custom mesh has been set (Default: false)
  93408. */
  93409. this._customMeshSet = false;
  93410. /**
  93411. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  93412. */
  93413. this.updateGizmoRotationToMatchAttachedMesh = true;
  93414. /**
  93415. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  93416. */
  93417. this.updateGizmoPositionToMatchAttachedMesh = true;
  93418. /**
  93419. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  93420. */
  93421. this._updateScale = true;
  93422. this._interactionsEnabled = true;
  93423. this._tempVector = new BABYLON.Vector3();
  93424. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  93425. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  93426. _this._update();
  93427. });
  93428. this.attachedMesh = null;
  93429. }
  93430. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  93431. /**
  93432. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  93433. * * When set, interactions will be enabled
  93434. */
  93435. get: function () {
  93436. return this._attachedMesh;
  93437. },
  93438. set: function (value) {
  93439. this._attachedMesh = value;
  93440. this._rootMesh.setEnabled(value ? true : false);
  93441. this._attachedMeshChanged(value);
  93442. },
  93443. enumerable: true,
  93444. configurable: true
  93445. });
  93446. /**
  93447. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  93448. * @param mesh The mesh to replace the default mesh of the gizmo
  93449. */
  93450. Gizmo.prototype.setCustomMesh = function (mesh) {
  93451. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  93452. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  93453. }
  93454. this._rootMesh.getChildMeshes().forEach(function (c) {
  93455. c.dispose();
  93456. });
  93457. mesh.parent = this._rootMesh;
  93458. this._customMeshSet = true;
  93459. };
  93460. Gizmo.prototype._attachedMeshChanged = function (value) {
  93461. };
  93462. /**
  93463. * @hidden
  93464. * Updates the gizmo to match the attached mesh's position/rotation
  93465. */
  93466. Gizmo.prototype._update = function () {
  93467. if (this.attachedMesh) {
  93468. if (this.updateGizmoRotationToMatchAttachedMesh) {
  93469. if (!this._rootMesh.rotationQuaternion) {
  93470. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  93471. }
  93472. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  93473. this._tempVector.copyFrom(this.attachedMesh.scaling);
  93474. if (this.attachedMesh.scaling.x < 0) {
  93475. this.attachedMesh.scaling.x *= -1;
  93476. }
  93477. if (this.attachedMesh.scaling.y < 0) {
  93478. this.attachedMesh.scaling.y *= -1;
  93479. }
  93480. if (this.attachedMesh.scaling.z < 0) {
  93481. this.attachedMesh.scaling.z *= -1;
  93482. }
  93483. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  93484. this.attachedMesh.scaling.copyFrom(this._tempVector);
  93485. this.attachedMesh.computeWorldMatrix();
  93486. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  93487. }
  93488. else if (this._rootMesh.rotationQuaternion) {
  93489. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  93490. }
  93491. if (this.updateGizmoPositionToMatchAttachedMesh) {
  93492. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  93493. }
  93494. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  93495. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  93496. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  93497. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  93498. }
  93499. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  93500. var dist = this._tempVector.length() * this.scaleRatio;
  93501. this._rootMesh.scaling.set(dist, dist, dist);
  93502. }
  93503. }
  93504. };
  93505. /**
  93506. * Disposes of the gizmo
  93507. */
  93508. Gizmo.prototype.dispose = function () {
  93509. this._rootMesh.dispose();
  93510. if (this._beforeRenderObserver) {
  93511. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  93512. }
  93513. };
  93514. return Gizmo;
  93515. }());
  93516. BABYLON.Gizmo = Gizmo;
  93517. })(BABYLON || (BABYLON = {}));
  93518. //# sourceMappingURL=babylon.gizmo.js.map
  93519. var BABYLON;
  93520. (function (BABYLON) {
  93521. /**
  93522. * Single axis drag gizmo
  93523. */
  93524. var AxisDragGizmo = /** @class */ (function (_super) {
  93525. __extends(AxisDragGizmo, _super);
  93526. /**
  93527. * Creates an AxisDragGizmo
  93528. * @param gizmoLayer The utility layer the gizmo will be added to
  93529. * @param dragAxis The axis which the gizmo will be able to drag on
  93530. * @param color The color of the gizmo
  93531. */
  93532. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  93533. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93534. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93535. var _this = _super.call(this, gizmoLayer) || this;
  93536. _this._pointerObserver = null;
  93537. /**
  93538. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93539. */
  93540. _this.snapDistance = 0;
  93541. /**
  93542. * Event that fires each time the gizmo snaps to a new location.
  93543. * * snapDistance is the the change in distance
  93544. */
  93545. _this.onSnapObservable = new BABYLON.Observable();
  93546. // Create Material
  93547. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93548. coloredMaterial.disableLighting = true;
  93549. coloredMaterial.emissiveColor = color;
  93550. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93551. hoverMaterial.disableLighting = true;
  93552. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93553. // Build mesh on root node
  93554. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93555. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  93556. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  93557. arrowTail.color = coloredMaterial.emissiveColor;
  93558. arrow.addChild(arrowMesh);
  93559. arrow.addChild(arrowTail);
  93560. // Position arrow pointing in its drag axis
  93561. arrowMesh.scaling.scaleInPlace(0.05);
  93562. arrowMesh.material = coloredMaterial;
  93563. arrowMesh.rotation.x = Math.PI / 2;
  93564. arrowMesh.position.z += 0.3;
  93565. arrowTail.scaling.scaleInPlace(0.26);
  93566. arrowTail.rotation.x = Math.PI / 2;
  93567. arrowTail.material = coloredMaterial;
  93568. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  93569. arrow.scaling.scaleInPlace(1 / 3);
  93570. _this._rootMesh.addChild(arrow);
  93571. var currentSnapDragDistance = 0;
  93572. var tmpVector = new BABYLON.Vector3();
  93573. var tmpSnapEvent = { snapDistance: 0 };
  93574. // Add drag behavior to handle events when the gizmo is dragged
  93575. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93576. _this.dragBehavior.moveAttached = false;
  93577. _this._rootMesh.addBehavior(_this.dragBehavior);
  93578. var localDelta = new BABYLON.Vector3();
  93579. var tmpMatrix = new BABYLON.Matrix();
  93580. _this.dragBehavior.onDragObservable.add(function (event) {
  93581. if (_this.attachedMesh) {
  93582. // Convert delta to local translation if it has a parent
  93583. if (_this.attachedMesh.parent) {
  93584. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  93585. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  93586. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  93587. }
  93588. else {
  93589. localDelta.copyFrom(event.delta);
  93590. }
  93591. // Snapping logic
  93592. if (_this.snapDistance == 0) {
  93593. _this.attachedMesh.position.addInPlace(localDelta);
  93594. }
  93595. else {
  93596. currentSnapDragDistance += event.dragDistance;
  93597. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  93598. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  93599. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  93600. localDelta.normalizeToRef(tmpVector);
  93601. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  93602. _this.attachedMesh.position.addInPlace(tmpVector);
  93603. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  93604. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  93605. }
  93606. }
  93607. }
  93608. });
  93609. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93610. if (_this._customMeshSet) {
  93611. return;
  93612. }
  93613. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  93614. var material = isHovered ? hoverMaterial : coloredMaterial;
  93615. _this._rootMesh.getChildMeshes().forEach(function (m) {
  93616. m.material = material;
  93617. if (m.color) {
  93618. m.color = material.emissiveColor;
  93619. }
  93620. });
  93621. });
  93622. return _this;
  93623. }
  93624. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  93625. if (this.dragBehavior) {
  93626. this.dragBehavior.enabled = value ? true : false;
  93627. }
  93628. };
  93629. /**
  93630. * Disposes of the gizmo
  93631. */
  93632. AxisDragGizmo.prototype.dispose = function () {
  93633. this.onSnapObservable.clear();
  93634. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93635. this.dragBehavior.detach();
  93636. _super.prototype.dispose.call(this);
  93637. };
  93638. return AxisDragGizmo;
  93639. }(BABYLON.Gizmo));
  93640. BABYLON.AxisDragGizmo = AxisDragGizmo;
  93641. })(BABYLON || (BABYLON = {}));
  93642. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  93643. var BABYLON;
  93644. (function (BABYLON) {
  93645. /**
  93646. * Single axis scale gizmo
  93647. */
  93648. var AxisScaleGizmo = /** @class */ (function (_super) {
  93649. __extends(AxisScaleGizmo, _super);
  93650. /**
  93651. * Creates an AxisScaleGizmo
  93652. * @param gizmoLayer The utility layer the gizmo will be added to
  93653. * @param dragAxis The axis which the gizmo will be able to scale on
  93654. * @param color The color of the gizmo
  93655. */
  93656. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  93657. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93658. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93659. var _this = _super.call(this, gizmoLayer) || this;
  93660. _this._pointerObserver = null;
  93661. /**
  93662. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93663. */
  93664. _this.snapDistance = 0;
  93665. /**
  93666. * Event that fires each time the gizmo snaps to a new location.
  93667. * * snapDistance is the the change in distance
  93668. */
  93669. _this.onSnapObservable = new BABYLON.Observable();
  93670. /**
  93671. * If the scaling operation should be done on all axis (default: false)
  93672. */
  93673. _this.uniformScaling = false;
  93674. // Create Material
  93675. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93676. _this._coloredMaterial.disableLighting = true;
  93677. _this._coloredMaterial.emissiveColor = color;
  93678. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93679. hoverMaterial.disableLighting = true;
  93680. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93681. // Build mesh on root node
  93682. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93683. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  93684. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  93685. arrowTail.color = _this._coloredMaterial.emissiveColor;
  93686. arrow.addChild(arrowMesh);
  93687. arrow.addChild(arrowTail);
  93688. // Position arrow pointing in its drag axis
  93689. arrowMesh.scaling.scaleInPlace(0.1);
  93690. arrowMesh.material = _this._coloredMaterial;
  93691. arrowMesh.rotation.x = Math.PI / 2;
  93692. arrowMesh.position.z += 0.3;
  93693. arrowTail.scaling.scaleInPlace(0.26);
  93694. arrowTail.rotation.x = Math.PI / 2;
  93695. arrowTail.material = _this._coloredMaterial;
  93696. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  93697. _this._rootMesh.addChild(arrow);
  93698. arrow.scaling.scaleInPlace(1 / 3);
  93699. // Add drag behavior to handle events when the gizmo is dragged
  93700. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93701. _this.dragBehavior.moveAttached = false;
  93702. _this._rootMesh.addBehavior(_this.dragBehavior);
  93703. var currentSnapDragDistance = 0;
  93704. var tmpVector = new BABYLON.Vector3();
  93705. var tmpSnapEvent = { snapDistance: 0 };
  93706. _this.dragBehavior.onDragObservable.add(function (event) {
  93707. if (_this.attachedMesh) {
  93708. // Snapping logic
  93709. var snapped = false;
  93710. var dragSteps = 0;
  93711. if (_this.uniformScaling) {
  93712. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  93713. if (tmpVector.y < 0) {
  93714. tmpVector.scaleInPlace(-1);
  93715. }
  93716. }
  93717. else {
  93718. tmpVector.copyFrom(dragAxis);
  93719. }
  93720. if (_this.snapDistance == 0) {
  93721. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  93722. }
  93723. else {
  93724. currentSnapDragDistance += event.dragDistance;
  93725. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  93726. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  93727. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  93728. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  93729. snapped = true;
  93730. }
  93731. else {
  93732. tmpVector.scaleInPlace(0);
  93733. }
  93734. }
  93735. _this.attachedMesh.scaling.addInPlace(tmpVector);
  93736. if (snapped) {
  93737. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  93738. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  93739. }
  93740. }
  93741. });
  93742. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93743. if (_this._customMeshSet) {
  93744. return;
  93745. }
  93746. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  93747. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  93748. _this._rootMesh.getChildMeshes().forEach(function (m) {
  93749. m.material = material;
  93750. if (m.color) {
  93751. m.color = material.emissiveColor;
  93752. }
  93753. });
  93754. });
  93755. return _this;
  93756. }
  93757. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  93758. if (this.dragBehavior) {
  93759. this.dragBehavior.enabled = value ? true : false;
  93760. }
  93761. };
  93762. /**
  93763. * Disposes of the gizmo
  93764. */
  93765. AxisScaleGizmo.prototype.dispose = function () {
  93766. this.onSnapObservable.clear();
  93767. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93768. this.dragBehavior.detach();
  93769. _super.prototype.dispose.call(this);
  93770. };
  93771. /**
  93772. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  93773. * @param mesh The mesh to replace the default mesh of the gizmo
  93774. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  93775. */
  93776. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  93777. var _this = this;
  93778. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  93779. _super.prototype.setCustomMesh.call(this, mesh);
  93780. if (useGizmoMaterial) {
  93781. this._rootMesh.getChildMeshes().forEach(function (m) {
  93782. m.material = _this._coloredMaterial;
  93783. if (m.color) {
  93784. m.color = _this._coloredMaterial.emissiveColor;
  93785. }
  93786. });
  93787. this._customMeshSet = false;
  93788. }
  93789. };
  93790. return AxisScaleGizmo;
  93791. }(BABYLON.Gizmo));
  93792. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  93793. })(BABYLON || (BABYLON = {}));
  93794. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  93795. var BABYLON;
  93796. (function (BABYLON) {
  93797. /**
  93798. * Single plane rotation gizmo
  93799. */
  93800. var PlaneRotationGizmo = /** @class */ (function (_super) {
  93801. __extends(PlaneRotationGizmo, _super);
  93802. /**
  93803. * Creates a PlaneRotationGizmo
  93804. * @param gizmoLayer The utility layer the gizmo will be added to
  93805. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  93806. * @param color The color of the gizmo
  93807. */
  93808. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  93809. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93810. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93811. var _this = _super.call(this, gizmoLayer) || this;
  93812. _this._pointerObserver = null;
  93813. /**
  93814. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  93815. */
  93816. _this.snapDistance = 0;
  93817. /**
  93818. * Event that fires each time the gizmo snaps to a new location.
  93819. * * snapDistance is the the change in distance
  93820. */
  93821. _this.onSnapObservable = new BABYLON.Observable();
  93822. // Create Material
  93823. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93824. coloredMaterial.disableLighting = true;
  93825. coloredMaterial.emissiveColor = color;
  93826. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93827. hoverMaterial.disableLighting = true;
  93828. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93829. // Build mesh on root node
  93830. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93831. // Create circle out of lines
  93832. var tessellation = 20;
  93833. var radius = 0.8;
  93834. var points = new Array();
  93835. for (var i = 0; i < tessellation; i++) {
  93836. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  93837. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  93838. }
  93839. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  93840. rotationMesh.color = coloredMaterial.emissiveColor;
  93841. // Position arrow pointing in its drag axis
  93842. rotationMesh.scaling.scaleInPlace(0.26);
  93843. rotationMesh.material = coloredMaterial;
  93844. rotationMesh.rotation.x = Math.PI / 2;
  93845. parentMesh.addChild(rotationMesh);
  93846. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  93847. _this._rootMesh.addChild(parentMesh);
  93848. parentMesh.scaling.scaleInPlace(1 / 3);
  93849. // Add drag behavior to handle events when the gizmo is dragged
  93850. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  93851. _this.dragBehavior.moveAttached = false;
  93852. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  93853. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  93854. _this._rootMesh.addBehavior(_this.dragBehavior);
  93855. var lastDragPosition = new BABYLON.Vector3();
  93856. _this.dragBehavior.onDragStartObservable.add(function (e) {
  93857. if (_this.attachedMesh) {
  93858. lastDragPosition.copyFrom(e.dragPlanePoint);
  93859. }
  93860. });
  93861. var rotationMatrix = new BABYLON.Matrix();
  93862. var planeNormalTowardsCamera = new BABYLON.Vector3();
  93863. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  93864. var tmpSnapEvent = { snapDistance: 0 };
  93865. var currentSnapDragDistance = 0;
  93866. var tmpMatrix = new BABYLON.Matrix();
  93867. var tmpVector = new BABYLON.Vector3();
  93868. var amountToRotate = new BABYLON.Quaternion();
  93869. _this.dragBehavior.onDragObservable.add(function (event) {
  93870. if (_this.attachedMesh) {
  93871. if (!_this.attachedMesh.rotationQuaternion) {
  93872. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  93873. }
  93874. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  93875. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  93876. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  93877. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  93878. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  93879. var angle = Math.atan2(cross.length(), dot);
  93880. planeNormalTowardsCamera.copyFrom(planeNormal);
  93881. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  93882. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  93883. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  93884. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  93885. }
  93886. // Flip up vector depending on which side the camera is on
  93887. if (gizmoLayer.utilityLayerScene.activeCamera) {
  93888. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  93889. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  93890. planeNormalTowardsCamera.scaleInPlace(-1);
  93891. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  93892. }
  93893. }
  93894. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  93895. if (halfCircleSide)
  93896. angle = -angle;
  93897. // Snapping logic
  93898. var snapped = false;
  93899. if (_this.snapDistance != 0) {
  93900. currentSnapDragDistance += angle;
  93901. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  93902. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  93903. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  93904. angle = _this.snapDistance * dragSteps;
  93905. snapped = true;
  93906. }
  93907. else {
  93908. angle = 0;
  93909. }
  93910. }
  93911. // If the mesh has a parent, convert needed world rotation to local rotation
  93912. tmpMatrix.reset();
  93913. if (_this.attachedMesh.parent) {
  93914. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  93915. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  93916. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  93917. }
  93918. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  93919. var quaternionCoefficient = Math.sin(angle / 2);
  93920. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  93921. // 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
  93922. if (tmpMatrix.determinant() > 0) {
  93923. amountToRotate.toEulerAnglesToRef(tmpVector);
  93924. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  93925. }
  93926. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  93927. // Rotate selected mesh quaternion over fixed axis
  93928. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  93929. }
  93930. else {
  93931. // Rotate selected mesh quaternion over rotated axis
  93932. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  93933. }
  93934. lastDragPosition.copyFrom(event.dragPlanePoint);
  93935. if (snapped) {
  93936. tmpSnapEvent.snapDistance = angle;
  93937. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  93938. }
  93939. }
  93940. });
  93941. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93942. if (_this._customMeshSet) {
  93943. return;
  93944. }
  93945. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  93946. var material = isHovered ? hoverMaterial : coloredMaterial;
  93947. _this._rootMesh.getChildMeshes().forEach(function (m) {
  93948. m.material = material;
  93949. if (m.color) {
  93950. m.color = material.emissiveColor;
  93951. }
  93952. });
  93953. });
  93954. return _this;
  93955. }
  93956. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  93957. if (this.dragBehavior) {
  93958. this.dragBehavior.enabled = value ? true : false;
  93959. }
  93960. };
  93961. /**
  93962. * Disposes of the gizmo
  93963. */
  93964. PlaneRotationGizmo.prototype.dispose = function () {
  93965. this.onSnapObservable.clear();
  93966. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93967. this.dragBehavior.detach();
  93968. _super.prototype.dispose.call(this);
  93969. };
  93970. return PlaneRotationGizmo;
  93971. }(BABYLON.Gizmo));
  93972. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  93973. })(BABYLON || (BABYLON = {}));
  93974. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  93975. var BABYLON;
  93976. (function (BABYLON) {
  93977. /**
  93978. * Gizmo that enables dragging a mesh along 3 axis
  93979. */
  93980. var PositionGizmo = /** @class */ (function (_super) {
  93981. __extends(PositionGizmo, _super);
  93982. /**
  93983. * Creates a PositionGizmo
  93984. * @param gizmoLayer The utility layer the gizmo will be added to
  93985. */
  93986. function PositionGizmo(gizmoLayer) {
  93987. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93988. var _this = _super.call(this, gizmoLayer) || this;
  93989. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  93990. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  93991. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  93992. _this.attachedMesh = null;
  93993. return _this;
  93994. }
  93995. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  93996. set: function (mesh) {
  93997. if (this.xGizmo) {
  93998. this.xGizmo.attachedMesh = mesh;
  93999. this.yGizmo.attachedMesh = mesh;
  94000. this.zGizmo.attachedMesh = mesh;
  94001. }
  94002. },
  94003. enumerable: true,
  94004. configurable: true
  94005. });
  94006. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94007. get: function () {
  94008. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94009. },
  94010. set: function (value) {
  94011. if (this.xGizmo) {
  94012. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94013. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94014. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94015. }
  94016. },
  94017. enumerable: true,
  94018. configurable: true
  94019. });
  94020. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  94021. get: function () {
  94022. return this.xGizmo.snapDistance;
  94023. },
  94024. /**
  94025. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94026. */
  94027. set: function (value) {
  94028. if (this.xGizmo) {
  94029. this.xGizmo.snapDistance = value;
  94030. this.yGizmo.snapDistance = value;
  94031. this.zGizmo.snapDistance = value;
  94032. }
  94033. },
  94034. enumerable: true,
  94035. configurable: true
  94036. });
  94037. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  94038. get: function () {
  94039. return this.xGizmo.scaleRatio;
  94040. },
  94041. /**
  94042. * Ratio for the scale of the gizmo (Default: 1)
  94043. */
  94044. set: function (value) {
  94045. if (this.xGizmo) {
  94046. this.xGizmo.scaleRatio = value;
  94047. this.yGizmo.scaleRatio = value;
  94048. this.zGizmo.scaleRatio = value;
  94049. }
  94050. },
  94051. enumerable: true,
  94052. configurable: true
  94053. });
  94054. /**
  94055. * Disposes of the gizmo
  94056. */
  94057. PositionGizmo.prototype.dispose = function () {
  94058. this.xGizmo.dispose();
  94059. this.yGizmo.dispose();
  94060. this.zGizmo.dispose();
  94061. };
  94062. /**
  94063. * CustomMeshes are not supported by this gizmo
  94064. * @param mesh The mesh to replace the default mesh of the gizmo
  94065. */
  94066. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  94067. 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)");
  94068. };
  94069. return PositionGizmo;
  94070. }(BABYLON.Gizmo));
  94071. BABYLON.PositionGizmo = PositionGizmo;
  94072. })(BABYLON || (BABYLON = {}));
  94073. //# sourceMappingURL=babylon.positionGizmo.js.map
  94074. var BABYLON;
  94075. (function (BABYLON) {
  94076. /**
  94077. * Gizmo that enables rotating a mesh along 3 axis
  94078. */
  94079. var RotationGizmo = /** @class */ (function (_super) {
  94080. __extends(RotationGizmo, _super);
  94081. /**
  94082. * Creates a RotationGizmo
  94083. * @param gizmoLayer The utility layer the gizmo will be added to
  94084. */
  94085. function RotationGizmo(gizmoLayer) {
  94086. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94087. var _this = _super.call(this, gizmoLayer) || this;
  94088. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94089. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94090. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94091. _this.attachedMesh = null;
  94092. return _this;
  94093. }
  94094. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  94095. set: function (mesh) {
  94096. if (this.xGizmo) {
  94097. this.xGizmo.attachedMesh = mesh;
  94098. this.yGizmo.attachedMesh = mesh;
  94099. this.zGizmo.attachedMesh = mesh;
  94100. }
  94101. },
  94102. enumerable: true,
  94103. configurable: true
  94104. });
  94105. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94106. get: function () {
  94107. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94108. },
  94109. set: function (value) {
  94110. if (this.xGizmo) {
  94111. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94112. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94113. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94114. }
  94115. },
  94116. enumerable: true,
  94117. configurable: true
  94118. });
  94119. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  94120. get: function () {
  94121. return this.xGizmo.snapDistance;
  94122. },
  94123. /**
  94124. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94125. */
  94126. set: function (value) {
  94127. if (this.xGizmo) {
  94128. this.xGizmo.snapDistance = value;
  94129. this.yGizmo.snapDistance = value;
  94130. this.zGizmo.snapDistance = value;
  94131. }
  94132. },
  94133. enumerable: true,
  94134. configurable: true
  94135. });
  94136. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  94137. get: function () {
  94138. return this.xGizmo.scaleRatio;
  94139. },
  94140. /**
  94141. * Ratio for the scale of the gizmo (Default: 1)
  94142. */
  94143. set: function (value) {
  94144. if (this.xGizmo) {
  94145. this.xGizmo.scaleRatio = value;
  94146. this.yGizmo.scaleRatio = value;
  94147. this.zGizmo.scaleRatio = value;
  94148. }
  94149. },
  94150. enumerable: true,
  94151. configurable: true
  94152. });
  94153. /**
  94154. * Disposes of the gizmo
  94155. */
  94156. RotationGizmo.prototype.dispose = function () {
  94157. this.xGizmo.dispose();
  94158. this.yGizmo.dispose();
  94159. this.zGizmo.dispose();
  94160. };
  94161. /**
  94162. * CustomMeshes are not supported by this gizmo
  94163. * @param mesh The mesh to replace the default mesh of the gizmo
  94164. */
  94165. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  94166. 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)");
  94167. };
  94168. return RotationGizmo;
  94169. }(BABYLON.Gizmo));
  94170. BABYLON.RotationGizmo = RotationGizmo;
  94171. })(BABYLON || (BABYLON = {}));
  94172. //# sourceMappingURL=babylon.rotationGizmo.js.map
  94173. var BABYLON;
  94174. (function (BABYLON) {
  94175. /**
  94176. * Gizmo that enables scaling a mesh along 3 axis
  94177. */
  94178. var ScaleGizmo = /** @class */ (function (_super) {
  94179. __extends(ScaleGizmo, _super);
  94180. /**
  94181. * Creates a ScaleGizmo
  94182. * @param gizmoLayer The utility layer the gizmo will be added to
  94183. */
  94184. function ScaleGizmo(gizmoLayer) {
  94185. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94186. var _this = _super.call(this, gizmoLayer) || this;
  94187. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94188. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94189. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94190. // Create uniform scale gizmo
  94191. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  94192. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94193. _this._uniformGizmo.uniformScaling = true;
  94194. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  94195. octahedron.scaling.scaleInPlace(0.007);
  94196. _this._uniformGizmo.setCustomMesh(octahedron, true);
  94197. _this.attachedMesh = null;
  94198. return _this;
  94199. }
  94200. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  94201. set: function (mesh) {
  94202. if (this.xGizmo) {
  94203. this.xGizmo.attachedMesh = mesh;
  94204. this.yGizmo.attachedMesh = mesh;
  94205. this.zGizmo.attachedMesh = mesh;
  94206. this._uniformGizmo.attachedMesh = mesh;
  94207. }
  94208. },
  94209. enumerable: true,
  94210. configurable: true
  94211. });
  94212. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94213. get: function () {
  94214. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94215. },
  94216. set: function (value) {
  94217. if (this.xGizmo) {
  94218. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94219. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94220. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94221. }
  94222. },
  94223. enumerable: true,
  94224. configurable: true
  94225. });
  94226. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  94227. get: function () {
  94228. return this.xGizmo.snapDistance;
  94229. },
  94230. /**
  94231. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94232. */
  94233. set: function (value) {
  94234. if (this.xGizmo) {
  94235. this.xGizmo.snapDistance = value;
  94236. this.yGizmo.snapDistance = value;
  94237. this.zGizmo.snapDistance = value;
  94238. this._uniformGizmo.snapDistance = value;
  94239. }
  94240. },
  94241. enumerable: true,
  94242. configurable: true
  94243. });
  94244. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  94245. get: function () {
  94246. return this.xGizmo.scaleRatio;
  94247. },
  94248. /**
  94249. * Ratio for the scale of the gizmo (Default: 1)
  94250. */
  94251. set: function (value) {
  94252. if (this.xGizmo) {
  94253. this.xGizmo.scaleRatio = value;
  94254. this.yGizmo.scaleRatio = value;
  94255. this.zGizmo.scaleRatio = value;
  94256. this._uniformGizmo.scaleRatio = value;
  94257. }
  94258. },
  94259. enumerable: true,
  94260. configurable: true
  94261. });
  94262. /**
  94263. * Disposes of the gizmo
  94264. */
  94265. ScaleGizmo.prototype.dispose = function () {
  94266. this.xGizmo.dispose();
  94267. this.yGizmo.dispose();
  94268. this.zGizmo.dispose();
  94269. this._uniformGizmo.dispose();
  94270. };
  94271. return ScaleGizmo;
  94272. }(BABYLON.Gizmo));
  94273. BABYLON.ScaleGizmo = ScaleGizmo;
  94274. })(BABYLON || (BABYLON = {}));
  94275. //# sourceMappingURL=babylon.scaleGizmo.js.map
  94276. var BABYLON;
  94277. (function (BABYLON) {
  94278. /**
  94279. * Bounding box gizmo
  94280. */
  94281. var BoundingBoxGizmo = /** @class */ (function (_super) {
  94282. __extends(BoundingBoxGizmo, _super);
  94283. /**
  94284. * Creates an BoundingBoxGizmo
  94285. * @param gizmoLayer The utility layer the gizmo will be added to
  94286. * @param color The color of the gizmo
  94287. */
  94288. function BoundingBoxGizmo(color, gizmoLayer) {
  94289. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94290. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  94291. var _this = _super.call(this, gizmoLayer) || this;
  94292. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  94293. _this._renderObserver = null;
  94294. _this._pointerObserver = null;
  94295. _this._scaleDragSpeed = 0.2;
  94296. _this._tmpQuaternion = new BABYLON.Quaternion();
  94297. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  94298. _this._tmpRotationMatrix = new BABYLON.Matrix();
  94299. /**
  94300. * 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)
  94301. */
  94302. _this.ignoreChildren = false;
  94303. /**
  94304. * 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)
  94305. */
  94306. _this.includeChildPredicate = null;
  94307. /**
  94308. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  94309. */
  94310. _this.rotationSphereSize = 0.1;
  94311. /**
  94312. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  94313. */
  94314. _this.scaleBoxSize = 0.1;
  94315. /**
  94316. * 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)
  94317. */
  94318. _this.fixedDragMeshScreenSize = false;
  94319. /**
  94320. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  94321. */
  94322. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  94323. /**
  94324. * Fired when a rotation sphere or scale box is dragged
  94325. */
  94326. _this.onDragStartObservable = new BABYLON.Observable();
  94327. /**
  94328. * Fired when a scale box is dragged
  94329. */
  94330. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  94331. /**
  94332. * Fired when a scale box drag is ended
  94333. */
  94334. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  94335. /**
  94336. * Fired when a rotation sphere is dragged
  94337. */
  94338. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  94339. /**
  94340. * Fired when a rotation sphere drag is ended
  94341. */
  94342. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  94343. /**
  94344. * 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)
  94345. */
  94346. _this.scalePivot = null;
  94347. _this._existingMeshScale = new BABYLON.Vector3();
  94348. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  94349. _this._updateScale = false;
  94350. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  94351. // Create Materials
  94352. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94353. coloredMaterial.disableLighting = true;
  94354. coloredMaterial.emissiveColor = color;
  94355. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94356. hoverColoredMaterial.disableLighting = true;
  94357. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94358. // Build bounding box out of lines
  94359. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94360. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  94361. var lines = [];
  94362. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  94363. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  94364. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94365. 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));
  94366. 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));
  94367. 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));
  94368. 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));
  94369. 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));
  94370. 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));
  94371. 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));
  94372. 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));
  94373. 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));
  94374. lines.forEach(function (l) {
  94375. l.color = color;
  94376. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  94377. l.isPickable = false;
  94378. _this._lineBoundingBox.addChild(l);
  94379. });
  94380. _this._rootMesh.addChild(_this._lineBoundingBox);
  94381. // Create rotation spheres
  94382. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94383. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  94384. var _loop_1 = function (i_1) {
  94385. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  94386. sphere.rotationQuaternion = new BABYLON.Quaternion();
  94387. sphere.material = coloredMaterial;
  94388. // Drag behavior
  94389. _dragBehavior = new BABYLON.PointerDragBehavior({});
  94390. _dragBehavior.moveAttached = false;
  94391. _dragBehavior.updateDragPlane = false;
  94392. sphere.addBehavior(_dragBehavior);
  94393. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  94394. var totalTurnAmountOfDrag = 0;
  94395. _dragBehavior.onDragStartObservable.add(function (event) {
  94396. startingTurnDirection.copyFrom(sphere.forward);
  94397. totalTurnAmountOfDrag = 0;
  94398. });
  94399. _dragBehavior.onDragObservable.add(function (event) {
  94400. _this.onRotationSphereDragObservable.notifyObservers({});
  94401. if (_this.attachedMesh) {
  94402. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  94403. var worldDragDirection = startingTurnDirection;
  94404. // Project the world right on to the drag plane
  94405. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  94406. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  94407. // project drag delta on to the resulting drag axis and rotate based on that
  94408. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  94409. // Make rotation relative to size of mesh.
  94410. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  94411. // Rotate based on axis
  94412. if (!_this.attachedMesh.rotationQuaternion) {
  94413. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  94414. }
  94415. if (!_this._anchorMesh.rotationQuaternion) {
  94416. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  94417. }
  94418. // Do not allow the object to turn more than a full circle
  94419. totalTurnAmountOfDrag += projectDist;
  94420. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  94421. if (i_1 >= 8) {
  94422. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  94423. }
  94424. else if (i_1 >= 4) {
  94425. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  94426. }
  94427. else {
  94428. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  94429. }
  94430. // Rotate around center of bounding box
  94431. _this._anchorMesh.addChild(_this.attachedMesh);
  94432. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  94433. _this._anchorMesh.removeChild(_this.attachedMesh);
  94434. }
  94435. _this.updateBoundingBox();
  94436. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  94437. }
  94438. });
  94439. // Selection/deselection
  94440. _dragBehavior.onDragStartObservable.add(function () {
  94441. _this.onDragStartObservable.notifyObservers({});
  94442. _this._selectNode(sphere);
  94443. });
  94444. _dragBehavior.onDragEndObservable.add(function () {
  94445. _this.onRotationSphereDragEndObservable.notifyObservers({});
  94446. _this._selectNode(null);
  94447. });
  94448. this_1._rotateSpheresParent.addChild(sphere);
  94449. };
  94450. var this_1 = this, _dragBehavior;
  94451. for (var i_1 = 0; i_1 < 12; i_1++) {
  94452. _loop_1(i_1);
  94453. }
  94454. _this._rootMesh.addChild(_this._rotateSpheresParent);
  94455. // Create scale cubes
  94456. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94457. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  94458. for (var i = 0; i < 2; i++) {
  94459. for (var j = 0; j < 2; j++) {
  94460. var _loop_2 = function () {
  94461. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  94462. box.material = coloredMaterial;
  94463. // Dragging logic
  94464. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  94465. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  94466. _dragBehavior.moveAttached = false;
  94467. box.addBehavior(_dragBehavior);
  94468. _dragBehavior.onDragObservable.add(function (event) {
  94469. _this.onScaleBoxDragObservable.notifyObservers({});
  94470. if (_this.attachedMesh) {
  94471. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  94472. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  94473. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  94474. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  94475. _this.updateBoundingBox();
  94476. if (_this.scalePivot) {
  94477. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  94478. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  94479. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  94480. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  94481. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  94482. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  94483. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  94484. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  94485. }
  94486. else {
  94487. // Scale from the position of the opposite corner
  94488. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  94489. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  94490. }
  94491. _this._anchorMesh.addChild(_this.attachedMesh);
  94492. _this._anchorMesh.scaling.addInPlace(deltaScale);
  94493. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  94494. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  94495. }
  94496. _this._anchorMesh.removeChild(_this.attachedMesh);
  94497. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  94498. }
  94499. });
  94500. // Selection/deselection
  94501. _dragBehavior.onDragStartObservable.add(function () {
  94502. _this.onDragStartObservable.notifyObservers({});
  94503. _this._selectNode(box);
  94504. });
  94505. _dragBehavior.onDragEndObservable.add(function () {
  94506. _this.onScaleBoxDragEndObservable.notifyObservers({});
  94507. _this._selectNode(null);
  94508. });
  94509. this_2._scaleBoxesParent.addChild(box);
  94510. };
  94511. var this_2 = this, _dragBehavior;
  94512. for (var k = 0; k < 2; k++) {
  94513. _loop_2();
  94514. }
  94515. }
  94516. }
  94517. _this._rootMesh.addChild(_this._scaleBoxesParent);
  94518. // Hover color change
  94519. var pointerIds = new Array();
  94520. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94521. if (!pointerIds[pointerInfo.event.pointerId]) {
  94522. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  94523. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  94524. pointerIds[pointerInfo.event.pointerId] = mesh;
  94525. mesh.material = hoverColoredMaterial;
  94526. }
  94527. });
  94528. }
  94529. else {
  94530. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  94531. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  94532. delete pointerIds[pointerInfo.event.pointerId];
  94533. }
  94534. }
  94535. });
  94536. // Update bounding box positions
  94537. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  94538. // Only update the bouding box if scaling has changed
  94539. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  94540. _this.updateBoundingBox();
  94541. }
  94542. });
  94543. _this.updateBoundingBox();
  94544. return _this;
  94545. }
  94546. /** @hidden */
  94547. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  94548. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  94549. // Save old pivot and set pivot to 0,0,0
  94550. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  94551. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  94552. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  94553. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  94554. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  94555. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  94556. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  94557. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  94558. }
  94559. }
  94560. BoundingBoxGizmo._PivotCached++;
  94561. };
  94562. /** @hidden */
  94563. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  94564. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  94565. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  94566. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  94567. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  94568. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  94569. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  94570. }
  94571. this._PivotCached--;
  94572. };
  94573. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  94574. if (value) {
  94575. // Reset anchor mesh to match attached mesh's scale
  94576. // This is needed to avoid invalid box/sphere position on first drag
  94577. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  94578. this._anchorMesh.addChild(value);
  94579. this._anchorMesh.removeChild(value);
  94580. BoundingBoxGizmo._RestorePivotPoint(value);
  94581. this.updateBoundingBox();
  94582. }
  94583. };
  94584. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  94585. this._rotateSpheresParent.getChildMeshes()
  94586. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  94587. m.isVisible = (!selectedMesh || m == selectedMesh);
  94588. });
  94589. };
  94590. /**
  94591. * Updates the bounding box information for the Gizmo
  94592. */
  94593. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  94594. if (this.attachedMesh) {
  94595. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  94596. this._update();
  94597. // Rotate based on axis
  94598. if (!this.attachedMesh.rotationQuaternion) {
  94599. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  94600. }
  94601. if (!this._anchorMesh.rotationQuaternion) {
  94602. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  94603. }
  94604. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  94605. // Store original position and reset mesh to origin before computing the bounding box
  94606. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  94607. this._tmpVector.copyFrom(this.attachedMesh.position);
  94608. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  94609. this.attachedMesh.position.set(0, 0, 0);
  94610. // Update bounding dimensions/positions
  94611. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  94612. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  94613. // Update gizmo to match bounding box scaling and rotation
  94614. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  94615. 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);
  94616. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  94617. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  94618. this._lineBoundingBox.computeWorldMatrix();
  94619. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  94620. // restore position/rotation values
  94621. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  94622. this.attachedMesh.position.copyFrom(this._tmpVector);
  94623. }
  94624. // Update rotation sphere locations
  94625. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  94626. for (var i = 0; i < 3; i++) {
  94627. for (var j = 0; j < 2; j++) {
  94628. for (var k = 0; k < 2; k++) {
  94629. var index = ((i * 4) + (j * 2)) + k;
  94630. if (i == 0) {
  94631. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  94632. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94633. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  94634. }
  94635. if (i == 1) {
  94636. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  94637. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94638. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  94639. }
  94640. if (i == 2) {
  94641. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  94642. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94643. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  94644. }
  94645. if (this.fixedDragMeshScreenSize) {
  94646. this._rootMesh.computeWorldMatrix();
  94647. this._rotateSpheresParent.computeWorldMatrix();
  94648. rotateSpheres[index].computeWorldMatrix();
  94649. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  94650. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  94651. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  94652. }
  94653. else {
  94654. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  94655. }
  94656. }
  94657. }
  94658. }
  94659. // Update scale box locations
  94660. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  94661. for (var i = 0; i < 2; i++) {
  94662. for (var j = 0; j < 2; j++) {
  94663. for (var k = 0; k < 2; k++) {
  94664. var index = ((i * 4) + (j * 2)) + k;
  94665. if (scaleBoxes[index]) {
  94666. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  94667. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94668. if (this.fixedDragMeshScreenSize) {
  94669. this._rootMesh.computeWorldMatrix();
  94670. this._scaleBoxesParent.computeWorldMatrix();
  94671. scaleBoxes[index].computeWorldMatrix();
  94672. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  94673. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  94674. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  94675. }
  94676. else {
  94677. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  94678. }
  94679. }
  94680. }
  94681. }
  94682. }
  94683. if (this.attachedMesh) {
  94684. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  94685. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  94686. }
  94687. };
  94688. /**
  94689. * Enables rotation on the specified axis and disables rotation on the others
  94690. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  94691. */
  94692. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  94693. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  94694. if (i < 4) {
  94695. m.setEnabled(axis.indexOf("x") != -1);
  94696. }
  94697. else if (i < 8) {
  94698. m.setEnabled(axis.indexOf("y") != -1);
  94699. }
  94700. else {
  94701. m.setEnabled(axis.indexOf("z") != -1);
  94702. }
  94703. });
  94704. };
  94705. /**
  94706. * Disposes of the gizmo
  94707. */
  94708. BoundingBoxGizmo.prototype.dispose = function () {
  94709. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94710. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  94711. this._lineBoundingBox.dispose();
  94712. this._rotateSpheresParent.dispose();
  94713. this._scaleBoxesParent.dispose();
  94714. _super.prototype.dispose.call(this);
  94715. };
  94716. /**
  94717. * 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)
  94718. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  94719. * @returns the bounding box mesh with the passed in mesh as a child
  94720. */
  94721. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  94722. var makeNotPickable = function (root) {
  94723. root.isPickable = false;
  94724. root.getChildMeshes().forEach(function (c) {
  94725. makeNotPickable(c);
  94726. });
  94727. };
  94728. makeNotPickable(mesh);
  94729. // Reset position to get boudning box from origin with no rotation
  94730. if (!mesh.rotationQuaternion) {
  94731. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  94732. }
  94733. var oldPos = mesh.position.clone();
  94734. var oldRot = mesh.rotationQuaternion.clone();
  94735. mesh.rotationQuaternion.set(0, 0, 0, 1);
  94736. mesh.position.set(0, 0, 0);
  94737. // Update bounding dimensions/positions
  94738. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  94739. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  94740. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  94741. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  94742. // Restore original positions
  94743. mesh.addChild(box);
  94744. mesh.rotationQuaternion.copyFrom(oldRot);
  94745. mesh.position.copyFrom(oldPos);
  94746. // Reverse parenting
  94747. mesh.removeChild(box);
  94748. box.addChild(mesh);
  94749. box.visibility = 0;
  94750. return box;
  94751. };
  94752. /**
  94753. * CustomMeshes are not supported by this gizmo
  94754. * @param mesh The mesh to replace the default mesh of the gizmo
  94755. */
  94756. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  94757. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  94758. };
  94759. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  94760. // store/remove pivot point should only be applied during their outermost calls
  94761. BoundingBoxGizmo._PivotCached = 0;
  94762. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  94763. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  94764. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  94765. return BoundingBoxGizmo;
  94766. }(BABYLON.Gizmo));
  94767. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  94768. })(BABYLON || (BABYLON = {}));
  94769. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  94770. var BABYLON;
  94771. (function (BABYLON) {
  94772. /**
  94773. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  94774. */
  94775. var GizmoManager = /** @class */ (function () {
  94776. /**
  94777. * Instatiates a gizmo manager
  94778. * @param scene the scene to overlay the gizmos on top of
  94779. */
  94780. function GizmoManager(scene) {
  94781. var _this = this;
  94782. this.scene = scene;
  94783. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  94784. this._pointerObserver = null;
  94785. this._attachedMesh = null;
  94786. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  94787. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  94788. /**
  94789. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  94790. */
  94791. this.attachableMeshes = null;
  94792. /**
  94793. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  94794. */
  94795. this.usePointerToAttachGizmos = true;
  94796. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  94797. // Instatiate/dispose gizmos based on pointer actions
  94798. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  94799. if (!_this.usePointerToAttachGizmos) {
  94800. return;
  94801. }
  94802. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  94803. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  94804. var node = pointerInfo.pickInfo.pickedMesh;
  94805. if (_this.attachableMeshes == null) {
  94806. // Attach to the most parent node
  94807. while (node && node.parent != null) {
  94808. node = node.parent;
  94809. }
  94810. }
  94811. else {
  94812. // Attach to the parent node that is an attachableMesh
  94813. var found = false;
  94814. _this.attachableMeshes.forEach(function (mesh) {
  94815. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  94816. node = mesh;
  94817. found = true;
  94818. }
  94819. });
  94820. if (!found) {
  94821. node = null;
  94822. }
  94823. }
  94824. if (node instanceof BABYLON.AbstractMesh) {
  94825. _this.attachToMesh(node);
  94826. }
  94827. else {
  94828. _this.attachToMesh(null);
  94829. }
  94830. }
  94831. else {
  94832. _this.attachToMesh(null);
  94833. }
  94834. }
  94835. });
  94836. }
  94837. /**
  94838. * Attaches a set of gizmos to the specified mesh
  94839. * @param mesh The mesh the gizmo's should be attached to
  94840. */
  94841. GizmoManager.prototype.attachToMesh = function (mesh) {
  94842. if (this._attachedMesh) {
  94843. this._attachedMesh.removeBehavior(this._dragBehavior);
  94844. }
  94845. this._attachedMesh = mesh;
  94846. for (var key in this.gizmos) {
  94847. var gizmo = (this.gizmos[key]);
  94848. if (gizmo && this._gizmosEnabled[key]) {
  94849. gizmo.attachedMesh = mesh;
  94850. }
  94851. }
  94852. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  94853. this._attachedMesh.addBehavior(this._dragBehavior);
  94854. }
  94855. };
  94856. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  94857. get: function () {
  94858. return this._gizmosEnabled.positionGizmo;
  94859. },
  94860. /**
  94861. * If the position gizmo is enabled
  94862. */
  94863. set: function (value) {
  94864. if (value) {
  94865. if (!this.gizmos.positionGizmo) {
  94866. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  94867. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94868. }
  94869. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  94870. }
  94871. else if (this.gizmos.positionGizmo) {
  94872. this.gizmos.positionGizmo.attachedMesh = null;
  94873. }
  94874. this._gizmosEnabled.positionGizmo = value;
  94875. },
  94876. enumerable: true,
  94877. configurable: true
  94878. });
  94879. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  94880. get: function () {
  94881. return this._gizmosEnabled.rotationGizmo;
  94882. },
  94883. /**
  94884. * If the rotation gizmo is enabled
  94885. */
  94886. set: function (value) {
  94887. if (value) {
  94888. if (!this.gizmos.rotationGizmo) {
  94889. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  94890. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94891. }
  94892. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  94893. }
  94894. else if (this.gizmos.rotationGizmo) {
  94895. this.gizmos.rotationGizmo.attachedMesh = null;
  94896. }
  94897. this._gizmosEnabled.rotationGizmo = value;
  94898. },
  94899. enumerable: true,
  94900. configurable: true
  94901. });
  94902. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  94903. get: function () {
  94904. return this._gizmosEnabled.scaleGizmo;
  94905. },
  94906. /**
  94907. * If the scale gizmo is enabled
  94908. */
  94909. set: function (value) {
  94910. if (value) {
  94911. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  94912. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  94913. }
  94914. else if (this.gizmos.scaleGizmo) {
  94915. this.gizmos.scaleGizmo.attachedMesh = null;
  94916. }
  94917. this._gizmosEnabled.scaleGizmo = value;
  94918. },
  94919. enumerable: true,
  94920. configurable: true
  94921. });
  94922. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  94923. get: function () {
  94924. return this._gizmosEnabled.boundingBoxGizmo;
  94925. },
  94926. /**
  94927. * If the boundingBox gizmo is enabled
  94928. */
  94929. set: function (value) {
  94930. if (value) {
  94931. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  94932. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  94933. if (this._attachedMesh) {
  94934. this._attachedMesh.removeBehavior(this._dragBehavior);
  94935. this._attachedMesh.addBehavior(this._dragBehavior);
  94936. }
  94937. }
  94938. else if (this.gizmos.boundingBoxGizmo) {
  94939. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  94940. }
  94941. this._gizmosEnabled.boundingBoxGizmo = value;
  94942. },
  94943. enumerable: true,
  94944. configurable: true
  94945. });
  94946. /**
  94947. * Disposes of the gizmo manager
  94948. */
  94949. GizmoManager.prototype.dispose = function () {
  94950. this.scene.onPointerObservable.remove(this._pointerObserver);
  94951. for (var key in this.gizmos) {
  94952. var gizmo = (this.gizmos[key]);
  94953. if (gizmo) {
  94954. gizmo.dispose();
  94955. }
  94956. }
  94957. this._dragBehavior.detach();
  94958. };
  94959. return GizmoManager;
  94960. }());
  94961. BABYLON.GizmoManager = GizmoManager;
  94962. })(BABYLON || (BABYLON = {}));
  94963. //# sourceMappingURL=babylon.gizmoManager.js.map
  94964. var BABYLON;
  94965. (function (BABYLON) {
  94966. /**
  94967. * Defines a target to use with MorphTargetManager
  94968. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  94969. */
  94970. var MorphTarget = /** @class */ (function () {
  94971. /**
  94972. * Creates a new MorphTarget
  94973. * @param name defines the name of the target
  94974. * @param influence defines the influence to use
  94975. */
  94976. function MorphTarget(
  94977. /** defines the name of the target */
  94978. name, influence, scene) {
  94979. if (influence === void 0) { influence = 0; }
  94980. if (scene === void 0) { scene = null; }
  94981. this.name = name;
  94982. /**
  94983. * Gets or sets the list of animations
  94984. */
  94985. this.animations = new Array();
  94986. this._positions = null;
  94987. this._normals = null;
  94988. this._tangents = null;
  94989. /**
  94990. * Observable raised when the influence changes
  94991. */
  94992. this.onInfluenceChanged = new BABYLON.Observable();
  94993. this._animationPropertiesOverride = null;
  94994. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94995. this.influence = influence;
  94996. }
  94997. Object.defineProperty(MorphTarget.prototype, "influence", {
  94998. /**
  94999. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  95000. */
  95001. get: function () {
  95002. return this._influence;
  95003. },
  95004. set: function (influence) {
  95005. if (this._influence === influence) {
  95006. return;
  95007. }
  95008. var previous = this._influence;
  95009. this._influence = influence;
  95010. if (this.onInfluenceChanged.hasObservers) {
  95011. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  95012. }
  95013. },
  95014. enumerable: true,
  95015. configurable: true
  95016. });
  95017. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  95018. /**
  95019. * Gets or sets the animation properties override
  95020. */
  95021. get: function () {
  95022. if (!this._animationPropertiesOverride && this._scene) {
  95023. return this._scene.animationPropertiesOverride;
  95024. }
  95025. return this._animationPropertiesOverride;
  95026. },
  95027. set: function (value) {
  95028. this._animationPropertiesOverride = value;
  95029. },
  95030. enumerable: true,
  95031. configurable: true
  95032. });
  95033. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  95034. /**
  95035. * Gets a boolean defining if the target contains position data
  95036. */
  95037. get: function () {
  95038. return !!this._positions;
  95039. },
  95040. enumerable: true,
  95041. configurable: true
  95042. });
  95043. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  95044. /**
  95045. * Gets a boolean defining if the target contains normal data
  95046. */
  95047. get: function () {
  95048. return !!this._normals;
  95049. },
  95050. enumerable: true,
  95051. configurable: true
  95052. });
  95053. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  95054. /**
  95055. * Gets a boolean defining if the target contains tangent data
  95056. */
  95057. get: function () {
  95058. return !!this._tangents;
  95059. },
  95060. enumerable: true,
  95061. configurable: true
  95062. });
  95063. /**
  95064. * Affects position data to this target
  95065. * @param data defines the position data to use
  95066. */
  95067. MorphTarget.prototype.setPositions = function (data) {
  95068. this._positions = data;
  95069. };
  95070. /**
  95071. * Gets the position data stored in this target
  95072. * @returns a FloatArray containing the position data (or null if not present)
  95073. */
  95074. MorphTarget.prototype.getPositions = function () {
  95075. return this._positions;
  95076. };
  95077. /**
  95078. * Affects normal data to this target
  95079. * @param data defines the normal data to use
  95080. */
  95081. MorphTarget.prototype.setNormals = function (data) {
  95082. this._normals = data;
  95083. };
  95084. /**
  95085. * Gets the normal data stored in this target
  95086. * @returns a FloatArray containing the normal data (or null if not present)
  95087. */
  95088. MorphTarget.prototype.getNormals = function () {
  95089. return this._normals;
  95090. };
  95091. /**
  95092. * Affects tangent data to this target
  95093. * @param data defines the tangent data to use
  95094. */
  95095. MorphTarget.prototype.setTangents = function (data) {
  95096. this._tangents = data;
  95097. };
  95098. /**
  95099. * Gets the tangent data stored in this target
  95100. * @returns a FloatArray containing the tangent data (or null if not present)
  95101. */
  95102. MorphTarget.prototype.getTangents = function () {
  95103. return this._tangents;
  95104. };
  95105. /**
  95106. * Serializes the current target into a Serialization object
  95107. * @returns the serialized object
  95108. */
  95109. MorphTarget.prototype.serialize = function () {
  95110. var serializationObject = {};
  95111. serializationObject.name = this.name;
  95112. serializationObject.influence = this.influence;
  95113. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  95114. if (this.hasNormals) {
  95115. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  95116. }
  95117. if (this.hasTangents) {
  95118. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  95119. }
  95120. // Animations
  95121. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  95122. return serializationObject;
  95123. };
  95124. // Statics
  95125. /**
  95126. * Creates a new target from serialized data
  95127. * @param serializationObject defines the serialized data to use
  95128. * @returns a new MorphTarget
  95129. */
  95130. MorphTarget.Parse = function (serializationObject) {
  95131. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  95132. result.setPositions(serializationObject.positions);
  95133. if (serializationObject.normals) {
  95134. result.setNormals(serializationObject.normals);
  95135. }
  95136. if (serializationObject.tangents) {
  95137. result.setTangents(serializationObject.tangents);
  95138. }
  95139. // Animations
  95140. if (serializationObject.animations) {
  95141. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  95142. var parsedAnimation = serializationObject.animations[animationIndex];
  95143. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  95144. }
  95145. }
  95146. return result;
  95147. };
  95148. /**
  95149. * Creates a MorphTarget from mesh data
  95150. * @param mesh defines the source mesh
  95151. * @param name defines the name to use for the new target
  95152. * @param influence defines the influence to attach to the target
  95153. * @returns a new MorphTarget
  95154. */
  95155. MorphTarget.FromMesh = function (mesh, name, influence) {
  95156. if (!name) {
  95157. name = mesh.name;
  95158. }
  95159. var result = new MorphTarget(name, influence, mesh.getScene());
  95160. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  95161. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  95162. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  95163. }
  95164. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  95165. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  95166. }
  95167. return result;
  95168. };
  95169. return MorphTarget;
  95170. }());
  95171. BABYLON.MorphTarget = MorphTarget;
  95172. })(BABYLON || (BABYLON = {}));
  95173. //# sourceMappingURL=babylon.morphTarget.js.map
  95174. var BABYLON;
  95175. (function (BABYLON) {
  95176. /**
  95177. * This class is used to deform meshes using morphing between different targets
  95178. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  95179. */
  95180. var MorphTargetManager = /** @class */ (function () {
  95181. /**
  95182. * Creates a new MorphTargetManager
  95183. * @param scene defines the current scene
  95184. */
  95185. function MorphTargetManager(scene) {
  95186. if (scene === void 0) { scene = null; }
  95187. this._targets = new Array();
  95188. this._targetObservable = new Array();
  95189. this._activeTargets = new BABYLON.SmartArray(16);
  95190. this._supportsNormals = false;
  95191. this._supportsTangents = false;
  95192. this._vertexCount = 0;
  95193. this._uniqueId = 0;
  95194. this._tempInfluences = new Array();
  95195. if (!scene) {
  95196. scene = BABYLON.Engine.LastCreatedScene;
  95197. }
  95198. this._scene = scene;
  95199. if (this._scene) {
  95200. this._scene.morphTargetManagers.push(this);
  95201. this._uniqueId = this._scene.getUniqueId();
  95202. }
  95203. }
  95204. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  95205. /**
  95206. * Gets the unique ID of this manager
  95207. */
  95208. get: function () {
  95209. return this._uniqueId;
  95210. },
  95211. enumerable: true,
  95212. configurable: true
  95213. });
  95214. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  95215. /**
  95216. * Gets the number of vertices handled by this manager
  95217. */
  95218. get: function () {
  95219. return this._vertexCount;
  95220. },
  95221. enumerable: true,
  95222. configurable: true
  95223. });
  95224. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  95225. /**
  95226. * Gets a boolean indicating if this manager supports morphing of normals
  95227. */
  95228. get: function () {
  95229. return this._supportsNormals;
  95230. },
  95231. enumerable: true,
  95232. configurable: true
  95233. });
  95234. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  95235. /**
  95236. * Gets a boolean indicating if this manager supports morphing of tangents
  95237. */
  95238. get: function () {
  95239. return this._supportsTangents;
  95240. },
  95241. enumerable: true,
  95242. configurable: true
  95243. });
  95244. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  95245. /**
  95246. * Gets the number of targets stored in this manager
  95247. */
  95248. get: function () {
  95249. return this._targets.length;
  95250. },
  95251. enumerable: true,
  95252. configurable: true
  95253. });
  95254. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  95255. /**
  95256. * Gets the number of influencers (ie. the number of targets with influences > 0)
  95257. */
  95258. get: function () {
  95259. return this._activeTargets.length;
  95260. },
  95261. enumerable: true,
  95262. configurable: true
  95263. });
  95264. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  95265. /**
  95266. * Gets the list of influences (one per target)
  95267. */
  95268. get: function () {
  95269. return this._influences;
  95270. },
  95271. enumerable: true,
  95272. configurable: true
  95273. });
  95274. /**
  95275. * Gets the active target at specified index. An active target is a target with an influence > 0
  95276. * @param index defines the index to check
  95277. * @returns the requested target
  95278. */
  95279. MorphTargetManager.prototype.getActiveTarget = function (index) {
  95280. return this._activeTargets.data[index];
  95281. };
  95282. /**
  95283. * Gets the target at specified index
  95284. * @param index defines the index to check
  95285. * @returns the requested target
  95286. */
  95287. MorphTargetManager.prototype.getTarget = function (index) {
  95288. return this._targets[index];
  95289. };
  95290. /**
  95291. * Add a new target to this manager
  95292. * @param target defines the target to add
  95293. */
  95294. MorphTargetManager.prototype.addTarget = function (target) {
  95295. var _this = this;
  95296. this._targets.push(target);
  95297. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  95298. _this._syncActiveTargets(needUpdate);
  95299. }));
  95300. this._syncActiveTargets(true);
  95301. };
  95302. /**
  95303. * Removes a target from the manager
  95304. * @param target defines the target to remove
  95305. */
  95306. MorphTargetManager.prototype.removeTarget = function (target) {
  95307. var index = this._targets.indexOf(target);
  95308. if (index >= 0) {
  95309. this._targets.splice(index, 1);
  95310. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  95311. this._syncActiveTargets(true);
  95312. }
  95313. };
  95314. /**
  95315. * Serializes the current manager into a Serialization object
  95316. * @returns the serialized object
  95317. */
  95318. MorphTargetManager.prototype.serialize = function () {
  95319. var serializationObject = {};
  95320. serializationObject.id = this.uniqueId;
  95321. serializationObject.targets = [];
  95322. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  95323. var target = _a[_i];
  95324. serializationObject.targets.push(target.serialize());
  95325. }
  95326. return serializationObject;
  95327. };
  95328. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  95329. var influenceCount = 0;
  95330. this._activeTargets.reset();
  95331. this._supportsNormals = true;
  95332. this._supportsTangents = true;
  95333. this._vertexCount = 0;
  95334. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  95335. var target = _a[_i];
  95336. this._activeTargets.push(target);
  95337. this._tempInfluences[influenceCount++] = target.influence;
  95338. var positions = target.getPositions();
  95339. if (positions) {
  95340. this._supportsNormals = this._supportsNormals && target.hasNormals;
  95341. this._supportsTangents = this._supportsTangents && target.hasTangents;
  95342. var vertexCount = positions.length / 3;
  95343. if (this._vertexCount === 0) {
  95344. this._vertexCount = vertexCount;
  95345. }
  95346. else if (this._vertexCount !== vertexCount) {
  95347. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  95348. return;
  95349. }
  95350. }
  95351. }
  95352. if (!this._influences || this._influences.length !== influenceCount) {
  95353. this._influences = new Float32Array(influenceCount);
  95354. }
  95355. for (var index = 0; index < influenceCount; index++) {
  95356. this._influences[index] = this._tempInfluences[index];
  95357. }
  95358. if (needUpdate) {
  95359. this.synchronize();
  95360. }
  95361. };
  95362. /**
  95363. * Syncrhonize the targets with all the meshes using this morph target manager
  95364. */
  95365. MorphTargetManager.prototype.synchronize = function () {
  95366. if (!this._scene) {
  95367. return;
  95368. }
  95369. // Flag meshes as dirty to resync with the active targets
  95370. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  95371. var mesh = _a[_i];
  95372. if (mesh.morphTargetManager === this) {
  95373. mesh._syncGeometryWithMorphTargetManager();
  95374. }
  95375. }
  95376. };
  95377. // Statics
  95378. /**
  95379. * Creates a new MorphTargetManager from serialized data
  95380. * @param serializationObject defines the serialized data
  95381. * @param scene defines the hosting scene
  95382. * @returns the new MorphTargetManager
  95383. */
  95384. MorphTargetManager.Parse = function (serializationObject, scene) {
  95385. var result = new MorphTargetManager(scene);
  95386. result._uniqueId = serializationObject.id;
  95387. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  95388. var targetData = _a[_i];
  95389. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  95390. }
  95391. return result;
  95392. };
  95393. return MorphTargetManager;
  95394. }());
  95395. BABYLON.MorphTargetManager = MorphTargetManager;
  95396. })(BABYLON || (BABYLON = {}));
  95397. //# sourceMappingURL=babylon.morphTargetManager.js.map
  95398. var BABYLON;
  95399. (function (BABYLON) {
  95400. var Octree = /** @class */ (function () {
  95401. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  95402. if (maxDepth === void 0) { maxDepth = 2; }
  95403. this.maxDepth = maxDepth;
  95404. this.dynamicContent = new Array();
  95405. this._maxBlockCapacity = maxBlockCapacity || 64;
  95406. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  95407. this._creationFunc = creationFunc;
  95408. }
  95409. // Methods
  95410. Octree.prototype.update = function (worldMin, worldMax, entries) {
  95411. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  95412. };
  95413. Octree.prototype.addMesh = function (entry) {
  95414. for (var index = 0; index < this.blocks.length; index++) {
  95415. var block = this.blocks[index];
  95416. block.addEntry(entry);
  95417. }
  95418. };
  95419. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  95420. this._selectionContent.reset();
  95421. for (var index = 0; index < this.blocks.length; index++) {
  95422. var block = this.blocks[index];
  95423. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  95424. }
  95425. if (allowDuplicate) {
  95426. this._selectionContent.concat(this.dynamicContent);
  95427. }
  95428. else {
  95429. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95430. }
  95431. return this._selectionContent;
  95432. };
  95433. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  95434. this._selectionContent.reset();
  95435. for (var index = 0; index < this.blocks.length; index++) {
  95436. var block = this.blocks[index];
  95437. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  95438. }
  95439. if (allowDuplicate) {
  95440. this._selectionContent.concat(this.dynamicContent);
  95441. }
  95442. else {
  95443. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95444. }
  95445. return this._selectionContent;
  95446. };
  95447. Octree.prototype.intersectsRay = function (ray) {
  95448. this._selectionContent.reset();
  95449. for (var index = 0; index < this.blocks.length; index++) {
  95450. var block = this.blocks[index];
  95451. block.intersectsRay(ray, this._selectionContent);
  95452. }
  95453. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95454. return this._selectionContent;
  95455. };
  95456. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  95457. target.blocks = new Array();
  95458. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  95459. // Segmenting space
  95460. for (var x = 0; x < 2; x++) {
  95461. for (var y = 0; y < 2; y++) {
  95462. for (var z = 0; z < 2; z++) {
  95463. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  95464. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  95465. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  95466. block.addEntries(entries);
  95467. target.blocks.push(block);
  95468. }
  95469. }
  95470. }
  95471. };
  95472. Octree.CreationFuncForMeshes = function (entry, block) {
  95473. var boundingInfo = entry.getBoundingInfo();
  95474. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  95475. block.entries.push(entry);
  95476. }
  95477. };
  95478. Octree.CreationFuncForSubMeshes = function (entry, block) {
  95479. var boundingInfo = entry.getBoundingInfo();
  95480. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  95481. block.entries.push(entry);
  95482. }
  95483. };
  95484. return Octree;
  95485. }());
  95486. BABYLON.Octree = Octree;
  95487. })(BABYLON || (BABYLON = {}));
  95488. //# sourceMappingURL=babylon.octree.js.map
  95489. var BABYLON;
  95490. (function (BABYLON) {
  95491. var OctreeBlock = /** @class */ (function () {
  95492. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  95493. this.entries = new Array();
  95494. this._boundingVectors = new Array();
  95495. this._capacity = capacity;
  95496. this._depth = depth;
  95497. this._maxDepth = maxDepth;
  95498. this._creationFunc = creationFunc;
  95499. this._minPoint = minPoint;
  95500. this._maxPoint = maxPoint;
  95501. this._boundingVectors.push(minPoint.clone());
  95502. this._boundingVectors.push(maxPoint.clone());
  95503. this._boundingVectors.push(minPoint.clone());
  95504. this._boundingVectors[2].x = maxPoint.x;
  95505. this._boundingVectors.push(minPoint.clone());
  95506. this._boundingVectors[3].y = maxPoint.y;
  95507. this._boundingVectors.push(minPoint.clone());
  95508. this._boundingVectors[4].z = maxPoint.z;
  95509. this._boundingVectors.push(maxPoint.clone());
  95510. this._boundingVectors[5].z = minPoint.z;
  95511. this._boundingVectors.push(maxPoint.clone());
  95512. this._boundingVectors[6].x = minPoint.x;
  95513. this._boundingVectors.push(maxPoint.clone());
  95514. this._boundingVectors[7].y = minPoint.y;
  95515. }
  95516. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  95517. // Property
  95518. get: function () {
  95519. return this._capacity;
  95520. },
  95521. enumerable: true,
  95522. configurable: true
  95523. });
  95524. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  95525. get: function () {
  95526. return this._minPoint;
  95527. },
  95528. enumerable: true,
  95529. configurable: true
  95530. });
  95531. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  95532. get: function () {
  95533. return this._maxPoint;
  95534. },
  95535. enumerable: true,
  95536. configurable: true
  95537. });
  95538. // Methods
  95539. OctreeBlock.prototype.addEntry = function (entry) {
  95540. if (this.blocks) {
  95541. for (var index = 0; index < this.blocks.length; index++) {
  95542. var block = this.blocks[index];
  95543. block.addEntry(entry);
  95544. }
  95545. return;
  95546. }
  95547. this._creationFunc(entry, this);
  95548. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  95549. this.createInnerBlocks();
  95550. }
  95551. };
  95552. OctreeBlock.prototype.addEntries = function (entries) {
  95553. for (var index = 0; index < entries.length; index++) {
  95554. var mesh = entries[index];
  95555. this.addEntry(mesh);
  95556. }
  95557. };
  95558. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  95559. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  95560. if (this.blocks) {
  95561. for (var index = 0; index < this.blocks.length; index++) {
  95562. var block = this.blocks[index];
  95563. block.select(frustumPlanes, selection, allowDuplicate);
  95564. }
  95565. return;
  95566. }
  95567. if (allowDuplicate) {
  95568. selection.concat(this.entries);
  95569. }
  95570. else {
  95571. selection.concatWithNoDuplicate(this.entries);
  95572. }
  95573. }
  95574. };
  95575. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  95576. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  95577. if (this.blocks) {
  95578. for (var index = 0; index < this.blocks.length; index++) {
  95579. var block = this.blocks[index];
  95580. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  95581. }
  95582. return;
  95583. }
  95584. if (allowDuplicate) {
  95585. selection.concat(this.entries);
  95586. }
  95587. else {
  95588. selection.concatWithNoDuplicate(this.entries);
  95589. }
  95590. }
  95591. };
  95592. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  95593. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  95594. if (this.blocks) {
  95595. for (var index = 0; index < this.blocks.length; index++) {
  95596. var block = this.blocks[index];
  95597. block.intersectsRay(ray, selection);
  95598. }
  95599. return;
  95600. }
  95601. selection.concatWithNoDuplicate(this.entries);
  95602. }
  95603. };
  95604. OctreeBlock.prototype.createInnerBlocks = function () {
  95605. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  95606. };
  95607. return OctreeBlock;
  95608. }());
  95609. BABYLON.OctreeBlock = OctreeBlock;
  95610. })(BABYLON || (BABYLON = {}));
  95611. //# sourceMappingURL=babylon.octreeBlock.js.map
  95612. var BABYLON;
  95613. (function (BABYLON) {
  95614. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  95615. if (maxCapacity === void 0) { maxCapacity = 64; }
  95616. if (maxDepth === void 0) { maxDepth = 2; }
  95617. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  95618. if (!component) {
  95619. component = new OctreeSceneComponent(this);
  95620. this._addComponent(component);
  95621. }
  95622. if (!this._selectionOctree) {
  95623. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  95624. }
  95625. var worldExtends = this.getWorldExtends();
  95626. // Update octree
  95627. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  95628. return this._selectionOctree;
  95629. };
  95630. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  95631. get: function () {
  95632. return this._selectionOctree;
  95633. },
  95634. enumerable: true,
  95635. configurable: true
  95636. });
  95637. /**
  95638. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  95639. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  95640. * @param maxCapacity defines the maximum size of each block (64 by default)
  95641. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  95642. * @returns the new octree
  95643. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  95644. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  95645. */
  95646. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  95647. if (maxCapacity === void 0) { maxCapacity = 64; }
  95648. if (maxDepth === void 0) { maxDepth = 2; }
  95649. var scene = this.getScene();
  95650. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  95651. if (!component) {
  95652. component = new OctreeSceneComponent(scene);
  95653. scene._addComponent(component);
  95654. }
  95655. if (!this._submeshesOctree) {
  95656. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  95657. }
  95658. this.computeWorldMatrix(true);
  95659. var boundingInfo = this.getBoundingInfo();
  95660. // Update octree
  95661. var bbox = boundingInfo.boundingBox;
  95662. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  95663. return this._submeshesOctree;
  95664. };
  95665. /**
  95666. * Defines the octree scene component responsible to manage any octrees
  95667. * in a given scene.
  95668. */
  95669. var OctreeSceneComponent = /** @class */ (function () {
  95670. /**
  95671. * Creates a new instance of the component for the given scene
  95672. * @param scene Defines the scene to register the component in
  95673. */
  95674. function OctreeSceneComponent(scene) {
  95675. /**
  95676. * The component name helpfull to identify the component in the list of scene components.
  95677. */
  95678. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  95679. /**
  95680. * Indicates if the meshes have been checked to make sure they are isEnabled()
  95681. */
  95682. this.checksIsEnabled = true;
  95683. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  95684. this.scene = scene;
  95685. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  95686. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  95687. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  95688. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  95689. }
  95690. /**
  95691. * Registers the component in a given scene
  95692. */
  95693. OctreeSceneComponent.prototype.register = function () {
  95694. var _this = this;
  95695. this.scene.onMeshRemovedObservable.add(function (mesh) {
  95696. var sceneOctree = _this.scene.selectionOctree;
  95697. if (sceneOctree !== undefined && sceneOctree !== null) {
  95698. var index = sceneOctree.dynamicContent.indexOf(mesh);
  95699. if (index !== -1) {
  95700. sceneOctree.dynamicContent.splice(index, 1);
  95701. }
  95702. }
  95703. });
  95704. this.scene.onMeshImportedObservable.add(function (mesh) {
  95705. var sceneOctree = _this.scene.selectionOctree;
  95706. if (sceneOctree !== undefined && sceneOctree !== null) {
  95707. sceneOctree.addMesh(mesh);
  95708. }
  95709. });
  95710. };
  95711. /**
  95712. * Return the list of active meshes
  95713. * @returns the list of active meshes
  95714. */
  95715. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  95716. if (this.scene._selectionOctree) {
  95717. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  95718. return selection;
  95719. }
  95720. return this.scene._getDefaultMeshCandidates();
  95721. };
  95722. /**
  95723. * Return the list of active sub meshes
  95724. * @param mesh The mesh to get the candidates sub meshes from
  95725. * @returns the list of active sub meshes
  95726. */
  95727. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  95728. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  95729. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  95730. return intersections;
  95731. }
  95732. return this.scene._getDefaultSubMeshCandidates(mesh);
  95733. };
  95734. /**
  95735. * Return the list of sub meshes intersecting with a given local ray
  95736. * @param mesh defines the mesh to find the submesh for
  95737. * @param localRay defines the ray in local space
  95738. * @returns the list of intersecting sub meshes
  95739. */
  95740. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  95741. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  95742. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  95743. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  95744. return intersections;
  95745. }
  95746. return this.scene._getDefaultSubMeshCandidates(mesh);
  95747. };
  95748. /**
  95749. * Return the list of sub meshes colliding with a collider
  95750. * @param mesh defines the mesh to find the submesh for
  95751. * @param collider defines the collider to evaluate the collision against
  95752. * @returns the list of colliding sub meshes
  95753. */
  95754. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  95755. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  95756. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  95757. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  95758. return intersections;
  95759. }
  95760. return this.scene._getDefaultSubMeshCandidates(mesh);
  95761. };
  95762. /**
  95763. * Rebuilds the elements related to this component in case of
  95764. * context lost for instance.
  95765. */
  95766. OctreeSceneComponent.prototype.rebuild = function () {
  95767. // Nothing to do here.
  95768. };
  95769. /**
  95770. * Disposes the component and the associated ressources.
  95771. */
  95772. OctreeSceneComponent.prototype.dispose = function () {
  95773. // Nothing to do here.
  95774. };
  95775. return OctreeSceneComponent;
  95776. }());
  95777. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  95778. })(BABYLON || (BABYLON = {}));
  95779. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  95780. var BABYLON;
  95781. (function (BABYLON) {
  95782. /**
  95783. * Postprocess used to generate anaglyphic rendering
  95784. */
  95785. var AnaglyphPostProcess = /** @class */ (function (_super) {
  95786. __extends(AnaglyphPostProcess, _super);
  95787. /**
  95788. * Creates a new AnaglyphPostProcess
  95789. * @param name defines postprocess name
  95790. * @param options defines creation options or target ratio scale
  95791. * @param rigCameras defines cameras using this postprocess
  95792. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  95793. * @param engine defines hosting engine
  95794. * @param reusable defines if the postprocess will be reused multiple times per frame
  95795. */
  95796. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  95797. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  95798. _this._passedProcess = rigCameras[0]._rigPostProcess;
  95799. _this.onApplyObservable.add(function (effect) {
  95800. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  95801. });
  95802. return _this;
  95803. }
  95804. return AnaglyphPostProcess;
  95805. }(BABYLON.PostProcess));
  95806. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  95807. })(BABYLON || (BABYLON = {}));
  95808. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  95809. var BABYLON;
  95810. (function (BABYLON) {
  95811. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  95812. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95813. });
  95814. /**
  95815. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  95816. */
  95817. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  95818. __extends(AnaglyphArcRotateCamera, _super);
  95819. /**
  95820. * Creates a new AnaglyphArcRotateCamera
  95821. * @param name defines camera name
  95822. * @param alpha defines alpha angle (in radians)
  95823. * @param beta defines beta angle (in radians)
  95824. * @param radius defines radius
  95825. * @param target defines camera target
  95826. * @param interaxialDistance defines distance between each color axis
  95827. * @param scene defines the hosting scene
  95828. */
  95829. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  95830. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  95831. _this.interaxialDistance = interaxialDistance;
  95832. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95833. return _this;
  95834. }
  95835. /**
  95836. * Gets camera class name
  95837. * @returns AnaglyphArcRotateCamera
  95838. */
  95839. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  95840. return "AnaglyphArcRotateCamera";
  95841. };
  95842. return AnaglyphArcRotateCamera;
  95843. }(BABYLON.ArcRotateCamera));
  95844. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  95845. })(BABYLON || (BABYLON = {}));
  95846. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  95847. var BABYLON;
  95848. (function (BABYLON) {
  95849. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  95850. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95851. });
  95852. /**
  95853. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  95854. */
  95855. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  95856. __extends(AnaglyphFreeCamera, _super);
  95857. /**
  95858. * Creates a new AnaglyphFreeCamera
  95859. * @param name defines camera name
  95860. * @param position defines initial position
  95861. * @param interaxialDistance defines distance between each color axis
  95862. * @param scene defines the hosting scene
  95863. */
  95864. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  95865. var _this = _super.call(this, name, position, scene) || this;
  95866. _this.interaxialDistance = interaxialDistance;
  95867. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95868. return _this;
  95869. }
  95870. /**
  95871. * Gets camera class name
  95872. * @returns AnaglyphFreeCamera
  95873. */
  95874. AnaglyphFreeCamera.prototype.getClassName = function () {
  95875. return "AnaglyphFreeCamera";
  95876. };
  95877. return AnaglyphFreeCamera;
  95878. }(BABYLON.FreeCamera));
  95879. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  95880. })(BABYLON || (BABYLON = {}));
  95881. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  95882. var BABYLON;
  95883. (function (BABYLON) {
  95884. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  95885. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95886. });
  95887. /**
  95888. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  95889. */
  95890. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  95891. __extends(AnaglyphGamepadCamera, _super);
  95892. /**
  95893. * Creates a new AnaglyphGamepadCamera
  95894. * @param name defines camera name
  95895. * @param position defines initial position
  95896. * @param interaxialDistance defines distance between each color axis
  95897. * @param scene defines the hosting scene
  95898. */
  95899. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  95900. var _this = _super.call(this, name, position, scene) || this;
  95901. _this.interaxialDistance = interaxialDistance;
  95902. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95903. return _this;
  95904. }
  95905. /**
  95906. * Gets camera class name
  95907. * @returns AnaglyphGamepadCamera
  95908. */
  95909. AnaglyphGamepadCamera.prototype.getClassName = function () {
  95910. return "AnaglyphGamepadCamera";
  95911. };
  95912. return AnaglyphGamepadCamera;
  95913. }(BABYLON.GamepadCamera));
  95914. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  95915. })(BABYLON || (BABYLON = {}));
  95916. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  95917. var BABYLON;
  95918. (function (BABYLON) {
  95919. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  95920. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95921. });
  95922. /**
  95923. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  95924. */
  95925. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  95926. __extends(AnaglyphUniversalCamera, _super);
  95927. /**
  95928. * Creates a new AnaglyphUniversalCamera
  95929. * @param name defines camera name
  95930. * @param position defines initial position
  95931. * @param interaxialDistance defines distance between each color axis
  95932. * @param scene defines the hosting scene
  95933. */
  95934. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  95935. var _this = _super.call(this, name, position, scene) || this;
  95936. _this.interaxialDistance = interaxialDistance;
  95937. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95938. return _this;
  95939. }
  95940. /**
  95941. * Gets camera class name
  95942. * @returns AnaglyphUniversalCamera
  95943. */
  95944. AnaglyphUniversalCamera.prototype.getClassName = function () {
  95945. return "AnaglyphUniversalCamera";
  95946. };
  95947. return AnaglyphUniversalCamera;
  95948. }(BABYLON.UniversalCamera));
  95949. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  95950. })(BABYLON || (BABYLON = {}));
  95951. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  95952. var BABYLON;
  95953. (function (BABYLON) {
  95954. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  95955. __extends(StereoscopicInterlacePostProcess, _super);
  95956. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  95957. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  95958. _this._passedProcess = rigCameras[0]._rigPostProcess;
  95959. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  95960. _this.onSizeChangedObservable.add(function () {
  95961. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  95962. });
  95963. _this.onApplyObservable.add(function (effect) {
  95964. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  95965. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  95966. });
  95967. return _this;
  95968. }
  95969. return StereoscopicInterlacePostProcess;
  95970. }(BABYLON.PostProcess));
  95971. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  95972. })(BABYLON || (BABYLON = {}));
  95973. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  95974. var BABYLON;
  95975. (function (BABYLON) {
  95976. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  95977. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  95978. });
  95979. /**
  95980. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  95981. */
  95982. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  95983. __extends(StereoscopicArcRotateCamera, _super);
  95984. /**
  95985. * Creates a new StereoscopicArcRotateCamera
  95986. * @param name defines camera name
  95987. * @param alpha defines alpha angle (in radians)
  95988. * @param beta defines beta angle (in radians)
  95989. * @param radius defines radius
  95990. * @param target defines camera target
  95991. * @param interaxialDistance defines distance between each color axis
  95992. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  95993. * @param scene defines the hosting scene
  95994. */
  95995. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  95996. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  95997. _this.interaxialDistance = interaxialDistance;
  95998. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  95999. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96000. return _this;
  96001. }
  96002. /**
  96003. * Gets camera class name
  96004. * @returns StereoscopicArcRotateCamera
  96005. */
  96006. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  96007. return "StereoscopicArcRotateCamera";
  96008. };
  96009. return StereoscopicArcRotateCamera;
  96010. }(BABYLON.ArcRotateCamera));
  96011. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  96012. })(BABYLON || (BABYLON = {}));
  96013. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  96014. var BABYLON;
  96015. (function (BABYLON) {
  96016. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  96017. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96018. });
  96019. /**
  96020. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  96021. */
  96022. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  96023. __extends(StereoscopicFreeCamera, _super);
  96024. /**
  96025. * Creates a new StereoscopicFreeCamera
  96026. * @param name defines camera name
  96027. * @param position defines initial position
  96028. * @param interaxialDistance defines distance between each color axis
  96029. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96030. * @param scene defines the hosting scene
  96031. */
  96032. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96033. var _this = _super.call(this, name, position, scene) || this;
  96034. _this.interaxialDistance = interaxialDistance;
  96035. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96036. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96037. return _this;
  96038. }
  96039. /**
  96040. * Gets camera class name
  96041. * @returns StereoscopicFreeCamera
  96042. */
  96043. StereoscopicFreeCamera.prototype.getClassName = function () {
  96044. return "StereoscopicFreeCamera";
  96045. };
  96046. return StereoscopicFreeCamera;
  96047. }(BABYLON.FreeCamera));
  96048. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  96049. })(BABYLON || (BABYLON = {}));
  96050. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  96051. var BABYLON;
  96052. (function (BABYLON) {
  96053. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  96054. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96055. });
  96056. /**
  96057. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  96058. */
  96059. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  96060. __extends(StereoscopicGamepadCamera, _super);
  96061. /**
  96062. * Creates a new StereoscopicGamepadCamera
  96063. * @param name defines camera name
  96064. * @param position defines initial position
  96065. * @param interaxialDistance defines distance between each color axis
  96066. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96067. * @param scene defines the hosting scene
  96068. */
  96069. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96070. var _this = _super.call(this, name, position, scene) || this;
  96071. _this.interaxialDistance = interaxialDistance;
  96072. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96073. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96074. return _this;
  96075. }
  96076. /**
  96077. * Gets camera class name
  96078. * @returns StereoscopicGamepadCamera
  96079. */
  96080. StereoscopicGamepadCamera.prototype.getClassName = function () {
  96081. return "StereoscopicGamepadCamera";
  96082. };
  96083. return StereoscopicGamepadCamera;
  96084. }(BABYLON.GamepadCamera));
  96085. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  96086. })(BABYLON || (BABYLON = {}));
  96087. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  96088. var BABYLON;
  96089. (function (BABYLON) {
  96090. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  96091. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96092. });
  96093. /**
  96094. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  96095. */
  96096. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  96097. __extends(StereoscopicUniversalCamera, _super);
  96098. /**
  96099. * Creates a new StereoscopicUniversalCamera
  96100. * @param name defines camera name
  96101. * @param position defines initial position
  96102. * @param interaxialDistance defines distance between each color axis
  96103. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96104. * @param scene defines the hosting scene
  96105. */
  96106. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96107. var _this = _super.call(this, name, position, scene) || this;
  96108. _this.interaxialDistance = interaxialDistance;
  96109. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96110. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96111. return _this;
  96112. }
  96113. /**
  96114. * Gets camera class name
  96115. * @returns StereoscopicUniversalCamera
  96116. */
  96117. StereoscopicUniversalCamera.prototype.getClassName = function () {
  96118. return "StereoscopicUniversalCamera";
  96119. };
  96120. return StereoscopicUniversalCamera;
  96121. }(BABYLON.UniversalCamera));
  96122. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  96123. })(BABYLON || (BABYLON = {}));
  96124. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  96125. var BABYLON;
  96126. (function (BABYLON) {
  96127. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  96128. __extends(VRDistortionCorrectionPostProcess, _super);
  96129. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  96130. var _this = _super.call(this, name, "vrDistortionCorrection", [
  96131. 'LensCenter',
  96132. 'Scale',
  96133. 'ScaleIn',
  96134. 'HmdWarpParam'
  96135. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  96136. _this._isRightEye = isRightEye;
  96137. _this._distortionFactors = vrMetrics.distortionK;
  96138. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  96139. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  96140. _this.adaptScaleToCurrentViewport = true;
  96141. _this.onSizeChangedObservable.add(function () {
  96142. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  96143. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  96144. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  96145. });
  96146. _this.onApplyObservable.add(function (effect) {
  96147. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  96148. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  96149. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  96150. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  96151. });
  96152. return _this;
  96153. }
  96154. return VRDistortionCorrectionPostProcess;
  96155. }(BABYLON.PostProcess));
  96156. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  96157. })(BABYLON || (BABYLON = {}));
  96158. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  96159. var BABYLON;
  96160. (function (BABYLON) {
  96161. /**
  96162. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  96163. * Screen rotation is taken into account.
  96164. */
  96165. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  96166. function FreeCameraDeviceOrientationInput() {
  96167. var _this = this;
  96168. this._screenOrientationAngle = 0;
  96169. this._screenQuaternion = new BABYLON.Quaternion();
  96170. this._alpha = 0;
  96171. this._beta = 0;
  96172. this._gamma = 0;
  96173. this._orientationChanged = function () {
  96174. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  96175. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  96176. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  96177. };
  96178. this._deviceOrientation = function (evt) {
  96179. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  96180. _this._beta = evt.beta !== null ? evt.beta : 0;
  96181. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  96182. };
  96183. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  96184. this._orientationChanged();
  96185. }
  96186. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  96187. get: function () {
  96188. return this._camera;
  96189. },
  96190. set: function (camera) {
  96191. this._camera = camera;
  96192. if (this._camera != null && !this._camera.rotationQuaternion) {
  96193. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  96194. }
  96195. },
  96196. enumerable: true,
  96197. configurable: true
  96198. });
  96199. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  96200. window.addEventListener("orientationchange", this._orientationChanged);
  96201. window.addEventListener("deviceorientation", this._deviceOrientation);
  96202. //In certain cases, the attach control is called AFTER orientation was changed,
  96203. //So this is needed.
  96204. this._orientationChanged();
  96205. };
  96206. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  96207. window.removeEventListener("orientationchange", this._orientationChanged);
  96208. window.removeEventListener("deviceorientation", this._deviceOrientation);
  96209. };
  96210. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  96211. //if no device orientation provided, don't update the rotation.
  96212. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  96213. if (!this._alpha)
  96214. return;
  96215. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  96216. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  96217. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  96218. //Mirror on XY Plane
  96219. this._camera.rotationQuaternion.z *= -1;
  96220. this._camera.rotationQuaternion.w *= -1;
  96221. };
  96222. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  96223. return "FreeCameraDeviceOrientationInput";
  96224. };
  96225. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  96226. return "deviceOrientation";
  96227. };
  96228. return FreeCameraDeviceOrientationInput;
  96229. }());
  96230. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  96231. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  96232. })(BABYLON || (BABYLON = {}));
  96233. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  96234. var BABYLON;
  96235. (function (BABYLON) {
  96236. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  96237. function ArcRotateCameraVRDeviceOrientationInput() {
  96238. this.alphaCorrection = 1;
  96239. this.betaCorrection = 1;
  96240. this.gammaCorrection = 1;
  96241. this._alpha = 0;
  96242. this._gamma = 0;
  96243. this._dirty = false;
  96244. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  96245. }
  96246. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  96247. this.camera.attachControl(element, noPreventDefault);
  96248. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  96249. };
  96250. /** @hidden */
  96251. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  96252. if (evt.alpha !== null) {
  96253. this._alpha = +evt.alpha | 0;
  96254. }
  96255. if (evt.gamma !== null) {
  96256. this._gamma = +evt.gamma | 0;
  96257. }
  96258. this._dirty = true;
  96259. };
  96260. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  96261. if (this._dirty) {
  96262. this._dirty = false;
  96263. if (this._gamma < 0) {
  96264. this._gamma = 180 + this._gamma;
  96265. }
  96266. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  96267. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  96268. }
  96269. };
  96270. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  96271. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  96272. };
  96273. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  96274. return "ArcRotateCameraVRDeviceOrientationInput";
  96275. };
  96276. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  96277. return "VRDeviceOrientation";
  96278. };
  96279. return ArcRotateCameraVRDeviceOrientationInput;
  96280. }());
  96281. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  96282. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  96283. })(BABYLON || (BABYLON = {}));
  96284. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  96285. var BABYLON;
  96286. (function (BABYLON) {
  96287. var VRCameraMetrics = /** @class */ (function () {
  96288. function VRCameraMetrics() {
  96289. this.compensateDistortion = true;
  96290. }
  96291. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  96292. get: function () {
  96293. return this.hResolution / (2 * this.vResolution);
  96294. },
  96295. enumerable: true,
  96296. configurable: true
  96297. });
  96298. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  96299. get: function () {
  96300. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  96301. },
  96302. enumerable: true,
  96303. configurable: true
  96304. });
  96305. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  96306. get: function () {
  96307. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  96308. var h = (4 * meters) / this.hScreenSize;
  96309. return BABYLON.Matrix.Translation(h, 0, 0);
  96310. },
  96311. enumerable: true,
  96312. configurable: true
  96313. });
  96314. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  96315. get: function () {
  96316. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  96317. var h = (4 * meters) / this.hScreenSize;
  96318. return BABYLON.Matrix.Translation(-h, 0, 0);
  96319. },
  96320. enumerable: true,
  96321. configurable: true
  96322. });
  96323. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  96324. get: function () {
  96325. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  96326. },
  96327. enumerable: true,
  96328. configurable: true
  96329. });
  96330. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  96331. get: function () {
  96332. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  96333. },
  96334. enumerable: true,
  96335. configurable: true
  96336. });
  96337. VRCameraMetrics.GetDefault = function () {
  96338. var result = new VRCameraMetrics();
  96339. result.hResolution = 1280;
  96340. result.vResolution = 800;
  96341. result.hScreenSize = 0.149759993;
  96342. result.vScreenSize = 0.0935999975;
  96343. result.vScreenCenter = 0.0467999987;
  96344. result.eyeToScreenDistance = 0.0410000011;
  96345. result.lensSeparationDistance = 0.0635000020;
  96346. result.interpupillaryDistance = 0.0640000030;
  96347. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  96348. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  96349. result.postProcessScaleFactor = 1.714605507808412;
  96350. result.lensCenterOffset = 0.151976421;
  96351. return result;
  96352. };
  96353. return VRCameraMetrics;
  96354. }());
  96355. BABYLON.VRCameraMetrics = VRCameraMetrics;
  96356. })(BABYLON || (BABYLON = {}));
  96357. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  96358. var BABYLON;
  96359. (function (BABYLON) {
  96360. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  96361. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96362. });
  96363. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  96364. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96365. });
  96366. /**
  96367. * This represents a WebVR camera.
  96368. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  96369. * @example http://doc.babylonjs.com/how_to/webvr_camera
  96370. */
  96371. var WebVRFreeCamera = /** @class */ (function (_super) {
  96372. __extends(WebVRFreeCamera, _super);
  96373. /**
  96374. * Instantiates a WebVRFreeCamera.
  96375. * @param name The name of the WebVRFreeCamera
  96376. * @param position The starting anchor position for the camera
  96377. * @param scene The scene the camera belongs to
  96378. * @param webVROptions a set of customizable options for the webVRCamera
  96379. */
  96380. function WebVRFreeCamera(name, position, scene, webVROptions) {
  96381. if (webVROptions === void 0) { webVROptions = {}; }
  96382. var _this = _super.call(this, name, position, scene) || this;
  96383. _this.webVROptions = webVROptions;
  96384. /**
  96385. * @hidden
  96386. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  96387. */
  96388. _this._vrDevice = null;
  96389. /**
  96390. * The rawPose of the vrDevice.
  96391. */
  96392. _this.rawPose = null;
  96393. _this._specsVersion = "1.1";
  96394. _this._attached = false;
  96395. _this._descendants = [];
  96396. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  96397. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  96398. /** @hidden */
  96399. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  96400. _this._standingMatrix = null;
  96401. /**
  96402. * Represents device position in babylon space.
  96403. */
  96404. _this.devicePosition = BABYLON.Vector3.Zero();
  96405. /**
  96406. * Represents device rotation in babylon space.
  96407. */
  96408. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  96409. /**
  96410. * The scale of the device to be used when translating from device space to babylon space.
  96411. */
  96412. _this.deviceScaleFactor = 1;
  96413. _this._deviceToWorld = BABYLON.Matrix.Identity();
  96414. _this._worldToDevice = BABYLON.Matrix.Identity();
  96415. /**
  96416. * References to the webVR controllers for the vrDevice.
  96417. */
  96418. _this.controllers = [];
  96419. /**
  96420. * Emits an event when a controller is attached.
  96421. */
  96422. _this.onControllersAttachedObservable = new BABYLON.Observable();
  96423. /**
  96424. * Emits an event when a controller's mesh has been loaded;
  96425. */
  96426. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  96427. /**
  96428. * Emits an event when the HMD's pose has been updated.
  96429. */
  96430. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  96431. _this._poseSet = false;
  96432. /**
  96433. * If the rig cameras be used as parent instead of this camera.
  96434. */
  96435. _this.rigParenting = true;
  96436. _this._defaultHeight = undefined;
  96437. _this._htmlElementAttached = null;
  96438. _this._detachIfAttached = function () {
  96439. var vrDisplay = _this.getEngine().getVRDevice();
  96440. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  96441. _this.detachControl(_this._htmlElementAttached);
  96442. }
  96443. };
  96444. _this._workingVector = BABYLON.Vector3.Zero();
  96445. _this._oneVector = BABYLON.Vector3.One();
  96446. _this._workingMatrix = BABYLON.Matrix.Identity();
  96447. _this._tmpMatrix = new BABYLON.Matrix();
  96448. _this._cache.position = BABYLON.Vector3.Zero();
  96449. if (webVROptions.defaultHeight) {
  96450. _this._defaultHeight = webVROptions.defaultHeight;
  96451. _this.position.y = _this._defaultHeight;
  96452. }
  96453. _this.minZ = 0.1;
  96454. //legacy support - the compensation boolean was removed.
  96455. if (arguments.length === 5) {
  96456. _this.webVROptions = arguments[4];
  96457. }
  96458. // default webVR options
  96459. if (_this.webVROptions.trackPosition == undefined) {
  96460. _this.webVROptions.trackPosition = true;
  96461. }
  96462. if (_this.webVROptions.controllerMeshes == undefined) {
  96463. _this.webVROptions.controllerMeshes = true;
  96464. }
  96465. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  96466. _this.webVROptions.defaultLightingOnControllers = true;
  96467. }
  96468. _this.rotationQuaternion = new BABYLON.Quaternion();
  96469. if (_this.webVROptions && _this.webVROptions.positionScale) {
  96470. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  96471. }
  96472. //enable VR
  96473. var engine = _this.getEngine();
  96474. _this._onVREnabled = function (success) { if (success) {
  96475. _this.initControllers();
  96476. } };
  96477. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  96478. engine.initWebVR().add(function (event) {
  96479. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  96480. return;
  96481. }
  96482. _this._vrDevice = event.vrDisplay;
  96483. //reset the rig parameters.
  96484. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  96485. if (_this._attached) {
  96486. _this.getEngine().enableVR();
  96487. }
  96488. });
  96489. if (typeof (VRFrameData) !== "undefined")
  96490. _this._frameData = new VRFrameData();
  96491. /**
  96492. * The idea behind the following lines:
  96493. * objects that have the camera as parent should actually have the rig cameras as a parent.
  96494. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  96495. * the second will not show it correctly.
  96496. *
  96497. * To solve this - each object that has the camera as parent will be added to a protected array.
  96498. * When the rig camera renders, it will take this array and set all of those to be its children.
  96499. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  96500. * Amazing!
  96501. */
  96502. scene.onBeforeCameraRenderObservable.add(function (camera) {
  96503. if (camera.parent === _this && _this.rigParenting) {
  96504. _this._descendants = _this.getDescendants(true, function (n) {
  96505. // don't take the cameras or the controllers!
  96506. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  96507. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  96508. return !isController && !isRigCamera;
  96509. });
  96510. _this._descendants.forEach(function (node) {
  96511. node.parent = camera;
  96512. });
  96513. }
  96514. });
  96515. scene.onAfterCameraRenderObservable.add(function (camera) {
  96516. if (camera.parent === _this && _this.rigParenting) {
  96517. _this._descendants.forEach(function (node) {
  96518. node.parent = _this;
  96519. });
  96520. }
  96521. });
  96522. return _this;
  96523. }
  96524. /**
  96525. * Gets the device distance from the ground in meters.
  96526. * @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.
  96527. */
  96528. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  96529. if (this._standingMatrix) {
  96530. // Add standing matrix offset to get real offset from ground in room
  96531. this._standingMatrix.getTranslationToRef(this._workingVector);
  96532. return this._deviceRoomPosition.y + this._workingVector.y;
  96533. }
  96534. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  96535. return this._defaultHeight || 0;
  96536. };
  96537. /**
  96538. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  96539. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  96540. */
  96541. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  96542. var _this = this;
  96543. if (callback === void 0) { callback = function (bool) { }; }
  96544. // Use standing matrix if available
  96545. this.getEngine().initWebVRAsync().then(function (result) {
  96546. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  96547. callback(false);
  96548. }
  96549. else {
  96550. _this._standingMatrix = new BABYLON.Matrix();
  96551. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  96552. if (!_this.getScene().useRightHandedSystem) {
  96553. [2, 6, 8, 9, 14].forEach(function (num) {
  96554. if (_this._standingMatrix) {
  96555. _this._standingMatrix.m[num] *= -1;
  96556. }
  96557. });
  96558. }
  96559. callback(true);
  96560. }
  96561. });
  96562. };
  96563. /**
  96564. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  96565. * @returns A promise with a boolean set to if the standing matrix is supported.
  96566. */
  96567. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  96568. var _this = this;
  96569. return new Promise(function (res, rej) {
  96570. _this.useStandingMatrix(function (supported) {
  96571. res(supported);
  96572. });
  96573. });
  96574. };
  96575. /**
  96576. * Disposes the camera
  96577. */
  96578. WebVRFreeCamera.prototype.dispose = function () {
  96579. this._detachIfAttached();
  96580. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  96581. _super.prototype.dispose.call(this);
  96582. };
  96583. /**
  96584. * Gets a vrController by name.
  96585. * @param name The name of the controller to retreive
  96586. * @returns the controller matching the name specified or null if not found
  96587. */
  96588. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  96589. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  96590. var gp = _a[_i];
  96591. if (gp.hand === name) {
  96592. return gp;
  96593. }
  96594. }
  96595. return null;
  96596. };
  96597. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  96598. /**
  96599. * The controller corrisponding to the users left hand.
  96600. */
  96601. get: function () {
  96602. if (!this._leftController) {
  96603. this._leftController = this.getControllerByName("left");
  96604. }
  96605. return this._leftController;
  96606. },
  96607. enumerable: true,
  96608. configurable: true
  96609. });
  96610. ;
  96611. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  96612. /**
  96613. * The controller corrisponding to the users right hand.
  96614. */
  96615. get: function () {
  96616. if (!this._rightController) {
  96617. this._rightController = this.getControllerByName("right");
  96618. }
  96619. return this._rightController;
  96620. },
  96621. enumerable: true,
  96622. configurable: true
  96623. });
  96624. ;
  96625. /**
  96626. * Casts a ray forward from the vrCamera's gaze.
  96627. * @param length Length of the ray (default: 100)
  96628. * @returns the ray corrisponding to the gaze
  96629. */
  96630. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  96631. if (length === void 0) { length = 100; }
  96632. if (this.leftCamera) {
  96633. // Use left eye to avoid computation to compute center on every call
  96634. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  96635. }
  96636. else {
  96637. return _super.prototype.getForwardRay.call(this, length);
  96638. }
  96639. };
  96640. /**
  96641. * @hidden
  96642. * Updates the camera based on device's frame data
  96643. */
  96644. WebVRFreeCamera.prototype._checkInputs = function () {
  96645. if (this._vrDevice && this._vrDevice.isPresenting) {
  96646. this._vrDevice.getFrameData(this._frameData);
  96647. this.updateFromDevice(this._frameData.pose);
  96648. }
  96649. _super.prototype._checkInputs.call(this);
  96650. };
  96651. /**
  96652. * Updates the poseControlled values based on the input device pose.
  96653. * @param poseData Pose coming from the device
  96654. */
  96655. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  96656. if (poseData && poseData.orientation) {
  96657. this.rawPose = poseData;
  96658. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  96659. if (this.getScene().useRightHandedSystem) {
  96660. this._deviceRoomRotationQuaternion.z *= -1;
  96661. this._deviceRoomRotationQuaternion.w *= -1;
  96662. }
  96663. if (this.webVROptions.trackPosition && this.rawPose.position) {
  96664. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  96665. if (this.getScene().useRightHandedSystem) {
  96666. this._deviceRoomPosition.z *= -1;
  96667. }
  96668. }
  96669. this._poseSet = true;
  96670. }
  96671. };
  96672. /**
  96673. * WebVR's attach control will start broadcasting frames to the device.
  96674. * Note that in certain browsers (chrome for example) this function must be called
  96675. * within a user-interaction callback. Example:
  96676. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  96677. *
  96678. * @param element html element to attach the vrDevice to
  96679. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  96680. */
  96681. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  96682. _super.prototype.attachControl.call(this, element, noPreventDefault);
  96683. this._attached = true;
  96684. this._htmlElementAttached = element;
  96685. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  96686. if (this._vrDevice) {
  96687. this.getEngine().enableVR();
  96688. }
  96689. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  96690. };
  96691. /**
  96692. * Detaches the camera from the html element and disables VR
  96693. *
  96694. * @param element html element to detach from
  96695. */
  96696. WebVRFreeCamera.prototype.detachControl = function (element) {
  96697. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  96698. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  96699. _super.prototype.detachControl.call(this, element);
  96700. this._attached = false;
  96701. this.getEngine().disableVR();
  96702. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  96703. };
  96704. /**
  96705. * @returns the name of this class
  96706. */
  96707. WebVRFreeCamera.prototype.getClassName = function () {
  96708. return "WebVRFreeCamera";
  96709. };
  96710. /**
  96711. * Calls resetPose on the vrDisplay
  96712. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  96713. */
  96714. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  96715. //uses the vrDisplay's "resetPose()".
  96716. //pitch and roll won't be affected.
  96717. this._vrDevice.resetPose();
  96718. };
  96719. /**
  96720. * @hidden
  96721. * Updates the rig cameras (left and right eye)
  96722. */
  96723. WebVRFreeCamera.prototype._updateRigCameras = function () {
  96724. var camLeft = this._rigCameras[0];
  96725. var camRight = this._rigCameras[1];
  96726. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  96727. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  96728. camLeft.position.copyFrom(this._deviceRoomPosition);
  96729. camRight.position.copyFrom(this._deviceRoomPosition);
  96730. };
  96731. // Remove translation from 6dof headset if trackposition is set to false
  96732. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  96733. if (isViewMatrix === void 0) { isViewMatrix = false; }
  96734. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  96735. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  96736. if (!isViewMatrix) {
  96737. this._tmpMatrix.invert();
  96738. }
  96739. this._tmpMatrix.multiplyToRef(matrix, matrix);
  96740. }
  96741. };
  96742. /**
  96743. * @hidden
  96744. * Updates the cached values of the camera
  96745. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  96746. */
  96747. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  96748. var _this = this;
  96749. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  96750. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  96751. if (!this.updateCacheCalled) {
  96752. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  96753. this.updateCacheCalled = true;
  96754. this.update();
  96755. }
  96756. // Set working vector to the device position in room space rotated by the new rotation
  96757. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  96758. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  96759. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  96760. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  96761. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  96762. // Add translation from anchor position
  96763. this._deviceToWorld.getTranslationToRef(this._workingVector);
  96764. this._workingVector.addInPlace(this.position);
  96765. this._workingVector.subtractInPlace(this._cache.position);
  96766. this._deviceToWorld.setTranslation(this._workingVector);
  96767. // Set an inverted matrix to be used when updating the camera
  96768. this._deviceToWorld.invertToRef(this._worldToDevice);
  96769. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  96770. this.controllers.forEach(function (controller) {
  96771. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  96772. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  96773. controller.update();
  96774. });
  96775. }
  96776. if (!ignoreParentClass) {
  96777. _super.prototype._updateCache.call(this);
  96778. }
  96779. this.updateCacheCalled = false;
  96780. };
  96781. /**
  96782. * Updates the current device position and rotation in the babylon world
  96783. */
  96784. WebVRFreeCamera.prototype.update = function () {
  96785. // Get current device position in babylon world
  96786. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  96787. // Get current device rotation in babylon world
  96788. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  96789. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  96790. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  96791. if (this._poseSet) {
  96792. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  96793. }
  96794. _super.prototype.update.call(this);
  96795. };
  96796. /**
  96797. * @hidden
  96798. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  96799. * @returns an identity matrix
  96800. */
  96801. WebVRFreeCamera.prototype._getViewMatrix = function () {
  96802. return BABYLON.Matrix.Identity();
  96803. };
  96804. /**
  96805. * This function is called by the two RIG cameras.
  96806. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  96807. */
  96808. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  96809. var _this = this;
  96810. // Update the parent camera prior to using a child camera to avoid desynchronization
  96811. var parentCamera = this._cameraRigParams["parentCamera"];
  96812. parentCamera._updateCache();
  96813. //WebVR 1.1
  96814. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  96815. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  96816. if (!this.getScene().useRightHandedSystem) {
  96817. [2, 6, 8, 9, 14].forEach(function (num) {
  96818. _this._webvrViewMatrix.m[num] *= -1;
  96819. });
  96820. }
  96821. // update the camera rotation matrix
  96822. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  96823. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  96824. // Computing target and final matrix
  96825. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  96826. // should the view matrix be updated with scale and position offset?
  96827. if (parentCamera.deviceScaleFactor !== 1) {
  96828. this._webvrViewMatrix.invert();
  96829. // scale the position, if set
  96830. if (parentCamera.deviceScaleFactor) {
  96831. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  96832. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  96833. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  96834. }
  96835. this._webvrViewMatrix.invert();
  96836. }
  96837. // Remove translation from 6dof headset if trackposition is set to false
  96838. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  96839. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  96840. // Compute global position
  96841. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  96842. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  96843. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  96844. this._workingMatrix.getTranslationToRef(this._globalPosition);
  96845. this._markSyncedWithParent();
  96846. return this._webvrViewMatrix;
  96847. };
  96848. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  96849. var _this = this;
  96850. var parentCamera = this.parent;
  96851. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  96852. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  96853. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  96854. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  96855. //babylon compatible matrix
  96856. if (!this.getScene().useRightHandedSystem) {
  96857. [8, 9, 10, 11].forEach(function (num) {
  96858. _this._projectionMatrix.m[num] *= -1;
  96859. });
  96860. }
  96861. return this._projectionMatrix;
  96862. };
  96863. /**
  96864. * Initializes the controllers and their meshes
  96865. */
  96866. WebVRFreeCamera.prototype.initControllers = function () {
  96867. var _this = this;
  96868. this.controllers = [];
  96869. var manager = this.getScene().gamepadManager;
  96870. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  96871. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  96872. var webVrController = gamepad;
  96873. if (webVrController.defaultModel) {
  96874. webVrController.defaultModel.setEnabled(false);
  96875. }
  96876. if (webVrController.hand === "right") {
  96877. _this._rightController = null;
  96878. }
  96879. if (webVrController.hand === "left") {
  96880. _this._leftController = null;
  96881. }
  96882. var controllerIndex = _this.controllers.indexOf(webVrController);
  96883. if (controllerIndex !== -1) {
  96884. _this.controllers.splice(controllerIndex, 1);
  96885. }
  96886. }
  96887. });
  96888. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  96889. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  96890. var webVrController_1 = gamepad;
  96891. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  96892. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  96893. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  96894. if (_this.webVROptions.controllerMeshes) {
  96895. if (webVrController_1.defaultModel) {
  96896. webVrController_1.defaultModel.setEnabled(true);
  96897. }
  96898. else {
  96899. // Load the meshes
  96900. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  96901. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  96902. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  96903. if (_this.webVROptions.defaultLightingOnControllers) {
  96904. if (!_this._lightOnControllers) {
  96905. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  96906. }
  96907. var activateLightOnSubMeshes_1 = function (mesh, light) {
  96908. var children = mesh.getChildren();
  96909. if (children && children.length !== 0) {
  96910. children.forEach(function (mesh) {
  96911. light.includedOnlyMeshes.push(mesh);
  96912. activateLightOnSubMeshes_1(mesh, light);
  96913. });
  96914. }
  96915. };
  96916. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  96917. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  96918. }
  96919. });
  96920. }
  96921. }
  96922. webVrController_1.attachToPoseControlledCamera(_this);
  96923. // since this is async - sanity check. Is the controller already stored?
  96924. if (_this.controllers.indexOf(webVrController_1) === -1) {
  96925. //add to the controllers array
  96926. _this.controllers.push(webVrController_1);
  96927. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  96928. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  96929. // So we're overriding setting left & right manually to be sure
  96930. var firstViveWandDetected = false;
  96931. for (var i = 0; i < _this.controllers.length; i++) {
  96932. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  96933. if (!firstViveWandDetected) {
  96934. firstViveWandDetected = true;
  96935. _this.controllers[i].hand = "left";
  96936. }
  96937. else {
  96938. _this.controllers[i].hand = "right";
  96939. }
  96940. }
  96941. }
  96942. //did we find enough controllers? Great! let the developer know.
  96943. if (_this.controllers.length >= 2) {
  96944. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  96945. }
  96946. }
  96947. }
  96948. });
  96949. };
  96950. return WebVRFreeCamera;
  96951. }(BABYLON.FreeCamera));
  96952. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  96953. })(BABYLON || (BABYLON = {}));
  96954. //# sourceMappingURL=babylon.webVRCamera.js.map
  96955. var BABYLON;
  96956. (function (BABYLON) {
  96957. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  96958. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  96959. });
  96960. // We're mainly based on the logic defined into the FreeCamera code
  96961. /**
  96962. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  96963. * being tilted forward or back and left or right.
  96964. */
  96965. var DeviceOrientationCamera = /** @class */ (function (_super) {
  96966. __extends(DeviceOrientationCamera, _super);
  96967. /**
  96968. * Creates a new device orientation camera
  96969. * @param name The name of the camera
  96970. * @param position The start position camera
  96971. * @param scene The scene the camera belongs to
  96972. */
  96973. function DeviceOrientationCamera(name, position, scene) {
  96974. var _this = _super.call(this, name, position, scene) || this;
  96975. _this._quaternionCache = new BABYLON.Quaternion();
  96976. _this.inputs.addDeviceOrientation();
  96977. return _this;
  96978. }
  96979. /**
  96980. * Gets the current instance class name ("DeviceOrientationCamera").
  96981. * This helps avoiding instanceof at run time.
  96982. * @returns the class name
  96983. */
  96984. DeviceOrientationCamera.prototype.getClassName = function () {
  96985. return "DeviceOrientationCamera";
  96986. };
  96987. /**
  96988. * @hidden
  96989. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  96990. */
  96991. DeviceOrientationCamera.prototype._checkInputs = function () {
  96992. _super.prototype._checkInputs.call(this);
  96993. this._quaternionCache.copyFrom(this.rotationQuaternion);
  96994. if (this._initialQuaternion) {
  96995. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  96996. }
  96997. };
  96998. /**
  96999. * Reset the camera to its default orientation on the specified axis only.
  97000. * @param axis The axis to reset
  97001. */
  97002. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  97003. var _this = this;
  97004. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  97005. //can only work if this camera has a rotation quaternion already.
  97006. if (!this.rotationQuaternion)
  97007. return;
  97008. if (!this._initialQuaternion) {
  97009. this._initialQuaternion = new BABYLON.Quaternion();
  97010. }
  97011. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  97012. ['x', 'y', 'z'].forEach(function (axisName) {
  97013. if (!axis[axisName]) {
  97014. _this._initialQuaternion[axisName] = 0;
  97015. }
  97016. else {
  97017. _this._initialQuaternion[axisName] *= -1;
  97018. }
  97019. });
  97020. this._initialQuaternion.normalize();
  97021. //force rotation update
  97022. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  97023. };
  97024. return DeviceOrientationCamera;
  97025. }(BABYLON.FreeCamera));
  97026. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  97027. })(BABYLON || (BABYLON = {}));
  97028. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  97029. var BABYLON;
  97030. (function (BABYLON) {
  97031. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  97032. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  97033. });
  97034. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  97035. __extends(VRDeviceOrientationFreeCamera, _super);
  97036. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97037. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97038. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97039. var _this = _super.call(this, name, position, scene) || this;
  97040. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97041. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97042. return _this;
  97043. }
  97044. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  97045. return "VRDeviceOrientationFreeCamera";
  97046. };
  97047. return VRDeviceOrientationFreeCamera;
  97048. }(BABYLON.DeviceOrientationCamera));
  97049. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  97050. })(BABYLON || (BABYLON = {}));
  97051. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  97052. var BABYLON;
  97053. (function (BABYLON) {
  97054. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  97055. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  97056. });
  97057. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  97058. __extends(VRDeviceOrientationArcRotateCamera, _super);
  97059. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  97060. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97061. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97062. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  97063. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97064. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97065. _this.inputs.addVRDeviceOrientation();
  97066. return _this;
  97067. }
  97068. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  97069. return "VRDeviceOrientationArcRotateCamera";
  97070. };
  97071. return VRDeviceOrientationArcRotateCamera;
  97072. }(BABYLON.ArcRotateCamera));
  97073. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  97074. })(BABYLON || (BABYLON = {}));
  97075. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  97076. var BABYLON;
  97077. (function (BABYLON) {
  97078. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  97079. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  97080. });
  97081. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  97082. __extends(VRDeviceOrientationGamepadCamera, _super);
  97083. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97084. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97085. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97086. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  97087. _this.inputs.addGamepad();
  97088. return _this;
  97089. }
  97090. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  97091. return "VRDeviceOrientationGamepadCamera";
  97092. };
  97093. return VRDeviceOrientationGamepadCamera;
  97094. }(BABYLON.VRDeviceOrientationFreeCamera));
  97095. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  97096. })(BABYLON || (BABYLON = {}));
  97097. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  97098. var BABYLON;
  97099. (function (BABYLON) {
  97100. var VRExperienceHelperGazer = /** @class */ (function () {
  97101. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  97102. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  97103. this.scene = scene;
  97104. /** @hidden */
  97105. this._pointerDownOnMeshAsked = false;
  97106. /** @hidden */
  97107. this._isActionableMesh = false;
  97108. /** @hidden */
  97109. this._teleportationRequestInitiated = false;
  97110. /** @hidden */
  97111. this._teleportationBackRequestInitiated = false;
  97112. /** @hidden */
  97113. this._rotationRightAsked = false;
  97114. /** @hidden */
  97115. this._rotationLeftAsked = false;
  97116. /** @hidden */
  97117. this._dpadPressed = true;
  97118. /** @hidden */
  97119. this._activePointer = false;
  97120. this._id = VRExperienceHelperGazer._idCounter++;
  97121. // Gaze tracker
  97122. if (!gazeTrackerToClone) {
  97123. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  97124. this._gazeTracker.bakeCurrentTransformIntoVertices();
  97125. this._gazeTracker.isPickable = false;
  97126. this._gazeTracker.isVisible = false;
  97127. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  97128. targetMat.specularColor = BABYLON.Color3.Black();
  97129. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  97130. targetMat.backFaceCulling = false;
  97131. this._gazeTracker.material = targetMat;
  97132. }
  97133. else {
  97134. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  97135. }
  97136. }
  97137. /** @hidden */
  97138. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  97139. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  97140. };
  97141. /** @hidden */
  97142. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  97143. this._pointerDownOnMeshAsked = true;
  97144. if (this._currentHit) {
  97145. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  97146. }
  97147. };
  97148. /** @hidden */
  97149. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  97150. if (this._currentHit) {
  97151. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  97152. }
  97153. this._pointerDownOnMeshAsked = false;
  97154. };
  97155. /** @hidden */
  97156. VRExperienceHelperGazer.prototype._activatePointer = function () {
  97157. this._activePointer = true;
  97158. };
  97159. /** @hidden */
  97160. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  97161. this._activePointer = false;
  97162. };
  97163. /** @hidden */
  97164. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  97165. if (distance === void 0) { distance = 100; }
  97166. };
  97167. VRExperienceHelperGazer.prototype.dispose = function () {
  97168. this._interactionsEnabled = false;
  97169. this._teleportationEnabled = false;
  97170. if (this._gazeTracker) {
  97171. this._gazeTracker.dispose();
  97172. }
  97173. };
  97174. VRExperienceHelperGazer._idCounter = 0;
  97175. return VRExperienceHelperGazer;
  97176. }());
  97177. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  97178. __extends(VRExperienceHelperControllerGazer, _super);
  97179. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  97180. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  97181. _this.webVRController = webVRController;
  97182. // Laser pointer
  97183. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  97184. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  97185. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  97186. laserPointerMaterial.alpha = 0.6;
  97187. _this._laserPointer.material = laserPointerMaterial;
  97188. _this._laserPointer.rotation.x = Math.PI / 2;
  97189. _this._laserPointer.position.z = -0.5;
  97190. _this._laserPointer.isVisible = false;
  97191. _this._laserPointer.isPickable = false;
  97192. if (!webVRController.mesh) {
  97193. // Create an empty mesh that is used prior to loading the high quality model
  97194. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  97195. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  97196. preloadPointerPose.rotation.x = -0.7;
  97197. preloadMesh.addChild(preloadPointerPose);
  97198. webVRController.attachToMesh(preloadMesh);
  97199. }
  97200. _this._setLaserPointerParent(webVRController.mesh);
  97201. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  97202. _this._setLaserPointerParent(mesh);
  97203. });
  97204. return _this;
  97205. }
  97206. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  97207. return this.webVRController.getForwardRay(length);
  97208. };
  97209. /** @hidden */
  97210. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  97211. _super.prototype._activatePointer.call(this);
  97212. this._laserPointer.isVisible = true;
  97213. };
  97214. /** @hidden */
  97215. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  97216. _super.prototype._deactivatePointer.call(this);
  97217. this._laserPointer.isVisible = false;
  97218. };
  97219. /** @hidden */
  97220. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  97221. this._laserPointer.material.emissiveColor = color;
  97222. };
  97223. /** @hidden */
  97224. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  97225. var makeNotPick = function (root) {
  97226. root.isPickable = false;
  97227. root.getChildMeshes().forEach(function (c) {
  97228. makeNotPick(c);
  97229. });
  97230. };
  97231. makeNotPick(mesh);
  97232. var childMeshes = mesh.getChildMeshes();
  97233. this.webVRController._pointingPoseNode = null;
  97234. for (var i = 0; i < childMeshes.length; i++) {
  97235. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  97236. mesh = childMeshes[i];
  97237. this.webVRController._pointingPoseNode = mesh;
  97238. break;
  97239. }
  97240. }
  97241. this._laserPointer.parent = mesh;
  97242. };
  97243. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  97244. if (distance === void 0) { distance = 100; }
  97245. this._laserPointer.scaling.y = distance;
  97246. this._laserPointer.position.z = -distance / 2;
  97247. };
  97248. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  97249. _super.prototype.dispose.call(this);
  97250. this._laserPointer.dispose();
  97251. if (this._meshAttachedObserver) {
  97252. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  97253. }
  97254. };
  97255. return VRExperienceHelperControllerGazer;
  97256. }(VRExperienceHelperGazer));
  97257. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  97258. __extends(VRExperienceHelperCameraGazer, _super);
  97259. function VRExperienceHelperCameraGazer(getCamera, scene) {
  97260. var _this = _super.call(this, scene) || this;
  97261. _this.getCamera = getCamera;
  97262. return _this;
  97263. }
  97264. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  97265. var camera = this.getCamera();
  97266. if (camera) {
  97267. return camera.getForwardRay(length);
  97268. }
  97269. else {
  97270. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  97271. }
  97272. };
  97273. return VRExperienceHelperCameraGazer;
  97274. }(VRExperienceHelperGazer));
  97275. /**
  97276. * Helps to quickly add VR support to an existing scene.
  97277. * See http://doc.babylonjs.com/how_to/webvr_helper
  97278. */
  97279. var VRExperienceHelper = /** @class */ (function () {
  97280. /**
  97281. * Instantiates a VRExperienceHelper.
  97282. * Helps to quickly add VR support to an existing scene.
  97283. * @param scene The scene the VRExperienceHelper belongs to.
  97284. * @param webVROptions Options to modify the vr experience helper's behavior.
  97285. */
  97286. function VRExperienceHelper(scene,
  97287. /** Options to modify the vr experience helper's behavior. */
  97288. webVROptions) {
  97289. if (webVROptions === void 0) { webVROptions = {}; }
  97290. var _this = this;
  97291. this.webVROptions = webVROptions;
  97292. // Can the system support WebVR, even if a headset isn't plugged in?
  97293. this._webVRsupported = false;
  97294. // If WebVR is supported, is a headset plugged in and are we ready to present?
  97295. this._webVRready = false;
  97296. // Are we waiting for the requestPresent callback to complete?
  97297. this._webVRrequesting = false;
  97298. // Are we presenting to the headset right now? (this is the vrDevice state)
  97299. this._webVRpresenting = false;
  97300. // Are we presenting in the fullscreen fallback?
  97301. this._fullscreenVRpresenting = false;
  97302. /**
  97303. * Observable raised when entering VR.
  97304. */
  97305. this.onEnteringVRObservable = new BABYLON.Observable();
  97306. /**
  97307. * Observable raised when exiting VR.
  97308. */
  97309. this.onExitingVRObservable = new BABYLON.Observable();
  97310. /**
  97311. * Observable raised when controller mesh is loaded.
  97312. */
  97313. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  97314. this._useCustomVRButton = false;
  97315. this._teleportationRequested = false;
  97316. this._teleportActive = false;
  97317. this._floorMeshesCollection = [];
  97318. this._rotationAllowed = true;
  97319. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  97320. this._isDefaultTeleportationTarget = true;
  97321. this._teleportationFillColor = "#444444";
  97322. this._teleportationBorderColor = "#FFFFFF";
  97323. this._rotationAngle = 0;
  97324. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  97325. this._padSensibilityUp = 0.65;
  97326. this._padSensibilityDown = 0.35;
  97327. this._leftController = null;
  97328. this._rightController = null;
  97329. /**
  97330. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  97331. */
  97332. this.onNewMeshSelected = new BABYLON.Observable();
  97333. /**
  97334. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  97335. */
  97336. this.onNewMeshPicked = new BABYLON.Observable();
  97337. /**
  97338. * Observable raised before camera teleportation
  97339. */
  97340. this.onBeforeCameraTeleport = new BABYLON.Observable();
  97341. /**
  97342. * Observable raised after camera teleportation
  97343. */
  97344. this.onAfterCameraTeleport = new BABYLON.Observable();
  97345. /**
  97346. * Observable raised when current selected mesh gets unselected
  97347. */
  97348. this.onSelectedMeshUnselected = new BABYLON.Observable();
  97349. /**
  97350. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  97351. */
  97352. this.teleportationEnabled = true;
  97353. this._teleportationInitialized = false;
  97354. this._interactionsEnabled = false;
  97355. this._interactionsRequested = false;
  97356. this._displayGaze = true;
  97357. this._displayLaserPointer = true;
  97358. /**
  97359. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  97360. */
  97361. this.updateGazeTrackerScale = true;
  97362. this._onResize = function () {
  97363. _this.moveButtonToBottomRight();
  97364. if (_this._fullscreenVRpresenting && _this._webVRready) {
  97365. _this.exitVR();
  97366. }
  97367. };
  97368. this._onFullscreenChange = function () {
  97369. if (document.fullscreen !== undefined) {
  97370. _this._fullscreenVRpresenting = document.fullscreen;
  97371. }
  97372. else if (document.mozFullScreen !== undefined) {
  97373. _this._fullscreenVRpresenting = document.mozFullScreen;
  97374. }
  97375. else if (document.webkitIsFullScreen !== undefined) {
  97376. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  97377. }
  97378. else if (document.msIsFullScreen !== undefined) {
  97379. _this._fullscreenVRpresenting = document.msIsFullScreen;
  97380. }
  97381. else if (document.msFullscreenElement !== undefined) {
  97382. _this._fullscreenVRpresenting = document.msFullscreenElement;
  97383. }
  97384. if (!_this._fullscreenVRpresenting && _this._canvas) {
  97385. _this.exitVR();
  97386. if (!_this._useCustomVRButton) {
  97387. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  97388. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  97389. }
  97390. }
  97391. };
  97392. this.beforeRender = function () {
  97393. if (_this._leftController && _this._leftController._activePointer) {
  97394. _this._castRayAndSelectObject(_this._leftController);
  97395. }
  97396. if (_this._rightController && _this._rightController._activePointer) {
  97397. _this._castRayAndSelectObject(_this._rightController);
  97398. }
  97399. if (_this._noControllerIsActive) {
  97400. _this._castRayAndSelectObject(_this._cameraGazer);
  97401. }
  97402. else {
  97403. _this._cameraGazer._gazeTracker.isVisible = false;
  97404. }
  97405. };
  97406. this._onNewGamepadConnected = function (gamepad) {
  97407. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  97408. if (gamepad.leftStick) {
  97409. gamepad.onleftstickchanged(function (stickValues) {
  97410. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  97411. // Listening to classic/xbox gamepad only if no VR controller is active
  97412. if ((!_this._leftController && !_this._rightController) ||
  97413. ((_this._leftController && !_this._leftController._activePointer) &&
  97414. (_this._rightController && !_this._rightController._activePointer))) {
  97415. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  97416. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  97417. }
  97418. }
  97419. });
  97420. }
  97421. if (gamepad.rightStick) {
  97422. gamepad.onrightstickchanged(function (stickValues) {
  97423. if (_this._teleportationInitialized) {
  97424. _this._checkRotate(stickValues, _this._cameraGazer);
  97425. }
  97426. });
  97427. }
  97428. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  97429. gamepad.onbuttondown(function (buttonPressed) {
  97430. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  97431. _this._cameraGazer._selectionPointerDown();
  97432. }
  97433. });
  97434. gamepad.onbuttonup(function (buttonPressed) {
  97435. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  97436. _this._cameraGazer._selectionPointerUp();
  97437. }
  97438. });
  97439. }
  97440. }
  97441. else {
  97442. var webVRController = gamepad;
  97443. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  97444. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  97445. _this._rightController = controller;
  97446. }
  97447. else {
  97448. _this._leftController = controller;
  97449. }
  97450. _this._tryEnableInteractionOnController(controller);
  97451. }
  97452. };
  97453. // 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
  97454. this._tryEnableInteractionOnController = function (controller) {
  97455. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  97456. _this._enableInteractionOnController(controller);
  97457. }
  97458. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  97459. _this._enableTeleportationOnController(controller);
  97460. }
  97461. };
  97462. this._onNewGamepadDisconnected = function (gamepad) {
  97463. if (gamepad instanceof BABYLON.WebVRController) {
  97464. if (gamepad.hand === "left" && _this._leftController != null) {
  97465. _this._leftController.dispose();
  97466. _this._leftController = null;
  97467. }
  97468. if (gamepad.hand === "right" && _this._rightController != null) {
  97469. _this._rightController.dispose();
  97470. _this._rightController = null;
  97471. }
  97472. }
  97473. };
  97474. this._workingVector = BABYLON.Vector3.Zero();
  97475. this._workingQuaternion = BABYLON.Quaternion.Identity();
  97476. this._workingMatrix = BABYLON.Matrix.Identity();
  97477. this._scene = scene;
  97478. this._canvas = scene.getEngine().getRenderingCanvas();
  97479. // Parse options
  97480. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  97481. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  97482. }
  97483. if (webVROptions.createDeviceOrientationCamera === undefined) {
  97484. webVROptions.createDeviceOrientationCamera = true;
  97485. }
  97486. if (webVROptions.laserToggle === undefined) {
  97487. webVROptions.laserToggle = true;
  97488. }
  97489. if (webVROptions.defaultHeight === undefined) {
  97490. webVROptions.defaultHeight = 1.7;
  97491. }
  97492. if (webVROptions.useCustomVRButton) {
  97493. this._useCustomVRButton = true;
  97494. if (webVROptions.customVRButton) {
  97495. this._btnVR = webVROptions.customVRButton;
  97496. }
  97497. }
  97498. if (webVROptions.rayLength) {
  97499. this._rayLength = webVROptions.rayLength;
  97500. }
  97501. this._defaultHeight = webVROptions.defaultHeight;
  97502. if (webVROptions.positionScale) {
  97503. this._rayLength *= webVROptions.positionScale;
  97504. this._defaultHeight *= webVROptions.positionScale;
  97505. }
  97506. this._hasEnteredVR = false;
  97507. // Set position
  97508. if (this._scene.activeCamera) {
  97509. this._position = this._scene.activeCamera.position.clone();
  97510. }
  97511. else {
  97512. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  97513. }
  97514. // Set non-vr camera
  97515. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  97516. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  97517. // Copy data from existing camera
  97518. if (this._scene.activeCamera) {
  97519. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  97520. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  97521. // Set rotation from previous camera
  97522. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  97523. var targetCamera = this._scene.activeCamera;
  97524. if (targetCamera.rotationQuaternion) {
  97525. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  97526. }
  97527. else {
  97528. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  97529. }
  97530. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  97531. }
  97532. }
  97533. this._scene.activeCamera = this._deviceOrientationCamera;
  97534. if (this._canvas) {
  97535. this._scene.activeCamera.attachControl(this._canvas);
  97536. }
  97537. }
  97538. else {
  97539. this._existingCamera = this._scene.activeCamera;
  97540. }
  97541. // Create VR cameras
  97542. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  97543. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  97544. }
  97545. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  97546. this._webVRCamera.useStandingMatrix();
  97547. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  97548. // Create default button
  97549. if (!this._useCustomVRButton) {
  97550. this._btnVR = document.createElement("BUTTON");
  97551. this._btnVR.className = "babylonVRicon";
  97552. this._btnVR.id = "babylonVRiconbtn";
  97553. this._btnVR.title = "Click to switch to VR";
  97554. 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) }";
  97555. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  97556. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  97557. // css += ".babylonVRicon.vrdisplaysupported { }";
  97558. // css += ".babylonVRicon.vrdisplayready { }";
  97559. // css += ".babylonVRicon.vrdisplayrequesting { }";
  97560. var style = document.createElement('style');
  97561. style.appendChild(document.createTextNode(css));
  97562. document.getElementsByTagName('head')[0].appendChild(style);
  97563. this.moveButtonToBottomRight();
  97564. }
  97565. // VR button click event
  97566. if (this._btnVR) {
  97567. this._btnVR.addEventListener("click", function () {
  97568. if (!_this.isInVRMode) {
  97569. _this.enterVR();
  97570. }
  97571. else {
  97572. _this.exitVR();
  97573. }
  97574. });
  97575. }
  97576. // Window events
  97577. window.addEventListener("resize", this._onResize);
  97578. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  97579. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  97580. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  97581. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  97582. document.onmsfullscreenchange = this._onFullscreenChange;
  97583. // Display vr button when headset is connected
  97584. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  97585. this.displayVRButton();
  97586. }
  97587. else {
  97588. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  97589. if (e.vrDisplay) {
  97590. _this.displayVRButton();
  97591. }
  97592. });
  97593. }
  97594. // Exiting VR mode using 'ESC' key on desktop
  97595. this._onKeyDown = function (event) {
  97596. if (event.keyCode === 27 && _this.isInVRMode) {
  97597. _this.exitVR();
  97598. }
  97599. };
  97600. document.addEventListener("keydown", this._onKeyDown);
  97601. // Exiting VR mode double tapping the touch screen
  97602. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  97603. if (_this.isInVRMode) {
  97604. _this.exitVR();
  97605. if (_this._fullscreenVRpresenting) {
  97606. _this._scene.getEngine().switchFullscreen(true);
  97607. }
  97608. }
  97609. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  97610. // Listen for WebVR display changes
  97611. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  97612. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  97613. this._onVRRequestPresentStart = function () {
  97614. _this._webVRrequesting = true;
  97615. _this.updateButtonVisibility();
  97616. };
  97617. this._onVRRequestPresentComplete = function (success) {
  97618. _this._webVRrequesting = false;
  97619. _this.updateButtonVisibility();
  97620. };
  97621. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  97622. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  97623. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  97624. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  97625. scene.onDisposeObservable.add(function () {
  97626. _this.dispose();
  97627. });
  97628. // Gamepad connection events
  97629. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  97630. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  97631. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  97632. this.updateButtonVisibility();
  97633. //create easing functions
  97634. this._circleEase = new BABYLON.CircleEase();
  97635. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  97636. if (this.webVROptions.floorMeshes) {
  97637. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  97638. }
  97639. }
  97640. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  97641. /** Return this.onEnteringVRObservable
  97642. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  97643. */
  97644. get: function () {
  97645. return this.onEnteringVRObservable;
  97646. },
  97647. enumerable: true,
  97648. configurable: true
  97649. });
  97650. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  97651. /** Return this.onExitingVRObservable
  97652. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  97653. */
  97654. get: function () {
  97655. return this.onExitingVRObservable;
  97656. },
  97657. enumerable: true,
  97658. configurable: true
  97659. });
  97660. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  97661. /** Return this.onControllerMeshLoadedObservable
  97662. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  97663. */
  97664. get: function () {
  97665. return this.onControllerMeshLoadedObservable;
  97666. },
  97667. enumerable: true,
  97668. configurable: true
  97669. });
  97670. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  97671. /**
  97672. * The mesh used to display where the user is going to teleport.
  97673. */
  97674. get: function () {
  97675. return this._teleportationTarget;
  97676. },
  97677. /**
  97678. * Sets the mesh to be used to display where the user is going to teleport.
  97679. */
  97680. set: function (value) {
  97681. if (value) {
  97682. value.name = "teleportationTarget";
  97683. this._isDefaultTeleportationTarget = false;
  97684. this._teleportationTarget = value;
  97685. }
  97686. },
  97687. enumerable: true,
  97688. configurable: true
  97689. });
  97690. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  97691. /**
  97692. * 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
  97693. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  97694. * See http://doc.babylonjs.com/resources/baking_transformations
  97695. */
  97696. get: function () {
  97697. return this._cameraGazer._gazeTracker;
  97698. },
  97699. set: function (value) {
  97700. if (value) {
  97701. // Dispose of existing meshes
  97702. if (this._cameraGazer._gazeTracker) {
  97703. this._cameraGazer._gazeTracker.dispose();
  97704. }
  97705. if (this._leftController && this._leftController._gazeTracker) {
  97706. this._leftController._gazeTracker.dispose();
  97707. }
  97708. if (this._rightController && this._rightController._gazeTracker) {
  97709. this._rightController._gazeTracker.dispose();
  97710. }
  97711. // Set and create gaze trackers on head and controllers
  97712. this._cameraGazer._gazeTracker = value;
  97713. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  97714. this._cameraGazer._gazeTracker.isPickable = false;
  97715. this._cameraGazer._gazeTracker.isVisible = false;
  97716. this._cameraGazer._gazeTracker.name = "gazeTracker";
  97717. if (this._leftController) {
  97718. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  97719. }
  97720. if (this._rightController) {
  97721. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  97722. }
  97723. }
  97724. },
  97725. enumerable: true,
  97726. configurable: true
  97727. });
  97728. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  97729. /**
  97730. * The gaze tracking mesh corresponding to the left controller
  97731. */
  97732. get: function () {
  97733. if (this._leftController) {
  97734. return this._leftController._gazeTracker;
  97735. }
  97736. return null;
  97737. },
  97738. enumerable: true,
  97739. configurable: true
  97740. });
  97741. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  97742. /**
  97743. * The gaze tracking mesh corresponding to the right controller
  97744. */
  97745. get: function () {
  97746. if (this._rightController) {
  97747. return this._rightController._gazeTracker;
  97748. }
  97749. return null;
  97750. },
  97751. enumerable: true,
  97752. configurable: true
  97753. });
  97754. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  97755. /**
  97756. * If the ray of the gaze should be displayed.
  97757. */
  97758. get: function () {
  97759. return this._displayGaze;
  97760. },
  97761. /**
  97762. * Sets if the ray of the gaze should be displayed.
  97763. */
  97764. set: function (value) {
  97765. this._displayGaze = value;
  97766. if (!value) {
  97767. this._cameraGazer._gazeTracker.isVisible = false;
  97768. if (this._leftController) {
  97769. this._leftController._gazeTracker.isVisible = false;
  97770. }
  97771. if (this._rightController) {
  97772. this._rightController._gazeTracker.isVisible = false;
  97773. }
  97774. }
  97775. },
  97776. enumerable: true,
  97777. configurable: true
  97778. });
  97779. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  97780. /**
  97781. * If the ray of the LaserPointer should be displayed.
  97782. */
  97783. get: function () {
  97784. return this._displayLaserPointer;
  97785. },
  97786. /**
  97787. * Sets if the ray of the LaserPointer should be displayed.
  97788. */
  97789. set: function (value) {
  97790. this._displayLaserPointer = value;
  97791. if (!value) {
  97792. if (this._rightController) {
  97793. this._rightController._deactivatePointer();
  97794. this._rightController._gazeTracker.isVisible = false;
  97795. }
  97796. if (this._leftController) {
  97797. this._leftController._deactivatePointer();
  97798. this._leftController._gazeTracker.isVisible = false;
  97799. }
  97800. }
  97801. else {
  97802. if (this._rightController) {
  97803. this._rightController._activatePointer();
  97804. }
  97805. if (this._leftController) {
  97806. this._leftController._activatePointer();
  97807. }
  97808. }
  97809. },
  97810. enumerable: true,
  97811. configurable: true
  97812. });
  97813. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  97814. /**
  97815. * The deviceOrientationCamera used as the camera when not in VR.
  97816. */
  97817. get: function () {
  97818. return this._deviceOrientationCamera;
  97819. },
  97820. enumerable: true,
  97821. configurable: true
  97822. });
  97823. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  97824. /**
  97825. * Based on the current WebVR support, returns the current VR camera used.
  97826. */
  97827. get: function () {
  97828. if (this._webVRready) {
  97829. return this._webVRCamera;
  97830. }
  97831. else {
  97832. return this._scene.activeCamera;
  97833. }
  97834. },
  97835. enumerable: true,
  97836. configurable: true
  97837. });
  97838. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  97839. /**
  97840. * The webVRCamera which is used when in VR.
  97841. */
  97842. get: function () {
  97843. return this._webVRCamera;
  97844. },
  97845. enumerable: true,
  97846. configurable: true
  97847. });
  97848. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  97849. /**
  97850. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  97851. */
  97852. get: function () {
  97853. return this._vrDeviceOrientationCamera;
  97854. },
  97855. enumerable: true,
  97856. configurable: true
  97857. });
  97858. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  97859. get: function () {
  97860. var result = this._cameraGazer._teleportationRequestInitiated
  97861. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  97862. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  97863. return result;
  97864. },
  97865. enumerable: true,
  97866. configurable: true
  97867. });
  97868. // Raised when one of the controller has loaded successfully its associated default mesh
  97869. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  97870. if (this._leftController && this._leftController.webVRController == webVRController) {
  97871. if (webVRController.mesh) {
  97872. this._leftController._setLaserPointerParent(webVRController.mesh);
  97873. }
  97874. }
  97875. if (this._rightController && this._rightController.webVRController == webVRController) {
  97876. if (webVRController.mesh) {
  97877. this._rightController._setLaserPointerParent(webVRController.mesh);
  97878. }
  97879. }
  97880. try {
  97881. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  97882. }
  97883. catch (err) {
  97884. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  97885. }
  97886. };
  97887. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  97888. /**
  97889. * Gets a value indicating if we are currently in VR mode.
  97890. */
  97891. get: function () {
  97892. return this._webVRpresenting || this._fullscreenVRpresenting;
  97893. },
  97894. enumerable: true,
  97895. configurable: true
  97896. });
  97897. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  97898. var vrDisplay = this._scene.getEngine().getVRDevice();
  97899. if (vrDisplay) {
  97900. var wasPresenting = this._webVRpresenting;
  97901. this._webVRpresenting = vrDisplay.isPresenting;
  97902. if (wasPresenting && !this._webVRpresenting)
  97903. this.exitVR();
  97904. }
  97905. else {
  97906. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  97907. }
  97908. this.updateButtonVisibility();
  97909. };
  97910. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  97911. this._webVRsupported = eventArgs.vrSupported;
  97912. this._webVRready = !!eventArgs.vrDisplay;
  97913. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  97914. this.updateButtonVisibility();
  97915. };
  97916. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  97917. if (this._canvas && !this._useCustomVRButton) {
  97918. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  97919. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  97920. }
  97921. };
  97922. VRExperienceHelper.prototype.displayVRButton = function () {
  97923. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  97924. document.body.appendChild(this._btnVR);
  97925. this._btnVRDisplayed = true;
  97926. }
  97927. };
  97928. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  97929. if (!this._btnVR || this._useCustomVRButton) {
  97930. return;
  97931. }
  97932. this._btnVR.className = "babylonVRicon";
  97933. if (this.isInVRMode) {
  97934. this._btnVR.className += " vrdisplaypresenting";
  97935. }
  97936. else {
  97937. if (this._webVRready)
  97938. this._btnVR.className += " vrdisplayready";
  97939. if (this._webVRsupported)
  97940. this._btnVR.className += " vrdisplaysupported";
  97941. if (this._webVRrequesting)
  97942. this._btnVR.className += " vrdisplayrequesting";
  97943. }
  97944. };
  97945. /**
  97946. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  97947. * Otherwise, will use the fullscreen API.
  97948. */
  97949. VRExperienceHelper.prototype.enterVR = function () {
  97950. if (this.onEnteringVRObservable) {
  97951. try {
  97952. this.onEnteringVRObservable.notifyObservers(this);
  97953. }
  97954. catch (err) {
  97955. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  97956. }
  97957. }
  97958. if (this._scene.activeCamera) {
  97959. this._position = this._scene.activeCamera.position.clone();
  97960. // make sure that we return to the last active camera
  97961. this._existingCamera = this._scene.activeCamera;
  97962. }
  97963. if (this._webVRrequesting)
  97964. return;
  97965. // If WebVR is supported and a headset is connected
  97966. if (this._webVRready) {
  97967. if (!this._webVRpresenting) {
  97968. this._webVRCamera.position = this._position;
  97969. this._scene.activeCamera = this._webVRCamera;
  97970. }
  97971. }
  97972. else if (this._vrDeviceOrientationCamera) {
  97973. this._vrDeviceOrientationCamera.position = this._position;
  97974. if (this._scene.activeCamera) {
  97975. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  97976. }
  97977. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  97978. this._scene.getEngine().switchFullscreen(true);
  97979. this.updateButtonVisibility();
  97980. }
  97981. if (this._scene.activeCamera && this._canvas) {
  97982. this._scene.activeCamera.attachControl(this._canvas);
  97983. }
  97984. if (this._interactionsEnabled) {
  97985. this._scene.registerBeforeRender(this.beforeRender);
  97986. }
  97987. this._hasEnteredVR = true;
  97988. };
  97989. /**
  97990. * Attempt to exit VR, or fullscreen.
  97991. */
  97992. VRExperienceHelper.prototype.exitVR = function () {
  97993. if (this._hasEnteredVR) {
  97994. if (this.onExitingVRObservable) {
  97995. try {
  97996. this.onExitingVRObservable.notifyObservers(this);
  97997. }
  97998. catch (err) {
  97999. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  98000. }
  98001. }
  98002. if (this._webVRpresenting) {
  98003. this._scene.getEngine().disableVR();
  98004. }
  98005. if (this._scene.activeCamera) {
  98006. this._position = this._scene.activeCamera.position.clone();
  98007. }
  98008. if (this._deviceOrientationCamera) {
  98009. this._deviceOrientationCamera.position = this._position;
  98010. this._scene.activeCamera = this._deviceOrientationCamera;
  98011. if (this._canvas) {
  98012. this._scene.activeCamera.attachControl(this._canvas);
  98013. }
  98014. }
  98015. else if (this._existingCamera) {
  98016. this._existingCamera.position = this._position;
  98017. this._scene.activeCamera = this._existingCamera;
  98018. }
  98019. this.updateButtonVisibility();
  98020. if (this._interactionsEnabled) {
  98021. this._scene.unregisterBeforeRender(this.beforeRender);
  98022. this._cameraGazer._gazeTracker.isVisible = false;
  98023. if (this._leftController) {
  98024. this._leftController._gazeTracker.isVisible = false;
  98025. }
  98026. if (this._rightController) {
  98027. this._rightController._gazeTracker.isVisible = false;
  98028. }
  98029. }
  98030. // resize to update width and height when exiting vr exits fullscreen
  98031. this._scene.getEngine().resize();
  98032. this._hasEnteredVR = false;
  98033. }
  98034. };
  98035. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  98036. /**
  98037. * The position of the vr experience helper.
  98038. */
  98039. get: function () {
  98040. return this._position;
  98041. },
  98042. /**
  98043. * Sets the position of the vr experience helper.
  98044. */
  98045. set: function (value) {
  98046. this._position = value;
  98047. if (this._scene.activeCamera) {
  98048. this._scene.activeCamera.position = value;
  98049. }
  98050. },
  98051. enumerable: true,
  98052. configurable: true
  98053. });
  98054. /**
  98055. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  98056. */
  98057. VRExperienceHelper.prototype.enableInteractions = function () {
  98058. var _this = this;
  98059. if (!this._interactionsEnabled) {
  98060. this._interactionsRequested = true;
  98061. if (this._leftController) {
  98062. this._enableInteractionOnController(this._leftController);
  98063. }
  98064. if (this._rightController) {
  98065. this._enableInteractionOnController(this._rightController);
  98066. }
  98067. this.raySelectionPredicate = function (mesh) {
  98068. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  98069. };
  98070. this.meshSelectionPredicate = function (mesh) {
  98071. return true;
  98072. };
  98073. this._raySelectionPredicate = function (mesh) {
  98074. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  98075. && mesh.name.indexOf("teleportationTarget") === -1
  98076. && mesh.name.indexOf("torusTeleportation") === -1)) {
  98077. return _this.raySelectionPredicate(mesh);
  98078. }
  98079. return false;
  98080. };
  98081. this._interactionsEnabled = true;
  98082. }
  98083. };
  98084. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  98085. get: function () {
  98086. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  98087. },
  98088. enumerable: true,
  98089. configurable: true
  98090. });
  98091. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  98092. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  98093. if (this._floorMeshesCollection[i].id === mesh.id) {
  98094. return true;
  98095. }
  98096. }
  98097. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  98098. return true;
  98099. }
  98100. return false;
  98101. };
  98102. /**
  98103. * Adds a floor mesh to be used for teleportation.
  98104. * @param floorMesh the mesh to be used for teleportation.
  98105. */
  98106. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  98107. if (!this._floorMeshesCollection) {
  98108. return;
  98109. }
  98110. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  98111. return;
  98112. }
  98113. this._floorMeshesCollection.push(floorMesh);
  98114. };
  98115. /**
  98116. * Removes a floor mesh from being used for teleportation.
  98117. * @param floorMesh the mesh to be removed.
  98118. */
  98119. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  98120. if (!this._floorMeshesCollection) {
  98121. return;
  98122. }
  98123. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  98124. if (meshIndex !== -1) {
  98125. this._floorMeshesCollection.splice(meshIndex, 1);
  98126. }
  98127. };
  98128. /**
  98129. * Enables interactions and teleportation using the VR controllers and gaze.
  98130. * @param vrTeleportationOptions options to modify teleportation behavior.
  98131. */
  98132. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  98133. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  98134. if (!this._teleportationInitialized) {
  98135. this._teleportationRequested = true;
  98136. this.enableInteractions();
  98137. if (vrTeleportationOptions.floorMeshName) {
  98138. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  98139. }
  98140. if (vrTeleportationOptions.floorMeshes) {
  98141. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  98142. }
  98143. if (this._leftController != null) {
  98144. this._enableTeleportationOnController(this._leftController);
  98145. }
  98146. if (this._rightController != null) {
  98147. this._enableTeleportationOnController(this._rightController);
  98148. }
  98149. // Creates an image processing post process for the vignette not relying
  98150. // on the main scene configuration for image processing to reduce setup and spaces
  98151. // (gamma/linear) conflicts.
  98152. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  98153. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  98154. imageProcessingConfiguration.vignetteEnabled = true;
  98155. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  98156. this._webVRCamera.detachPostProcess(this._postProcessMove);
  98157. this._teleportationInitialized = true;
  98158. if (this._isDefaultTeleportationTarget) {
  98159. this._createTeleportationCircles();
  98160. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  98161. }
  98162. }
  98163. };
  98164. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  98165. var _this = this;
  98166. var controllerMesh = controller.webVRController.mesh;
  98167. if (controllerMesh) {
  98168. controller._interactionsEnabled = true;
  98169. controller._activatePointer();
  98170. if (this.webVROptions.laserToggle) {
  98171. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  98172. // Enabling / disabling laserPointer
  98173. if (_this._displayLaserPointer && stateObject.value === 1) {
  98174. if (controller._activePointer) {
  98175. controller._deactivatePointer();
  98176. }
  98177. else {
  98178. controller._activatePointer();
  98179. }
  98180. if (_this.displayGaze) {
  98181. controller._gazeTracker.isVisible = controller._activePointer;
  98182. }
  98183. }
  98184. });
  98185. }
  98186. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  98187. var gazer = controller;
  98188. if (_this._noControllerIsActive) {
  98189. gazer = _this._cameraGazer;
  98190. }
  98191. if (!gazer._pointerDownOnMeshAsked) {
  98192. if (stateObject.value > _this._padSensibilityUp) {
  98193. gazer._selectionPointerDown();
  98194. }
  98195. }
  98196. else if (stateObject.value < _this._padSensibilityDown) {
  98197. gazer._selectionPointerUp();
  98198. }
  98199. });
  98200. }
  98201. };
  98202. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  98203. // Dont teleport if another gaze already requested teleportation
  98204. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  98205. return;
  98206. }
  98207. if (!gazer._teleportationRequestInitiated) {
  98208. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  98209. gazer._activatePointer();
  98210. gazer._teleportationRequestInitiated = true;
  98211. }
  98212. }
  98213. else {
  98214. // Listening to the proper controller values changes to confirm teleportation
  98215. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  98216. if (this._teleportActive) {
  98217. this.teleportCamera(this._haloCenter);
  98218. }
  98219. gazer._teleportationRequestInitiated = false;
  98220. }
  98221. }
  98222. };
  98223. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  98224. // Only rotate when user is not currently selecting a teleportation location
  98225. if (gazer._teleportationRequestInitiated) {
  98226. return;
  98227. }
  98228. if (!gazer._rotationLeftAsked) {
  98229. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  98230. gazer._rotationLeftAsked = true;
  98231. if (this._rotationAllowed) {
  98232. this._rotateCamera(false);
  98233. }
  98234. }
  98235. }
  98236. else {
  98237. if (stateObject.x > -this._padSensibilityDown) {
  98238. gazer._rotationLeftAsked = false;
  98239. }
  98240. }
  98241. if (!gazer._rotationRightAsked) {
  98242. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  98243. gazer._rotationRightAsked = true;
  98244. if (this._rotationAllowed) {
  98245. this._rotateCamera(true);
  98246. }
  98247. }
  98248. }
  98249. else {
  98250. if (stateObject.x < this._padSensibilityDown) {
  98251. gazer._rotationRightAsked = false;
  98252. }
  98253. }
  98254. };
  98255. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  98256. // Only teleport backwards when user is not currently selecting a teleportation location
  98257. if (gazer._teleportationRequestInitiated) {
  98258. return;
  98259. }
  98260. // Teleport backwards
  98261. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  98262. if (!gazer._teleportationBackRequestInitiated) {
  98263. if (!this.currentVRCamera) {
  98264. return;
  98265. }
  98266. // Get rotation and position of the current camera
  98267. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  98268. var position = this.currentVRCamera.position;
  98269. // If the camera has device position, use that instead
  98270. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  98271. rotation = this.currentVRCamera.deviceRotationQuaternion;
  98272. position = this.currentVRCamera.devicePosition;
  98273. }
  98274. // Get matrix with only the y rotation of the device rotation
  98275. rotation.toEulerAnglesToRef(this._workingVector);
  98276. this._workingVector.z = 0;
  98277. this._workingVector.x = 0;
  98278. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  98279. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  98280. // Rotate backwards ray by device rotation to cast at the ground behind the user
  98281. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  98282. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  98283. var ray = new BABYLON.Ray(position, this._workingVector);
  98284. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  98285. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  98286. this.teleportCamera(hit.pickedPoint);
  98287. }
  98288. gazer._teleportationBackRequestInitiated = true;
  98289. }
  98290. }
  98291. else {
  98292. gazer._teleportationBackRequestInitiated = false;
  98293. }
  98294. };
  98295. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  98296. var _this = this;
  98297. var controllerMesh = controller.webVRController.mesh;
  98298. if (controllerMesh) {
  98299. if (!controller._interactionsEnabled) {
  98300. this._enableInteractionOnController(controller);
  98301. }
  98302. controller._interactionsEnabled = true;
  98303. controller._teleportationEnabled = true;
  98304. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  98305. controller._dpadPressed = false;
  98306. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  98307. controller._dpadPressed = stateObject.pressed;
  98308. if (!controller._dpadPressed) {
  98309. controller._rotationLeftAsked = false;
  98310. controller._rotationRightAsked = false;
  98311. controller._teleportationBackRequestInitiated = false;
  98312. }
  98313. });
  98314. }
  98315. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  98316. if (_this.teleportationEnabled) {
  98317. _this._checkTeleportBackwards(stateObject, controller);
  98318. _this._checkTeleportWithRay(stateObject, controller);
  98319. }
  98320. _this._checkRotate(stateObject, controller);
  98321. });
  98322. }
  98323. };
  98324. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  98325. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  98326. this._teleportationTarget.isPickable = false;
  98327. var length = 512;
  98328. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  98329. dynamicTexture.hasAlpha = true;
  98330. var context = dynamicTexture.getContext();
  98331. var centerX = length / 2;
  98332. var centerY = length / 2;
  98333. var radius = 200;
  98334. context.beginPath();
  98335. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  98336. context.fillStyle = this._teleportationFillColor;
  98337. context.fill();
  98338. context.lineWidth = 10;
  98339. context.strokeStyle = this._teleportationBorderColor;
  98340. context.stroke();
  98341. context.closePath();
  98342. dynamicTexture.update();
  98343. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  98344. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  98345. this._teleportationTarget.material = teleportationCircleMaterial;
  98346. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  98347. torus.isPickable = false;
  98348. torus.parent = this._teleportationTarget;
  98349. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  98350. var keys = [];
  98351. keys.push({
  98352. frame: 0,
  98353. value: 0
  98354. });
  98355. keys.push({
  98356. frame: 30,
  98357. value: 0.4
  98358. });
  98359. keys.push({
  98360. frame: 60,
  98361. value: 0
  98362. });
  98363. animationInnerCircle.setKeys(keys);
  98364. var easingFunction = new BABYLON.SineEase();
  98365. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  98366. animationInnerCircle.setEasingFunction(easingFunction);
  98367. torus.animations = [];
  98368. torus.animations.push(animationInnerCircle);
  98369. this._scene.beginAnimation(torus, 0, 60, true);
  98370. this._hideTeleportationTarget();
  98371. };
  98372. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  98373. this._teleportActive = true;
  98374. if (this._teleportationInitialized) {
  98375. this._teleportationTarget.isVisible = true;
  98376. if (this._isDefaultTeleportationTarget) {
  98377. this._teleportationTarget.getChildren()[0].isVisible = true;
  98378. }
  98379. }
  98380. };
  98381. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  98382. this._teleportActive = false;
  98383. if (this._teleportationInitialized) {
  98384. this._teleportationTarget.isVisible = false;
  98385. if (this._isDefaultTeleportationTarget) {
  98386. this._teleportationTarget.getChildren()[0].isVisible = false;
  98387. }
  98388. }
  98389. };
  98390. VRExperienceHelper.prototype._rotateCamera = function (right) {
  98391. var _this = this;
  98392. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  98393. return;
  98394. }
  98395. if (right) {
  98396. this._rotationAngle++;
  98397. }
  98398. else {
  98399. this._rotationAngle--;
  98400. }
  98401. this.currentVRCamera.animations = [];
  98402. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  98403. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98404. var animationRotationKeys = [];
  98405. animationRotationKeys.push({
  98406. frame: 0,
  98407. value: this.currentVRCamera.rotationQuaternion
  98408. });
  98409. animationRotationKeys.push({
  98410. frame: 6,
  98411. value: target
  98412. });
  98413. animationRotation.setKeys(animationRotationKeys);
  98414. animationRotation.setEasingFunction(this._circleEase);
  98415. this.currentVRCamera.animations.push(animationRotation);
  98416. this._postProcessMove.animations = [];
  98417. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98418. var vignetteWeightKeys = [];
  98419. vignetteWeightKeys.push({
  98420. frame: 0,
  98421. value: 0
  98422. });
  98423. vignetteWeightKeys.push({
  98424. frame: 3,
  98425. value: 4
  98426. });
  98427. vignetteWeightKeys.push({
  98428. frame: 6,
  98429. value: 0
  98430. });
  98431. animationPP.setKeys(vignetteWeightKeys);
  98432. animationPP.setEasingFunction(this._circleEase);
  98433. this._postProcessMove.animations.push(animationPP);
  98434. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98435. var vignetteStretchKeys = [];
  98436. vignetteStretchKeys.push({
  98437. frame: 0,
  98438. value: 0
  98439. });
  98440. vignetteStretchKeys.push({
  98441. frame: 3,
  98442. value: 10
  98443. });
  98444. vignetteStretchKeys.push({
  98445. frame: 6,
  98446. value: 0
  98447. });
  98448. animationPP2.setKeys(vignetteStretchKeys);
  98449. animationPP2.setEasingFunction(this._circleEase);
  98450. this._postProcessMove.animations.push(animationPP2);
  98451. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  98452. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  98453. this._postProcessMove.samples = 4;
  98454. this._webVRCamera.attachPostProcess(this._postProcessMove);
  98455. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  98456. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  98457. });
  98458. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  98459. };
  98460. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  98461. if (hit.pickedPoint) {
  98462. if (gazer._teleportationRequestInitiated) {
  98463. this._displayTeleportationTarget();
  98464. this._haloCenter.copyFrom(hit.pickedPoint);
  98465. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  98466. }
  98467. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  98468. if (pickNormal) {
  98469. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  98470. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  98471. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  98472. }
  98473. this._teleportationTarget.position.y += 0.1;
  98474. }
  98475. };
  98476. /**
  98477. * Teleports the users feet to the desired location
  98478. * @param location The location where the user's feet should be placed
  98479. */
  98480. VRExperienceHelper.prototype.teleportCamera = function (location) {
  98481. var _this = this;
  98482. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  98483. return;
  98484. }
  98485. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  98486. // offset of the headset from the anchor.
  98487. if (this.webVRCamera.leftCamera) {
  98488. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  98489. this._workingVector.subtractInPlace(this.webVRCamera.position);
  98490. location.subtractToRef(this._workingVector, this._workingVector);
  98491. }
  98492. else {
  98493. this._workingVector.copyFrom(location);
  98494. }
  98495. // Add height to account for user's height offset
  98496. if (this.isInVRMode) {
  98497. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  98498. }
  98499. else {
  98500. this._workingVector.y += this._defaultHeight;
  98501. }
  98502. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  98503. // Create animation from the camera's position to the new location
  98504. this.currentVRCamera.animations = [];
  98505. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98506. var animationCameraTeleportationKeys = [{
  98507. frame: 0,
  98508. value: this.currentVRCamera.position
  98509. },
  98510. {
  98511. frame: 11,
  98512. value: this._workingVector
  98513. }
  98514. ];
  98515. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  98516. animationCameraTeleportation.setEasingFunction(this._circleEase);
  98517. this.currentVRCamera.animations.push(animationCameraTeleportation);
  98518. this._postProcessMove.animations = [];
  98519. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98520. var vignetteWeightKeys = [];
  98521. vignetteWeightKeys.push({
  98522. frame: 0,
  98523. value: 0
  98524. });
  98525. vignetteWeightKeys.push({
  98526. frame: 5,
  98527. value: 8
  98528. });
  98529. vignetteWeightKeys.push({
  98530. frame: 11,
  98531. value: 0
  98532. });
  98533. animationPP.setKeys(vignetteWeightKeys);
  98534. this._postProcessMove.animations.push(animationPP);
  98535. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98536. var vignetteStretchKeys = [];
  98537. vignetteStretchKeys.push({
  98538. frame: 0,
  98539. value: 0
  98540. });
  98541. vignetteStretchKeys.push({
  98542. frame: 5,
  98543. value: 10
  98544. });
  98545. vignetteStretchKeys.push({
  98546. frame: 11,
  98547. value: 0
  98548. });
  98549. animationPP2.setKeys(vignetteStretchKeys);
  98550. this._postProcessMove.animations.push(animationPP2);
  98551. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  98552. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  98553. this._webVRCamera.attachPostProcess(this._postProcessMove);
  98554. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  98555. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  98556. });
  98557. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  98558. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  98559. });
  98560. this._hideTeleportationTarget();
  98561. };
  98562. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  98563. if (normal) {
  98564. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  98565. if (angle < Math.PI / 2) {
  98566. normal.scaleInPlace(-1);
  98567. }
  98568. }
  98569. return normal;
  98570. };
  98571. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  98572. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  98573. return;
  98574. }
  98575. var ray = gazer._getForwardRay(this._rayLength);
  98576. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  98577. if (hit) {
  98578. // Populate the contrllers mesh that can be used for drag/drop
  98579. if (gazer._laserPointer) {
  98580. hit.originMesh = gazer._laserPointer.parent;
  98581. }
  98582. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  98583. }
  98584. gazer._currentHit = hit;
  98585. // Moving the gazeTracker on the mesh face targetted
  98586. if (hit && hit.pickedPoint) {
  98587. if (this._displayGaze) {
  98588. var multiplier = 1;
  98589. gazer._gazeTracker.isVisible = true;
  98590. if (gazer._isActionableMesh) {
  98591. multiplier = 3;
  98592. }
  98593. if (this.updateGazeTrackerScale) {
  98594. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  98595. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  98596. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  98597. }
  98598. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  98599. // To avoid z-fighting
  98600. var deltaFighting = 0.002;
  98601. if (pickNormal) {
  98602. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  98603. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  98604. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  98605. }
  98606. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  98607. if (gazer._gazeTracker.position.x < 0) {
  98608. gazer._gazeTracker.position.x += deltaFighting;
  98609. }
  98610. else {
  98611. gazer._gazeTracker.position.x -= deltaFighting;
  98612. }
  98613. if (gazer._gazeTracker.position.y < 0) {
  98614. gazer._gazeTracker.position.y += deltaFighting;
  98615. }
  98616. else {
  98617. gazer._gazeTracker.position.y -= deltaFighting;
  98618. }
  98619. if (gazer._gazeTracker.position.z < 0) {
  98620. gazer._gazeTracker.position.z += deltaFighting;
  98621. }
  98622. else {
  98623. gazer._gazeTracker.position.z -= deltaFighting;
  98624. }
  98625. }
  98626. // Changing the size of the laser pointer based on the distance from the targetted point
  98627. gazer._updatePointerDistance(hit.distance);
  98628. }
  98629. else {
  98630. gazer._updatePointerDistance();
  98631. gazer._gazeTracker.isVisible = false;
  98632. }
  98633. if (hit && hit.pickedMesh) {
  98634. // The object selected is the floor, we're in a teleportation scenario
  98635. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  98636. // Moving the teleportation area to this targetted point
  98637. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  98638. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  98639. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  98640. }
  98641. gazer._currentMeshSelected = null;
  98642. if (gazer._teleportationRequestInitiated) {
  98643. this._moveTeleportationSelectorTo(hit, gazer, ray);
  98644. }
  98645. return;
  98646. }
  98647. // If not, we're in a selection scenario
  98648. //this._teleportationAllowed = false;
  98649. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  98650. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  98651. this.onNewMeshPicked.notifyObservers(hit);
  98652. gazer._currentMeshSelected = hit.pickedMesh;
  98653. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  98654. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  98655. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  98656. gazer._isActionableMesh = true;
  98657. }
  98658. else {
  98659. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98660. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98661. gazer._isActionableMesh = false;
  98662. }
  98663. try {
  98664. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  98665. }
  98666. catch (err) {
  98667. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  98668. }
  98669. }
  98670. else {
  98671. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  98672. gazer._currentMeshSelected = null;
  98673. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98674. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98675. }
  98676. }
  98677. }
  98678. else {
  98679. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  98680. gazer._currentMeshSelected = null;
  98681. //this._teleportationAllowed = false;
  98682. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98683. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98684. }
  98685. };
  98686. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  98687. if (mesh) {
  98688. this.onSelectedMeshUnselected.notifyObservers(mesh);
  98689. }
  98690. };
  98691. /**
  98692. * Sets the color of the laser ray from the vr controllers.
  98693. * @param color new color for the ray.
  98694. */
  98695. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  98696. if (this._leftController) {
  98697. this._leftController._setLaserPointerColor(color);
  98698. }
  98699. if (this._rightController) {
  98700. this._rightController._setLaserPointerColor(color);
  98701. }
  98702. };
  98703. /**
  98704. * Sets the color of the ray from the vr headsets gaze.
  98705. * @param color new color for the ray.
  98706. */
  98707. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  98708. if (!this._cameraGazer._gazeTracker.material) {
  98709. return;
  98710. }
  98711. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  98712. if (this._leftController) {
  98713. this._leftController._gazeTracker.material.emissiveColor = color;
  98714. }
  98715. if (this._rightController) {
  98716. this._rightController._gazeTracker.material.emissiveColor = color;
  98717. }
  98718. };
  98719. /**
  98720. * Exits VR and disposes of the vr experience helper
  98721. */
  98722. VRExperienceHelper.prototype.dispose = function () {
  98723. if (this.isInVRMode) {
  98724. this.exitVR();
  98725. }
  98726. if (this._postProcessMove) {
  98727. this._postProcessMove.dispose();
  98728. }
  98729. if (this._webVRCamera) {
  98730. this._webVRCamera.dispose();
  98731. }
  98732. if (this._vrDeviceOrientationCamera) {
  98733. this._vrDeviceOrientationCamera.dispose();
  98734. }
  98735. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  98736. document.body.removeChild(this._btnVR);
  98737. }
  98738. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  98739. this._deviceOrientationCamera.dispose();
  98740. }
  98741. if (this._cameraGazer) {
  98742. this._cameraGazer.dispose();
  98743. }
  98744. if (this._leftController) {
  98745. this._leftController.dispose();
  98746. }
  98747. if (this._rightController) {
  98748. this._rightController.dispose();
  98749. }
  98750. if (this._teleportationTarget) {
  98751. this._teleportationTarget.dispose();
  98752. }
  98753. this._floorMeshesCollection = [];
  98754. document.removeEventListener("keydown", this._onKeyDown);
  98755. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  98756. window.removeEventListener("resize", this._onResize);
  98757. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  98758. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  98759. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  98760. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  98761. document.onmsfullscreenchange = null;
  98762. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  98763. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  98764. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  98765. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  98766. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  98767. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  98768. this._scene.unregisterBeforeRender(this.beforeRender);
  98769. };
  98770. /**
  98771. * Gets the name of the VRExperienceHelper class
  98772. * @returns "VRExperienceHelper"
  98773. */
  98774. VRExperienceHelper.prototype.getClassName = function () {
  98775. return "VRExperienceHelper";
  98776. };
  98777. return VRExperienceHelper;
  98778. }());
  98779. BABYLON.VRExperienceHelper = VRExperienceHelper;
  98780. })(BABYLON || (BABYLON = {}));
  98781. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  98782. // Mainly based on these 2 articles :
  98783. // 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
  98784. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  98785. var BABYLON;
  98786. (function (BABYLON) {
  98787. /**
  98788. * Defines the potential axis of a Joystick
  98789. */
  98790. var JoystickAxis;
  98791. (function (JoystickAxis) {
  98792. /** X axis */
  98793. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  98794. /** Y axis */
  98795. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  98796. /** Z axis */
  98797. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  98798. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  98799. /**
  98800. * Class used to define virtual joystick (used in touch mode)
  98801. */
  98802. var VirtualJoystick = /** @class */ (function () {
  98803. /**
  98804. * Creates a new virtual joystick
  98805. * @param leftJoystick defines that the joystick is for left hand (false by default)
  98806. */
  98807. function VirtualJoystick(leftJoystick) {
  98808. var _this = this;
  98809. if (leftJoystick) {
  98810. this._leftJoystick = true;
  98811. }
  98812. else {
  98813. this._leftJoystick = false;
  98814. }
  98815. VirtualJoystick._globalJoystickIndex++;
  98816. // By default left & right arrow keys are moving the X
  98817. // and up & down keys are moving the Y
  98818. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  98819. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  98820. this.reverseLeftRight = false;
  98821. this.reverseUpDown = false;
  98822. // collections of pointers
  98823. this._touches = new BABYLON.StringDictionary();
  98824. this.deltaPosition = BABYLON.Vector3.Zero();
  98825. this._joystickSensibility = 25;
  98826. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  98827. this._onResize = function (evt) {
  98828. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  98829. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  98830. if (VirtualJoystick.vjCanvas) {
  98831. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  98832. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  98833. }
  98834. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  98835. };
  98836. // injecting a canvas element on top of the canvas 3D game
  98837. if (!VirtualJoystick.vjCanvas) {
  98838. window.addEventListener("resize", this._onResize, false);
  98839. VirtualJoystick.vjCanvas = document.createElement("canvas");
  98840. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  98841. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  98842. VirtualJoystick.vjCanvas.width = window.innerWidth;
  98843. VirtualJoystick.vjCanvas.height = window.innerHeight;
  98844. VirtualJoystick.vjCanvas.style.width = "100%";
  98845. VirtualJoystick.vjCanvas.style.height = "100%";
  98846. VirtualJoystick.vjCanvas.style.position = "absolute";
  98847. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  98848. VirtualJoystick.vjCanvas.style.top = "0px";
  98849. VirtualJoystick.vjCanvas.style.left = "0px";
  98850. VirtualJoystick.vjCanvas.style.zIndex = "5";
  98851. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  98852. // Support for jQuery PEP polyfill
  98853. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  98854. var context = VirtualJoystick.vjCanvas.getContext('2d');
  98855. if (!context) {
  98856. throw new Error("Unable to create canvas for virtual joystick");
  98857. }
  98858. VirtualJoystick.vjCanvasContext = context;
  98859. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  98860. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  98861. document.body.appendChild(VirtualJoystick.vjCanvas);
  98862. }
  98863. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  98864. this.pressed = false;
  98865. // default joystick color
  98866. this._joystickColor = "cyan";
  98867. this._joystickPointerID = -1;
  98868. // current joystick position
  98869. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  98870. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  98871. // origin joystick position
  98872. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  98873. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  98874. this._onPointerDownHandlerRef = function (evt) {
  98875. _this._onPointerDown(evt);
  98876. };
  98877. this._onPointerMoveHandlerRef = function (evt) {
  98878. _this._onPointerMove(evt);
  98879. };
  98880. this._onPointerUpHandlerRef = function (evt) {
  98881. _this._onPointerUp(evt);
  98882. };
  98883. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  98884. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  98885. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  98886. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  98887. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  98888. evt.preventDefault(); // Disables system menu
  98889. }, false);
  98890. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  98891. }
  98892. /**
  98893. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  98894. * @param newJoystickSensibility defines the new sensibility
  98895. */
  98896. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  98897. this._joystickSensibility = newJoystickSensibility;
  98898. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  98899. };
  98900. VirtualJoystick.prototype._onPointerDown = function (e) {
  98901. var positionOnScreenCondition;
  98902. e.preventDefault();
  98903. if (this._leftJoystick === true) {
  98904. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  98905. }
  98906. else {
  98907. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  98908. }
  98909. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  98910. // First contact will be dedicated to the virtual joystick
  98911. this._joystickPointerID = e.pointerId;
  98912. this._joystickPointerStartPos.x = e.clientX;
  98913. this._joystickPointerStartPos.y = e.clientY;
  98914. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  98915. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  98916. this._deltaJoystickVector.x = 0;
  98917. this._deltaJoystickVector.y = 0;
  98918. this.pressed = true;
  98919. this._touches.add(e.pointerId.toString(), e);
  98920. }
  98921. else {
  98922. // You can only trigger the action buttons with a joystick declared
  98923. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  98924. this._action();
  98925. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  98926. }
  98927. }
  98928. };
  98929. VirtualJoystick.prototype._onPointerMove = function (e) {
  98930. // If the current pointer is the one associated to the joystick (first touch contact)
  98931. if (this._joystickPointerID == e.pointerId) {
  98932. this._joystickPointerPos.x = e.clientX;
  98933. this._joystickPointerPos.y = e.clientY;
  98934. this._deltaJoystickVector = this._joystickPointerPos.clone();
  98935. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  98936. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  98937. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  98938. switch (this._axisTargetedByLeftAndRight) {
  98939. case JoystickAxis.X:
  98940. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  98941. break;
  98942. case JoystickAxis.Y:
  98943. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  98944. break;
  98945. case JoystickAxis.Z:
  98946. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  98947. break;
  98948. }
  98949. var directionUpDown = this.reverseUpDown ? 1 : -1;
  98950. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  98951. switch (this._axisTargetedByUpAndDown) {
  98952. case JoystickAxis.X:
  98953. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  98954. break;
  98955. case JoystickAxis.Y:
  98956. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  98957. break;
  98958. case JoystickAxis.Z:
  98959. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  98960. break;
  98961. }
  98962. }
  98963. else {
  98964. var data = this._touches.get(e.pointerId.toString());
  98965. if (data) {
  98966. data.x = e.clientX;
  98967. data.y = e.clientY;
  98968. }
  98969. }
  98970. };
  98971. VirtualJoystick.prototype._onPointerUp = function (e) {
  98972. if (this._joystickPointerID == e.pointerId) {
  98973. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  98974. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  98975. this._joystickPointerID = -1;
  98976. this.pressed = false;
  98977. }
  98978. else {
  98979. var touch = this._touches.get(e.pointerId.toString());
  98980. if (touch) {
  98981. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  98982. }
  98983. }
  98984. this._deltaJoystickVector.x = 0;
  98985. this._deltaJoystickVector.y = 0;
  98986. this._touches.remove(e.pointerId.toString());
  98987. };
  98988. /**
  98989. * Change the color of the virtual joystick
  98990. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  98991. */
  98992. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  98993. this._joystickColor = newColor;
  98994. };
  98995. /**
  98996. * Defines a callback to call when the joystick is touched
  98997. * @param action defines the callback
  98998. */
  98999. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  99000. this._action = action;
  99001. };
  99002. /**
  99003. * Defines which axis you'd like to control for left & right
  99004. * @param axis defines the axis to use
  99005. */
  99006. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  99007. switch (axis) {
  99008. case JoystickAxis.X:
  99009. case JoystickAxis.Y:
  99010. case JoystickAxis.Z:
  99011. this._axisTargetedByLeftAndRight = axis;
  99012. break;
  99013. default:
  99014. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  99015. break;
  99016. }
  99017. };
  99018. /**
  99019. * Defines which axis you'd like to control for up & down
  99020. * @param axis defines the axis to use
  99021. */
  99022. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  99023. switch (axis) {
  99024. case JoystickAxis.X:
  99025. case JoystickAxis.Y:
  99026. case JoystickAxis.Z:
  99027. this._axisTargetedByUpAndDown = axis;
  99028. break;
  99029. default:
  99030. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  99031. break;
  99032. }
  99033. };
  99034. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  99035. var _this = this;
  99036. if (this.pressed) {
  99037. this._touches.forEach(function (key, touch) {
  99038. if (touch.pointerId === _this._joystickPointerID) {
  99039. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  99040. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  99041. VirtualJoystick.vjCanvasContext.beginPath();
  99042. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99043. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99044. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  99045. VirtualJoystick.vjCanvasContext.stroke();
  99046. VirtualJoystick.vjCanvasContext.closePath();
  99047. VirtualJoystick.vjCanvasContext.beginPath();
  99048. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99049. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  99050. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  99051. VirtualJoystick.vjCanvasContext.stroke();
  99052. VirtualJoystick.vjCanvasContext.closePath();
  99053. VirtualJoystick.vjCanvasContext.beginPath();
  99054. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  99055. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  99056. VirtualJoystick.vjCanvasContext.stroke();
  99057. VirtualJoystick.vjCanvasContext.closePath();
  99058. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  99059. }
  99060. else {
  99061. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  99062. VirtualJoystick.vjCanvasContext.beginPath();
  99063. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  99064. VirtualJoystick.vjCanvasContext.beginPath();
  99065. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  99066. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99067. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  99068. VirtualJoystick.vjCanvasContext.stroke();
  99069. VirtualJoystick.vjCanvasContext.closePath();
  99070. touch.prevX = touch.x;
  99071. touch.prevY = touch.y;
  99072. }
  99073. ;
  99074. });
  99075. }
  99076. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  99077. };
  99078. /**
  99079. * Release internal HTML canvas
  99080. */
  99081. VirtualJoystick.prototype.releaseCanvas = function () {
  99082. if (VirtualJoystick.vjCanvas) {
  99083. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  99084. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  99085. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  99086. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  99087. window.removeEventListener("resize", this._onResize);
  99088. document.body.removeChild(VirtualJoystick.vjCanvas);
  99089. VirtualJoystick.vjCanvas = null;
  99090. }
  99091. };
  99092. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  99093. VirtualJoystick._globalJoystickIndex = 0;
  99094. return VirtualJoystick;
  99095. }());
  99096. BABYLON.VirtualJoystick = VirtualJoystick;
  99097. })(BABYLON || (BABYLON = {}));
  99098. //# sourceMappingURL=babylon.virtualJoystick.js.map
  99099. var BABYLON;
  99100. (function (BABYLON) {
  99101. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  99102. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  99103. });
  99104. // We're mainly based on the logic defined into the FreeCamera code
  99105. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  99106. __extends(VirtualJoysticksCamera, _super);
  99107. function VirtualJoysticksCamera(name, position, scene) {
  99108. var _this = _super.call(this, name, position, scene) || this;
  99109. _this.inputs.addVirtualJoystick();
  99110. return _this;
  99111. }
  99112. VirtualJoysticksCamera.prototype.getClassName = function () {
  99113. return "VirtualJoysticksCamera";
  99114. };
  99115. return VirtualJoysticksCamera;
  99116. }(BABYLON.FreeCamera));
  99117. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  99118. })(BABYLON || (BABYLON = {}));
  99119. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  99120. var BABYLON;
  99121. (function (BABYLON) {
  99122. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  99123. function FreeCameraVirtualJoystickInput() {
  99124. }
  99125. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  99126. return this._leftjoystick;
  99127. };
  99128. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  99129. return this._rightjoystick;
  99130. };
  99131. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  99132. if (this._leftjoystick) {
  99133. var camera = this.camera;
  99134. var speed = camera._computeLocalCameraSpeed() * 50;
  99135. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  99136. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  99137. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  99138. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  99139. if (!this._leftjoystick.pressed) {
  99140. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  99141. }
  99142. if (!this._rightjoystick.pressed) {
  99143. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  99144. }
  99145. }
  99146. };
  99147. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  99148. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  99149. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  99150. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  99151. this._leftjoystick.setJoystickSensibility(0.15);
  99152. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  99153. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  99154. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  99155. this._rightjoystick.reverseUpDown = true;
  99156. this._rightjoystick.setJoystickSensibility(0.05);
  99157. this._rightjoystick.setJoystickColor("yellow");
  99158. };
  99159. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  99160. this._leftjoystick.releaseCanvas();
  99161. this._rightjoystick.releaseCanvas();
  99162. };
  99163. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  99164. return "FreeCameraVirtualJoystickInput";
  99165. };
  99166. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  99167. return "virtualJoystick";
  99168. };
  99169. return FreeCameraVirtualJoystickInput;
  99170. }());
  99171. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  99172. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  99173. })(BABYLON || (BABYLON = {}));
  99174. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  99175. var BABYLON;
  99176. (function (BABYLON) {
  99177. var SimplificationSettings = /** @class */ (function () {
  99178. function SimplificationSettings(quality, distance, optimizeMesh) {
  99179. this.quality = quality;
  99180. this.distance = distance;
  99181. this.optimizeMesh = optimizeMesh;
  99182. }
  99183. return SimplificationSettings;
  99184. }());
  99185. BABYLON.SimplificationSettings = SimplificationSettings;
  99186. var SimplificationQueue = /** @class */ (function () {
  99187. function SimplificationQueue() {
  99188. this.running = false;
  99189. this._simplificationArray = [];
  99190. }
  99191. SimplificationQueue.prototype.addTask = function (task) {
  99192. this._simplificationArray.push(task);
  99193. };
  99194. SimplificationQueue.prototype.executeNext = function () {
  99195. var task = this._simplificationArray.pop();
  99196. if (task) {
  99197. this.running = true;
  99198. this.runSimplification(task);
  99199. }
  99200. else {
  99201. this.running = false;
  99202. }
  99203. };
  99204. SimplificationQueue.prototype.runSimplification = function (task) {
  99205. var _this = this;
  99206. if (task.parallelProcessing) {
  99207. //parallel simplifier
  99208. task.settings.forEach(function (setting) {
  99209. var simplifier = _this.getSimplifier(task);
  99210. simplifier.simplify(setting, function (newMesh) {
  99211. task.mesh.addLODLevel(setting.distance, newMesh);
  99212. newMesh.isVisible = true;
  99213. //check if it is the last
  99214. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  99215. //all done, run the success callback.
  99216. task.successCallback();
  99217. }
  99218. _this.executeNext();
  99219. });
  99220. });
  99221. }
  99222. else {
  99223. //single simplifier.
  99224. var simplifier = this.getSimplifier(task);
  99225. var runDecimation = function (setting, callback) {
  99226. simplifier.simplify(setting, function (newMesh) {
  99227. task.mesh.addLODLevel(setting.distance, newMesh);
  99228. newMesh.isVisible = true;
  99229. //run the next quality level
  99230. callback();
  99231. });
  99232. };
  99233. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  99234. runDecimation(task.settings[loop.index], function () {
  99235. loop.executeNext();
  99236. });
  99237. }, function () {
  99238. //execution ended, run the success callback.
  99239. if (task.successCallback) {
  99240. task.successCallback();
  99241. }
  99242. _this.executeNext();
  99243. });
  99244. }
  99245. };
  99246. SimplificationQueue.prototype.getSimplifier = function (task) {
  99247. switch (task.simplificationType) {
  99248. case SimplificationType.QUADRATIC:
  99249. default:
  99250. return new QuadraticErrorSimplification(task.mesh);
  99251. }
  99252. };
  99253. return SimplificationQueue;
  99254. }());
  99255. BABYLON.SimplificationQueue = SimplificationQueue;
  99256. /**
  99257. * The implemented types of simplification
  99258. * At the moment only Quadratic Error Decimation is implemented
  99259. */
  99260. var SimplificationType;
  99261. (function (SimplificationType) {
  99262. /** Quadratic error decimation */
  99263. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  99264. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  99265. var DecimationTriangle = /** @class */ (function () {
  99266. function DecimationTriangle(vertices) {
  99267. this.vertices = vertices;
  99268. this.error = new Array(4);
  99269. this.deleted = false;
  99270. this.isDirty = false;
  99271. this.deletePending = false;
  99272. this.borderFactor = 0;
  99273. }
  99274. return DecimationTriangle;
  99275. }());
  99276. BABYLON.DecimationTriangle = DecimationTriangle;
  99277. var DecimationVertex = /** @class */ (function () {
  99278. function DecimationVertex(position, id) {
  99279. this.position = position;
  99280. this.id = id;
  99281. this.isBorder = true;
  99282. this.q = new QuadraticMatrix();
  99283. this.triangleCount = 0;
  99284. this.triangleStart = 0;
  99285. this.originalOffsets = [];
  99286. }
  99287. DecimationVertex.prototype.updatePosition = function (newPosition) {
  99288. this.position.copyFrom(newPosition);
  99289. };
  99290. return DecimationVertex;
  99291. }());
  99292. BABYLON.DecimationVertex = DecimationVertex;
  99293. var QuadraticMatrix = /** @class */ (function () {
  99294. function QuadraticMatrix(data) {
  99295. this.data = new Array(10);
  99296. for (var i = 0; i < 10; ++i) {
  99297. if (data && data[i]) {
  99298. this.data[i] = data[i];
  99299. }
  99300. else {
  99301. this.data[i] = 0;
  99302. }
  99303. }
  99304. }
  99305. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  99306. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  99307. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  99308. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  99309. return det;
  99310. };
  99311. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  99312. for (var i = 0; i < 10; ++i) {
  99313. this.data[i] += matrix.data[i];
  99314. }
  99315. };
  99316. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  99317. for (var i = 0; i < 10; ++i) {
  99318. this.data[i] += data[i];
  99319. }
  99320. };
  99321. QuadraticMatrix.prototype.add = function (matrix) {
  99322. var m = new QuadraticMatrix();
  99323. for (var i = 0; i < 10; ++i) {
  99324. m.data[i] = this.data[i] + matrix.data[i];
  99325. }
  99326. return m;
  99327. };
  99328. QuadraticMatrix.FromData = function (a, b, c, d) {
  99329. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  99330. };
  99331. //returning an array to avoid garbage collection
  99332. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  99333. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  99334. };
  99335. return QuadraticMatrix;
  99336. }());
  99337. BABYLON.QuadraticMatrix = QuadraticMatrix;
  99338. var Reference = /** @class */ (function () {
  99339. function Reference(vertexId, triangleId) {
  99340. this.vertexId = vertexId;
  99341. this.triangleId = triangleId;
  99342. }
  99343. return Reference;
  99344. }());
  99345. BABYLON.Reference = Reference;
  99346. /**
  99347. * An implementation of the Quadratic Error simplification algorithm.
  99348. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  99349. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  99350. * @author RaananW
  99351. */
  99352. var QuadraticErrorSimplification = /** @class */ (function () {
  99353. function QuadraticErrorSimplification(_mesh) {
  99354. this._mesh = _mesh;
  99355. this.syncIterations = 5000;
  99356. this.aggressiveness = 7;
  99357. this.decimationIterations = 100;
  99358. this.boundingBoxEpsilon = BABYLON.Epsilon;
  99359. }
  99360. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  99361. var _this = this;
  99362. this.initDecimatedMesh();
  99363. //iterating through the submeshes array, one after the other.
  99364. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  99365. _this.initWithMesh(loop.index, function () {
  99366. _this.runDecimation(settings, loop.index, function () {
  99367. loop.executeNext();
  99368. });
  99369. }, settings.optimizeMesh);
  99370. }, function () {
  99371. setTimeout(function () {
  99372. successCallback(_this._reconstructedMesh);
  99373. }, 0);
  99374. });
  99375. };
  99376. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  99377. var _this = this;
  99378. var targetCount = ~~(this.triangles.length * settings.quality);
  99379. var deletedTriangles = 0;
  99380. var triangleCount = this.triangles.length;
  99381. var iterationFunction = function (iteration, callback) {
  99382. setTimeout(function () {
  99383. if (iteration % 5 === 0) {
  99384. _this.updateMesh(iteration === 0);
  99385. }
  99386. for (var i = 0; i < _this.triangles.length; ++i) {
  99387. _this.triangles[i].isDirty = false;
  99388. }
  99389. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  99390. var trianglesIterator = function (i) {
  99391. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  99392. var t = _this.triangles[tIdx];
  99393. if (!t)
  99394. return;
  99395. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  99396. return;
  99397. }
  99398. for (var j = 0; j < 3; ++j) {
  99399. if (t.error[j] < threshold) {
  99400. var deleted0 = [];
  99401. var deleted1 = [];
  99402. var v0 = t.vertices[j];
  99403. var v1 = t.vertices[(j + 1) % 3];
  99404. if (v0.isBorder || v1.isBorder)
  99405. continue;
  99406. var p = BABYLON.Vector3.Zero();
  99407. var n = BABYLON.Vector3.Zero();
  99408. var uv = BABYLON.Vector2.Zero();
  99409. var color = new BABYLON.Color4(0, 0, 0, 1);
  99410. _this.calculateError(v0, v1, p, n, uv, color);
  99411. var delTr = new Array();
  99412. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  99413. continue;
  99414. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  99415. continue;
  99416. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  99417. continue;
  99418. var uniqueArray = new Array();
  99419. delTr.forEach(function (deletedT) {
  99420. if (uniqueArray.indexOf(deletedT) === -1) {
  99421. deletedT.deletePending = true;
  99422. uniqueArray.push(deletedT);
  99423. }
  99424. });
  99425. if (uniqueArray.length % 2 !== 0) {
  99426. continue;
  99427. }
  99428. v0.q = v1.q.add(v0.q);
  99429. v0.updatePosition(p);
  99430. var tStart = _this.references.length;
  99431. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  99432. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  99433. var tCount = _this.references.length - tStart;
  99434. if (tCount <= v0.triangleCount) {
  99435. if (tCount) {
  99436. for (var c = 0; c < tCount; c++) {
  99437. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  99438. }
  99439. }
  99440. }
  99441. else {
  99442. v0.triangleStart = tStart;
  99443. }
  99444. v0.triangleCount = tCount;
  99445. break;
  99446. }
  99447. }
  99448. };
  99449. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  99450. }, 0);
  99451. };
  99452. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  99453. if (triangleCount - deletedTriangles <= targetCount)
  99454. loop.breakLoop();
  99455. else {
  99456. iterationFunction(loop.index, function () {
  99457. loop.executeNext();
  99458. });
  99459. }
  99460. }, function () {
  99461. setTimeout(function () {
  99462. //reconstruct this part of the mesh
  99463. _this.reconstructMesh(submeshIndex);
  99464. successCallback();
  99465. }, 0);
  99466. });
  99467. };
  99468. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  99469. var _this = this;
  99470. this.vertices = [];
  99471. this.triangles = [];
  99472. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99473. var indices = this._mesh.getIndices();
  99474. var submesh = this._mesh.subMeshes[submeshIndex];
  99475. var findInVertices = function (positionToSearch) {
  99476. if (optimizeMesh) {
  99477. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  99478. if (_this.vertices[ii].position.equals(positionToSearch)) {
  99479. return _this.vertices[ii];
  99480. }
  99481. }
  99482. }
  99483. return null;
  99484. };
  99485. var vertexReferences = [];
  99486. var vertexInit = function (i) {
  99487. if (!positionData) {
  99488. return;
  99489. }
  99490. var offset = i + submesh.verticesStart;
  99491. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  99492. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  99493. vertex.originalOffsets.push(offset);
  99494. if (vertex.id === _this.vertices.length) {
  99495. _this.vertices.push(vertex);
  99496. }
  99497. vertexReferences.push(vertex.id);
  99498. };
  99499. //var totalVertices = mesh.getTotalVertices();
  99500. var totalVertices = submesh.verticesCount;
  99501. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  99502. var indicesInit = function (i) {
  99503. if (!indices) {
  99504. return;
  99505. }
  99506. var offset = (submesh.indexStart / 3) + i;
  99507. var pos = (offset * 3);
  99508. var i0 = indices[pos + 0];
  99509. var i1 = indices[pos + 1];
  99510. var i2 = indices[pos + 2];
  99511. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  99512. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  99513. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  99514. var triangle = new DecimationTriangle([v0, v1, v2]);
  99515. triangle.originalOffset = pos;
  99516. _this.triangles.push(triangle);
  99517. };
  99518. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  99519. _this.init(callback);
  99520. });
  99521. });
  99522. };
  99523. QuadraticErrorSimplification.prototype.init = function (callback) {
  99524. var _this = this;
  99525. var triangleInit1 = function (i) {
  99526. var t = _this.triangles[i];
  99527. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  99528. for (var j = 0; j < 3; j++) {
  99529. 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))));
  99530. }
  99531. };
  99532. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  99533. var triangleInit2 = function (i) {
  99534. var t = _this.triangles[i];
  99535. for (var j = 0; j < 3; ++j) {
  99536. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  99537. }
  99538. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  99539. };
  99540. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  99541. callback();
  99542. });
  99543. });
  99544. };
  99545. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  99546. var newTriangles = [];
  99547. var i;
  99548. for (i = 0; i < this.vertices.length; ++i) {
  99549. this.vertices[i].triangleCount = 0;
  99550. }
  99551. var t;
  99552. var j;
  99553. for (i = 0; i < this.triangles.length; ++i) {
  99554. if (!this.triangles[i].deleted) {
  99555. t = this.triangles[i];
  99556. for (j = 0; j < 3; ++j) {
  99557. t.vertices[j].triangleCount = 1;
  99558. }
  99559. newTriangles.push(t);
  99560. }
  99561. }
  99562. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  99563. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  99564. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  99565. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  99566. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  99567. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  99568. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  99569. var vertexCount = 0;
  99570. for (i = 0; i < this.vertices.length; ++i) {
  99571. var vertex = this.vertices[i];
  99572. vertex.id = vertexCount;
  99573. if (vertex.triangleCount) {
  99574. vertex.originalOffsets.forEach(function (originalOffset) {
  99575. if (!normalData) {
  99576. return;
  99577. }
  99578. newPositionData.push(vertex.position.x);
  99579. newPositionData.push(vertex.position.y);
  99580. newPositionData.push(vertex.position.z);
  99581. newNormalData.push(normalData[originalOffset * 3]);
  99582. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  99583. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  99584. if (uvs && uvs.length) {
  99585. newUVsData.push(uvs[(originalOffset * 2)]);
  99586. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  99587. }
  99588. else if (colorsData && colorsData.length) {
  99589. newColorsData.push(colorsData[(originalOffset * 4)]);
  99590. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  99591. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  99592. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  99593. }
  99594. ++vertexCount;
  99595. });
  99596. }
  99597. }
  99598. var startingIndex = this._reconstructedMesh.getTotalIndices();
  99599. var startingVertex = this._reconstructedMesh.getTotalVertices();
  99600. var submeshesArray = this._reconstructedMesh.subMeshes;
  99601. this._reconstructedMesh.subMeshes = [];
  99602. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  99603. var originalIndices = this._mesh.getIndices();
  99604. for (i = 0; i < newTriangles.length; ++i) {
  99605. t = newTriangles[i]; //now get the new referencing point for each vertex
  99606. [0, 1, 2].forEach(function (idx) {
  99607. var id = originalIndices[t.originalOffset + idx];
  99608. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  99609. if (offset < 0)
  99610. offset = 0;
  99611. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  99612. });
  99613. }
  99614. //overwriting the old vertex buffers and indices.
  99615. this._reconstructedMesh.setIndices(newIndicesArray);
  99616. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  99617. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  99618. if (newUVsData.length > 0)
  99619. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  99620. if (newColorsData.length > 0)
  99621. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  99622. //create submesh
  99623. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  99624. if (submeshIndex > 0) {
  99625. this._reconstructedMesh.subMeshes = [];
  99626. submeshesArray.forEach(function (submesh) {
  99627. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  99628. });
  99629. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  99630. }
  99631. };
  99632. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  99633. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  99634. this._reconstructedMesh.material = this._mesh.material;
  99635. this._reconstructedMesh.parent = this._mesh.parent;
  99636. this._reconstructedMesh.isVisible = false;
  99637. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  99638. };
  99639. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  99640. for (var i = 0; i < vertex1.triangleCount; ++i) {
  99641. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  99642. if (t.deleted)
  99643. continue;
  99644. var s = this.references[vertex1.triangleStart + i].vertexId;
  99645. var v1 = t.vertices[(s + 1) % 3];
  99646. var v2 = t.vertices[(s + 2) % 3];
  99647. if ((v1 === vertex2 || v2 === vertex2)) {
  99648. deletedArray[i] = true;
  99649. delTr.push(t);
  99650. continue;
  99651. }
  99652. var d1 = v1.position.subtract(point);
  99653. d1 = d1.normalize();
  99654. var d2 = v2.position.subtract(point);
  99655. d2 = d2.normalize();
  99656. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  99657. return true;
  99658. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  99659. deletedArray[i] = false;
  99660. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  99661. return true;
  99662. }
  99663. return false;
  99664. };
  99665. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  99666. var newDeleted = deletedTriangles;
  99667. for (var i = 0; i < vertex.triangleCount; ++i) {
  99668. var ref = this.references[vertex.triangleStart + i];
  99669. var t = this.triangles[ref.triangleId];
  99670. if (t.deleted)
  99671. continue;
  99672. if (deletedArray[i] && t.deletePending) {
  99673. t.deleted = true;
  99674. newDeleted++;
  99675. continue;
  99676. }
  99677. t.vertices[ref.vertexId] = origVertex;
  99678. t.isDirty = true;
  99679. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  99680. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  99681. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  99682. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  99683. this.references.push(ref);
  99684. }
  99685. return newDeleted;
  99686. };
  99687. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  99688. for (var i = 0; i < this.vertices.length; ++i) {
  99689. var vCount = [];
  99690. var vId = [];
  99691. var v = this.vertices[i];
  99692. var j;
  99693. for (j = 0; j < v.triangleCount; ++j) {
  99694. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  99695. for (var ii = 0; ii < 3; ii++) {
  99696. var ofs = 0;
  99697. var vv = triangle.vertices[ii];
  99698. while (ofs < vCount.length) {
  99699. if (vId[ofs] === vv.id)
  99700. break;
  99701. ++ofs;
  99702. }
  99703. if (ofs === vCount.length) {
  99704. vCount.push(1);
  99705. vId.push(vv.id);
  99706. }
  99707. else {
  99708. vCount[ofs]++;
  99709. }
  99710. }
  99711. }
  99712. for (j = 0; j < vCount.length; ++j) {
  99713. if (vCount[j] === 1) {
  99714. this.vertices[vId[j]].isBorder = true;
  99715. }
  99716. else {
  99717. this.vertices[vId[j]].isBorder = false;
  99718. }
  99719. }
  99720. }
  99721. };
  99722. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  99723. if (identifyBorders === void 0) { identifyBorders = false; }
  99724. var i;
  99725. if (!identifyBorders) {
  99726. var newTrianglesVector = [];
  99727. for (i = 0; i < this.triangles.length; ++i) {
  99728. if (!this.triangles[i].deleted) {
  99729. newTrianglesVector.push(this.triangles[i]);
  99730. }
  99731. }
  99732. this.triangles = newTrianglesVector;
  99733. }
  99734. for (i = 0; i < this.vertices.length; ++i) {
  99735. this.vertices[i].triangleCount = 0;
  99736. this.vertices[i].triangleStart = 0;
  99737. }
  99738. var t;
  99739. var j;
  99740. var v;
  99741. for (i = 0; i < this.triangles.length; ++i) {
  99742. t = this.triangles[i];
  99743. for (j = 0; j < 3; ++j) {
  99744. v = t.vertices[j];
  99745. v.triangleCount++;
  99746. }
  99747. }
  99748. var tStart = 0;
  99749. for (i = 0; i < this.vertices.length; ++i) {
  99750. this.vertices[i].triangleStart = tStart;
  99751. tStart += this.vertices[i].triangleCount;
  99752. this.vertices[i].triangleCount = 0;
  99753. }
  99754. var newReferences = new Array(this.triangles.length * 3);
  99755. for (i = 0; i < this.triangles.length; ++i) {
  99756. t = this.triangles[i];
  99757. for (j = 0; j < 3; ++j) {
  99758. v = t.vertices[j];
  99759. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  99760. v.triangleCount++;
  99761. }
  99762. }
  99763. this.references = newReferences;
  99764. if (identifyBorders) {
  99765. this.identifyBorder();
  99766. }
  99767. };
  99768. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  99769. var x = point.x;
  99770. var y = point.y;
  99771. var z = point.z;
  99772. 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
  99773. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  99774. };
  99775. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  99776. var q = vertex1.q.add(vertex2.q);
  99777. var border = vertex1.isBorder && vertex2.isBorder;
  99778. var error = 0;
  99779. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  99780. if (qDet !== 0 && !border) {
  99781. if (!pointResult) {
  99782. pointResult = BABYLON.Vector3.Zero();
  99783. }
  99784. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  99785. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  99786. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  99787. error = this.vertexError(q, pointResult);
  99788. }
  99789. else {
  99790. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  99791. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  99792. var error1 = this.vertexError(q, vertex1.position);
  99793. var error2 = this.vertexError(q, vertex2.position);
  99794. var error3 = this.vertexError(q, p3);
  99795. error = Math.min(error1, error2, error3);
  99796. if (error === error1) {
  99797. if (pointResult) {
  99798. pointResult.copyFrom(vertex1.position);
  99799. }
  99800. }
  99801. else if (error === error2) {
  99802. if (pointResult) {
  99803. pointResult.copyFrom(vertex2.position);
  99804. }
  99805. }
  99806. else {
  99807. if (pointResult) {
  99808. pointResult.copyFrom(p3);
  99809. }
  99810. }
  99811. }
  99812. return error;
  99813. };
  99814. return QuadraticErrorSimplification;
  99815. }());
  99816. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  99817. })(BABYLON || (BABYLON = {}));
  99818. //# sourceMappingURL=babylon.meshSimplification.js.map
  99819. var BABYLON;
  99820. (function (BABYLON) {
  99821. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  99822. get: function () {
  99823. if (!this._simplificationQueue) {
  99824. this._simplificationQueue = new BABYLON.SimplificationQueue();
  99825. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  99826. if (!component) {
  99827. component = new SimplicationQueueSceneComponent(this);
  99828. this._addComponent(component);
  99829. }
  99830. }
  99831. return this._simplificationQueue;
  99832. },
  99833. set: function (value) {
  99834. this._simplificationQueue = value;
  99835. },
  99836. enumerable: true,
  99837. configurable: true
  99838. });
  99839. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  99840. if (parallelProcessing === void 0) { parallelProcessing = true; }
  99841. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  99842. this.getScene().simplificationQueue.addTask({
  99843. settings: settings,
  99844. parallelProcessing: parallelProcessing,
  99845. mesh: this,
  99846. simplificationType: simplificationType,
  99847. successCallback: successCallback
  99848. });
  99849. return this;
  99850. };
  99851. /**
  99852. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  99853. * created in a scene
  99854. */
  99855. var SimplicationQueueSceneComponent = /** @class */ (function () {
  99856. /**
  99857. * Creates a new instance of the component for the given scene
  99858. * @param scene Defines the scene to register the component in
  99859. */
  99860. function SimplicationQueueSceneComponent(scene) {
  99861. /**
  99862. * The component name helpfull to identify the component in the list of scene components.
  99863. */
  99864. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  99865. this.scene = scene;
  99866. }
  99867. /**
  99868. * Registers the component in a given scene
  99869. */
  99870. SimplicationQueueSceneComponent.prototype.register = function () {
  99871. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  99872. };
  99873. /**
  99874. * Rebuilds the elements related to this component in case of
  99875. * context lost for instance.
  99876. */
  99877. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  99878. // Nothing to do for this component
  99879. };
  99880. /**
  99881. * Disposes the component and the associated ressources
  99882. */
  99883. SimplicationQueueSceneComponent.prototype.dispose = function () {
  99884. // Nothing to do for this component
  99885. };
  99886. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  99887. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  99888. this.scene._simplificationQueue.executeNext();
  99889. }
  99890. };
  99891. return SimplicationQueueSceneComponent;
  99892. }());
  99893. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  99894. })(BABYLON || (BABYLON = {}));
  99895. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  99896. var BABYLON;
  99897. (function (BABYLON) {
  99898. var MeshLODLevel = /** @class */ (function () {
  99899. function MeshLODLevel(distance, mesh) {
  99900. this.distance = distance;
  99901. this.mesh = mesh;
  99902. }
  99903. return MeshLODLevel;
  99904. }());
  99905. BABYLON.MeshLODLevel = MeshLODLevel;
  99906. })(BABYLON || (BABYLON = {}));
  99907. //# sourceMappingURL=babylon.meshLODLevel.js.map
  99908. var BABYLON;
  99909. (function (BABYLON) {
  99910. /**
  99911. * Defines the root class used to create scene optimization to use with SceneOptimizer
  99912. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99913. */
  99914. var SceneOptimization = /** @class */ (function () {
  99915. /**
  99916. * Creates the SceneOptimization object
  99917. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99918. * @param desc defines the description associated with the optimization
  99919. */
  99920. function SceneOptimization(
  99921. /**
  99922. * Defines the priority of this optimization (0 by default which means first in the list)
  99923. */
  99924. priority) {
  99925. if (priority === void 0) { priority = 0; }
  99926. this.priority = priority;
  99927. }
  99928. /**
  99929. * Gets a string describing the action executed by the current optimization
  99930. * @returns description string
  99931. */
  99932. SceneOptimization.prototype.getDescription = function () {
  99933. return "";
  99934. };
  99935. /**
  99936. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99937. * @param scene defines the current scene where to apply this optimization
  99938. * @param optimizer defines the current optimizer
  99939. * @returns true if everything that can be done was applied
  99940. */
  99941. SceneOptimization.prototype.apply = function (scene, optimizer) {
  99942. return true;
  99943. };
  99944. ;
  99945. return SceneOptimization;
  99946. }());
  99947. BABYLON.SceneOptimization = SceneOptimization;
  99948. /**
  99949. * Defines an optimization used to reduce the size of render target textures
  99950. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99951. */
  99952. var TextureOptimization = /** @class */ (function (_super) {
  99953. __extends(TextureOptimization, _super);
  99954. /**
  99955. * Creates the TextureOptimization object
  99956. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99957. * @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
  99958. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  99959. */
  99960. function TextureOptimization(
  99961. /**
  99962. * Defines the priority of this optimization (0 by default which means first in the list)
  99963. */
  99964. priority,
  99965. /**
  99966. * 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
  99967. */
  99968. maximumSize,
  99969. /**
  99970. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  99971. */
  99972. step) {
  99973. if (priority === void 0) { priority = 0; }
  99974. if (maximumSize === void 0) { maximumSize = 1024; }
  99975. if (step === void 0) { step = 0.5; }
  99976. var _this = _super.call(this, priority) || this;
  99977. _this.priority = priority;
  99978. _this.maximumSize = maximumSize;
  99979. _this.step = step;
  99980. return _this;
  99981. }
  99982. /**
  99983. * Gets a string describing the action executed by the current optimization
  99984. * @returns description string
  99985. */
  99986. TextureOptimization.prototype.getDescription = function () {
  99987. return "Reducing render target texture size to " + this.maximumSize;
  99988. };
  99989. /**
  99990. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99991. * @param scene defines the current scene where to apply this optimization
  99992. * @param optimizer defines the current optimizer
  99993. * @returns true if everything that can be done was applied
  99994. */
  99995. TextureOptimization.prototype.apply = function (scene, optimizer) {
  99996. var allDone = true;
  99997. for (var index = 0; index < scene.textures.length; index++) {
  99998. var texture = scene.textures[index];
  99999. if (!texture.canRescale || texture.getContext) {
  100000. continue;
  100001. }
  100002. var currentSize = texture.getSize();
  100003. var maxDimension = Math.max(currentSize.width, currentSize.height);
  100004. if (maxDimension > this.maximumSize) {
  100005. texture.scale(this.step);
  100006. allDone = false;
  100007. }
  100008. }
  100009. return allDone;
  100010. };
  100011. return TextureOptimization;
  100012. }(SceneOptimization));
  100013. BABYLON.TextureOptimization = TextureOptimization;
  100014. /**
  100015. * Defines an optimization used to increase or decrease the rendering resolution
  100016. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100017. */
  100018. var HardwareScalingOptimization = /** @class */ (function (_super) {
  100019. __extends(HardwareScalingOptimization, _super);
  100020. /**
  100021. * Creates the HardwareScalingOptimization object
  100022. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100023. * @param maximumScale defines the maximum scale to use (2 by default)
  100024. * @param step defines the step to use between two passes (0.5 by default)
  100025. */
  100026. function HardwareScalingOptimization(
  100027. /**
  100028. * Defines the priority of this optimization (0 by default which means first in the list)
  100029. */
  100030. priority,
  100031. /**
  100032. * Defines the maximum scale to use (2 by default)
  100033. */
  100034. maximumScale,
  100035. /**
  100036. * Defines the step to use between two passes (0.5 by default)
  100037. */
  100038. step) {
  100039. if (priority === void 0) { priority = 0; }
  100040. if (maximumScale === void 0) { maximumScale = 2; }
  100041. if (step === void 0) { step = 0.25; }
  100042. var _this = _super.call(this, priority) || this;
  100043. _this.priority = priority;
  100044. _this.maximumScale = maximumScale;
  100045. _this.step = step;
  100046. _this._currentScale = -1;
  100047. _this._directionOffset = 1;
  100048. return _this;
  100049. }
  100050. /**
  100051. * Gets a string describing the action executed by the current optimization
  100052. * @return description string
  100053. */
  100054. HardwareScalingOptimization.prototype.getDescription = function () {
  100055. return "Setting hardware scaling level to " + this._currentScale;
  100056. };
  100057. /**
  100058. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100059. * @param scene defines the current scene where to apply this optimization
  100060. * @param optimizer defines the current optimizer
  100061. * @returns true if everything that can be done was applied
  100062. */
  100063. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  100064. if (this._currentScale === -1) {
  100065. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  100066. if (this._currentScale > this.maximumScale) {
  100067. this._directionOffset = -1;
  100068. }
  100069. }
  100070. this._currentScale += this._directionOffset * this.step;
  100071. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  100072. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  100073. };
  100074. ;
  100075. return HardwareScalingOptimization;
  100076. }(SceneOptimization));
  100077. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  100078. /**
  100079. * Defines an optimization used to remove shadows
  100080. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100081. */
  100082. var ShadowsOptimization = /** @class */ (function (_super) {
  100083. __extends(ShadowsOptimization, _super);
  100084. function ShadowsOptimization() {
  100085. return _super !== null && _super.apply(this, arguments) || this;
  100086. }
  100087. /**
  100088. * Gets a string describing the action executed by the current optimization
  100089. * @return description string
  100090. */
  100091. ShadowsOptimization.prototype.getDescription = function () {
  100092. return "Turning shadows on/off";
  100093. };
  100094. /**
  100095. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100096. * @param scene defines the current scene where to apply this optimization
  100097. * @param optimizer defines the current optimizer
  100098. * @returns true if everything that can be done was applied
  100099. */
  100100. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  100101. scene.shadowsEnabled = optimizer.isInImprovementMode;
  100102. return true;
  100103. };
  100104. ;
  100105. return ShadowsOptimization;
  100106. }(SceneOptimization));
  100107. BABYLON.ShadowsOptimization = ShadowsOptimization;
  100108. /**
  100109. * Defines an optimization used to turn post-processes off
  100110. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100111. */
  100112. var PostProcessesOptimization = /** @class */ (function (_super) {
  100113. __extends(PostProcessesOptimization, _super);
  100114. function PostProcessesOptimization() {
  100115. return _super !== null && _super.apply(this, arguments) || this;
  100116. }
  100117. /**
  100118. * Gets a string describing the action executed by the current optimization
  100119. * @return description string
  100120. */
  100121. PostProcessesOptimization.prototype.getDescription = function () {
  100122. return "Turning post-processes on/off";
  100123. };
  100124. /**
  100125. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100126. * @param scene defines the current scene where to apply this optimization
  100127. * @param optimizer defines the current optimizer
  100128. * @returns true if everything that can be done was applied
  100129. */
  100130. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  100131. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  100132. return true;
  100133. };
  100134. ;
  100135. return PostProcessesOptimization;
  100136. }(SceneOptimization));
  100137. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  100138. /**
  100139. * Defines an optimization used to turn lens flares off
  100140. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100141. */
  100142. var LensFlaresOptimization = /** @class */ (function (_super) {
  100143. __extends(LensFlaresOptimization, _super);
  100144. function LensFlaresOptimization() {
  100145. return _super !== null && _super.apply(this, arguments) || this;
  100146. }
  100147. /**
  100148. * Gets a string describing the action executed by the current optimization
  100149. * @return description string
  100150. */
  100151. LensFlaresOptimization.prototype.getDescription = function () {
  100152. return "Turning lens flares on/off";
  100153. };
  100154. /**
  100155. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100156. * @param scene defines the current scene where to apply this optimization
  100157. * @param optimizer defines the current optimizer
  100158. * @returns true if everything that can be done was applied
  100159. */
  100160. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  100161. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  100162. return true;
  100163. };
  100164. ;
  100165. return LensFlaresOptimization;
  100166. }(SceneOptimization));
  100167. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  100168. /**
  100169. * Defines an optimization based on user defined callback.
  100170. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100171. */
  100172. var CustomOptimization = /** @class */ (function (_super) {
  100173. __extends(CustomOptimization, _super);
  100174. function CustomOptimization() {
  100175. return _super !== null && _super.apply(this, arguments) || this;
  100176. }
  100177. /**
  100178. * Gets a string describing the action executed by the current optimization
  100179. * @returns description string
  100180. */
  100181. CustomOptimization.prototype.getDescription = function () {
  100182. if (this.onGetDescription) {
  100183. return this.onGetDescription();
  100184. }
  100185. return "Running user defined callback";
  100186. };
  100187. /**
  100188. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100189. * @param scene defines the current scene where to apply this optimization
  100190. * @param optimizer defines the current optimizer
  100191. * @returns true if everything that can be done was applied
  100192. */
  100193. CustomOptimization.prototype.apply = function (scene, optimizer) {
  100194. if (this.onApply) {
  100195. return this.onApply(scene, optimizer);
  100196. }
  100197. return true;
  100198. };
  100199. ;
  100200. return CustomOptimization;
  100201. }(SceneOptimization));
  100202. BABYLON.CustomOptimization = CustomOptimization;
  100203. /**
  100204. * Defines an optimization used to turn particles off
  100205. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100206. */
  100207. var ParticlesOptimization = /** @class */ (function (_super) {
  100208. __extends(ParticlesOptimization, _super);
  100209. function ParticlesOptimization() {
  100210. return _super !== null && _super.apply(this, arguments) || this;
  100211. }
  100212. /**
  100213. * Gets a string describing the action executed by the current optimization
  100214. * @return description string
  100215. */
  100216. ParticlesOptimization.prototype.getDescription = function () {
  100217. return "Turning particles on/off";
  100218. };
  100219. /**
  100220. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100221. * @param scene defines the current scene where to apply this optimization
  100222. * @param optimizer defines the current optimizer
  100223. * @returns true if everything that can be done was applied
  100224. */
  100225. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  100226. scene.particlesEnabled = optimizer.isInImprovementMode;
  100227. return true;
  100228. };
  100229. ;
  100230. return ParticlesOptimization;
  100231. }(SceneOptimization));
  100232. BABYLON.ParticlesOptimization = ParticlesOptimization;
  100233. /**
  100234. * Defines an optimization used to turn render targets off
  100235. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100236. */
  100237. var RenderTargetsOptimization = /** @class */ (function (_super) {
  100238. __extends(RenderTargetsOptimization, _super);
  100239. function RenderTargetsOptimization() {
  100240. return _super !== null && _super.apply(this, arguments) || this;
  100241. }
  100242. /**
  100243. * Gets a string describing the action executed by the current optimization
  100244. * @return description string
  100245. */
  100246. RenderTargetsOptimization.prototype.getDescription = function () {
  100247. return "Turning render targets off";
  100248. };
  100249. /**
  100250. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100251. * @param scene defines the current scene where to apply this optimization
  100252. * @param optimizer defines the current optimizer
  100253. * @returns true if everything that can be done was applied
  100254. */
  100255. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  100256. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  100257. return true;
  100258. };
  100259. ;
  100260. return RenderTargetsOptimization;
  100261. }(SceneOptimization));
  100262. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  100263. /**
  100264. * Defines an optimization used to merge meshes with compatible materials
  100265. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100266. */
  100267. var MergeMeshesOptimization = /** @class */ (function (_super) {
  100268. __extends(MergeMeshesOptimization, _super);
  100269. function MergeMeshesOptimization() {
  100270. var _this = _super !== null && _super.apply(this, arguments) || this;
  100271. _this._canBeMerged = function (abstractMesh) {
  100272. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  100273. return false;
  100274. }
  100275. var mesh = abstractMesh;
  100276. if (mesh.isDisposed()) {
  100277. return false;
  100278. }
  100279. if (!mesh.isVisible || !mesh.isEnabled()) {
  100280. return false;
  100281. }
  100282. if (mesh.instances.length > 0) {
  100283. return false;
  100284. }
  100285. if (mesh.skeleton || mesh.hasLODLevels) {
  100286. return false;
  100287. }
  100288. return true;
  100289. };
  100290. return _this;
  100291. }
  100292. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  100293. /**
  100294. * Gets or sets a boolean which defines if optimization octree has to be updated
  100295. */
  100296. get: function () {
  100297. return MergeMeshesOptimization._UpdateSelectionTree;
  100298. },
  100299. /**
  100300. * Gets or sets a boolean which defines if optimization octree has to be updated
  100301. */
  100302. set: function (value) {
  100303. MergeMeshesOptimization._UpdateSelectionTree = value;
  100304. },
  100305. enumerable: true,
  100306. configurable: true
  100307. });
  100308. /**
  100309. * Gets a string describing the action executed by the current optimization
  100310. * @return description string
  100311. */
  100312. MergeMeshesOptimization.prototype.getDescription = function () {
  100313. return "Merging similar meshes together";
  100314. };
  100315. /**
  100316. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100317. * @param scene defines the current scene where to apply this optimization
  100318. * @param optimizer defines the current optimizer
  100319. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  100320. * @returns true if everything that can be done was applied
  100321. */
  100322. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  100323. var globalPool = scene.meshes.slice(0);
  100324. var globalLength = globalPool.length;
  100325. for (var index = 0; index < globalLength; index++) {
  100326. var currentPool = new Array();
  100327. var current = globalPool[index];
  100328. // Checks
  100329. if (!this._canBeMerged(current)) {
  100330. continue;
  100331. }
  100332. currentPool.push(current);
  100333. // Find compatible meshes
  100334. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  100335. var otherMesh = globalPool[subIndex];
  100336. if (!this._canBeMerged(otherMesh)) {
  100337. continue;
  100338. }
  100339. if (otherMesh.material !== current.material) {
  100340. continue;
  100341. }
  100342. if (otherMesh.checkCollisions !== current.checkCollisions) {
  100343. continue;
  100344. }
  100345. currentPool.push(otherMesh);
  100346. globalLength--;
  100347. globalPool.splice(subIndex, 1);
  100348. subIndex--;
  100349. }
  100350. if (currentPool.length < 2) {
  100351. continue;
  100352. }
  100353. // Merge meshes
  100354. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  100355. }
  100356. // Call the octree system optimization if it is defined.
  100357. var sceneAsAny = scene;
  100358. if (sceneAsAny.createOrUpdateSelectionOctree) {
  100359. if (updateSelectionTree != undefined) {
  100360. if (updateSelectionTree) {
  100361. sceneAsAny.createOrUpdateSelectionOctree();
  100362. }
  100363. }
  100364. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  100365. sceneAsAny.createOrUpdateSelectionOctree();
  100366. }
  100367. }
  100368. return true;
  100369. };
  100370. ;
  100371. MergeMeshesOptimization._UpdateSelectionTree = false;
  100372. return MergeMeshesOptimization;
  100373. }(SceneOptimization));
  100374. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  100375. /**
  100376. * Defines a list of options used by SceneOptimizer
  100377. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100378. */
  100379. var SceneOptimizerOptions = /** @class */ (function () {
  100380. /**
  100381. * Creates a new list of options used by SceneOptimizer
  100382. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  100383. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  100384. */
  100385. function SceneOptimizerOptions(
  100386. /**
  100387. * Defines the target frame rate to reach (60 by default)
  100388. */
  100389. targetFrameRate,
  100390. /**
  100391. * Defines the interval between two checkes (2000ms by default)
  100392. */
  100393. trackerDuration) {
  100394. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  100395. if (trackerDuration === void 0) { trackerDuration = 2000; }
  100396. this.targetFrameRate = targetFrameRate;
  100397. this.trackerDuration = trackerDuration;
  100398. /**
  100399. * Gets the list of optimizations to apply
  100400. */
  100401. this.optimizations = new Array();
  100402. }
  100403. /**
  100404. * Add a new optimization
  100405. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  100406. * @returns the current SceneOptimizerOptions
  100407. */
  100408. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  100409. this.optimizations.push(optimization);
  100410. return this;
  100411. };
  100412. /**
  100413. * Add a new custom optimization
  100414. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  100415. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  100416. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100417. * @returns the current SceneOptimizerOptions
  100418. */
  100419. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  100420. if (priority === void 0) { priority = 0; }
  100421. var optimization = new CustomOptimization(priority);
  100422. optimization.onApply = onApply;
  100423. optimization.onGetDescription = onGetDescription;
  100424. this.optimizations.push(optimization);
  100425. return this;
  100426. };
  100427. /**
  100428. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  100429. * @param targetFrameRate defines the target frame rate (60 by default)
  100430. * @returns a SceneOptimizerOptions object
  100431. */
  100432. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  100433. var result = new SceneOptimizerOptions(targetFrameRate);
  100434. var priority = 0;
  100435. result.addOptimization(new MergeMeshesOptimization(priority));
  100436. result.addOptimization(new ShadowsOptimization(priority));
  100437. result.addOptimization(new LensFlaresOptimization(priority));
  100438. // Next priority
  100439. priority++;
  100440. result.addOptimization(new PostProcessesOptimization(priority));
  100441. result.addOptimization(new ParticlesOptimization(priority));
  100442. // Next priority
  100443. priority++;
  100444. result.addOptimization(new TextureOptimization(priority, 1024));
  100445. return result;
  100446. };
  100447. /**
  100448. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  100449. * @param targetFrameRate defines the target frame rate (60 by default)
  100450. * @returns a SceneOptimizerOptions object
  100451. */
  100452. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  100453. var result = new SceneOptimizerOptions(targetFrameRate);
  100454. var priority = 0;
  100455. result.addOptimization(new MergeMeshesOptimization(priority));
  100456. result.addOptimization(new ShadowsOptimization(priority));
  100457. result.addOptimization(new LensFlaresOptimization(priority));
  100458. // Next priority
  100459. priority++;
  100460. result.addOptimization(new PostProcessesOptimization(priority));
  100461. result.addOptimization(new ParticlesOptimization(priority));
  100462. // Next priority
  100463. priority++;
  100464. result.addOptimization(new TextureOptimization(priority, 512));
  100465. // Next priority
  100466. priority++;
  100467. result.addOptimization(new RenderTargetsOptimization(priority));
  100468. // Next priority
  100469. priority++;
  100470. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  100471. return result;
  100472. };
  100473. /**
  100474. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  100475. * @param targetFrameRate defines the target frame rate (60 by default)
  100476. * @returns a SceneOptimizerOptions object
  100477. */
  100478. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  100479. var result = new SceneOptimizerOptions(targetFrameRate);
  100480. var priority = 0;
  100481. result.addOptimization(new MergeMeshesOptimization(priority));
  100482. result.addOptimization(new ShadowsOptimization(priority));
  100483. result.addOptimization(new LensFlaresOptimization(priority));
  100484. // Next priority
  100485. priority++;
  100486. result.addOptimization(new PostProcessesOptimization(priority));
  100487. result.addOptimization(new ParticlesOptimization(priority));
  100488. // Next priority
  100489. priority++;
  100490. result.addOptimization(new TextureOptimization(priority, 256));
  100491. // Next priority
  100492. priority++;
  100493. result.addOptimization(new RenderTargetsOptimization(priority));
  100494. // Next priority
  100495. priority++;
  100496. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  100497. return result;
  100498. };
  100499. return SceneOptimizerOptions;
  100500. }());
  100501. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  100502. /**
  100503. * Class used to run optimizations in order to reach a target frame rate
  100504. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100505. */
  100506. var SceneOptimizer = /** @class */ (function () {
  100507. /**
  100508. * Creates a new SceneOptimizer
  100509. * @param scene defines the scene to work on
  100510. * @param options defines the options to use with the SceneOptimizer
  100511. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  100512. * @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)
  100513. */
  100514. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  100515. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  100516. if (improvementMode === void 0) { improvementMode = false; }
  100517. var _this = this;
  100518. this._isRunning = false;
  100519. this._currentPriorityLevel = 0;
  100520. this._targetFrameRate = 60;
  100521. this._trackerDuration = 2000;
  100522. this._currentFrameRate = 0;
  100523. this._improvementMode = false;
  100524. /**
  100525. * Defines an observable called when the optimizer reaches the target frame rate
  100526. */
  100527. this.onSuccessObservable = new BABYLON.Observable();
  100528. /**
  100529. * Defines an observable called when the optimizer enables an optimization
  100530. */
  100531. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  100532. /**
  100533. * Defines an observable called when the optimizer is not able to reach the target frame rate
  100534. */
  100535. this.onFailureObservable = new BABYLON.Observable();
  100536. if (!options) {
  100537. this._options = new SceneOptimizerOptions();
  100538. }
  100539. else {
  100540. this._options = options;
  100541. }
  100542. if (this._options.targetFrameRate) {
  100543. this._targetFrameRate = this._options.targetFrameRate;
  100544. }
  100545. if (this._options.trackerDuration) {
  100546. this._trackerDuration = this._options.trackerDuration;
  100547. }
  100548. if (autoGeneratePriorities) {
  100549. var priority = 0;
  100550. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  100551. var optim = _a[_i];
  100552. optim.priority = priority++;
  100553. }
  100554. }
  100555. this._improvementMode = improvementMode;
  100556. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  100557. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  100558. _this._sceneDisposeObserver = null;
  100559. _this.dispose();
  100560. });
  100561. }
  100562. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  100563. /**
  100564. * Gets a boolean indicating if the optimizer is in improvement mode
  100565. */
  100566. get: function () {
  100567. return this._improvementMode;
  100568. },
  100569. enumerable: true,
  100570. configurable: true
  100571. });
  100572. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  100573. /**
  100574. * Gets the current priority level (0 at start)
  100575. */
  100576. get: function () {
  100577. return this._currentPriorityLevel;
  100578. },
  100579. enumerable: true,
  100580. configurable: true
  100581. });
  100582. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  100583. /**
  100584. * Gets the current frame rate checked by the SceneOptimizer
  100585. */
  100586. get: function () {
  100587. return this._currentFrameRate;
  100588. },
  100589. enumerable: true,
  100590. configurable: true
  100591. });
  100592. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  100593. /**
  100594. * Gets or sets the current target frame rate (60 by default)
  100595. */
  100596. get: function () {
  100597. return this._targetFrameRate;
  100598. },
  100599. /**
  100600. * Gets or sets the current target frame rate (60 by default)
  100601. */
  100602. set: function (value) {
  100603. this._targetFrameRate = value;
  100604. },
  100605. enumerable: true,
  100606. configurable: true
  100607. });
  100608. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  100609. /**
  100610. * Gets or sets the current interval between two checks (every 2000ms by default)
  100611. */
  100612. get: function () {
  100613. return this._trackerDuration;
  100614. },
  100615. /**
  100616. * Gets or sets the current interval between two checks (every 2000ms by default)
  100617. */
  100618. set: function (value) {
  100619. this._trackerDuration = value;
  100620. },
  100621. enumerable: true,
  100622. configurable: true
  100623. });
  100624. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  100625. /**
  100626. * Gets the list of active optimizations
  100627. */
  100628. get: function () {
  100629. return this._options.optimizations;
  100630. },
  100631. enumerable: true,
  100632. configurable: true
  100633. });
  100634. /**
  100635. * Stops the current optimizer
  100636. */
  100637. SceneOptimizer.prototype.stop = function () {
  100638. this._isRunning = false;
  100639. };
  100640. /**
  100641. * Reset the optimizer to initial step (current priority level = 0)
  100642. */
  100643. SceneOptimizer.prototype.reset = function () {
  100644. this._currentPriorityLevel = 0;
  100645. };
  100646. /**
  100647. * Start the optimizer. By default it will try to reach a specific framerate
  100648. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  100649. */
  100650. SceneOptimizer.prototype.start = function () {
  100651. var _this = this;
  100652. if (this._isRunning) {
  100653. return;
  100654. }
  100655. this._isRunning = true;
  100656. // Let's wait for the scene to be ready before running our check
  100657. this._scene.executeWhenReady(function () {
  100658. setTimeout(function () {
  100659. _this._checkCurrentState();
  100660. }, _this._trackerDuration);
  100661. });
  100662. };
  100663. SceneOptimizer.prototype._checkCurrentState = function () {
  100664. var _this = this;
  100665. if (!this._isRunning) {
  100666. return;
  100667. }
  100668. var scene = this._scene;
  100669. var options = this._options;
  100670. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  100671. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  100672. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  100673. this._isRunning = false;
  100674. this.onSuccessObservable.notifyObservers(this);
  100675. return;
  100676. }
  100677. // Apply current level of optimizations
  100678. var allDone = true;
  100679. var noOptimizationApplied = true;
  100680. for (var index = 0; index < options.optimizations.length; index++) {
  100681. var optimization = options.optimizations[index];
  100682. if (optimization.priority === this._currentPriorityLevel) {
  100683. noOptimizationApplied = false;
  100684. allDone = allDone && optimization.apply(scene, this);
  100685. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  100686. }
  100687. }
  100688. // If no optimization was applied, this is a failure :(
  100689. if (noOptimizationApplied) {
  100690. this._isRunning = false;
  100691. this.onFailureObservable.notifyObservers(this);
  100692. return;
  100693. }
  100694. // If all optimizations were done, move to next level
  100695. if (allDone) {
  100696. this._currentPriorityLevel++;
  100697. }
  100698. // Let's the system running for a specific amount of time before checking FPS
  100699. scene.executeWhenReady(function () {
  100700. setTimeout(function () {
  100701. _this._checkCurrentState();
  100702. }, _this._trackerDuration);
  100703. });
  100704. };
  100705. /**
  100706. * Release all resources
  100707. */
  100708. SceneOptimizer.prototype.dispose = function () {
  100709. this.stop();
  100710. this.onSuccessObservable.clear();
  100711. this.onFailureObservable.clear();
  100712. this.onNewOptimizationAppliedObservable.clear();
  100713. if (this._sceneDisposeObserver) {
  100714. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  100715. }
  100716. };
  100717. /**
  100718. * Helper function to create a SceneOptimizer with one single line of code
  100719. * @param scene defines the scene to work on
  100720. * @param options defines the options to use with the SceneOptimizer
  100721. * @param onSuccess defines a callback to call on success
  100722. * @param onFailure defines a callback to call on failure
  100723. * @returns the new SceneOptimizer object
  100724. */
  100725. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  100726. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  100727. if (onSuccess) {
  100728. optimizer.onSuccessObservable.add(function () {
  100729. onSuccess();
  100730. });
  100731. }
  100732. if (onFailure) {
  100733. optimizer.onFailureObservable.add(function () {
  100734. onFailure();
  100735. });
  100736. }
  100737. optimizer.start();
  100738. return optimizer;
  100739. };
  100740. return SceneOptimizer;
  100741. }());
  100742. BABYLON.SceneOptimizer = SceneOptimizer;
  100743. })(BABYLON || (BABYLON = {}));
  100744. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  100745. var BABYLON;
  100746. (function (BABYLON) {
  100747. /**
  100748. * Gets the outline renderer associated with the scene
  100749. * @returns a OutlineRenderer
  100750. */
  100751. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  100752. if (!this._outlineRenderer) {
  100753. this._outlineRenderer = new OutlineRenderer(this);
  100754. }
  100755. return this._outlineRenderer;
  100756. };
  100757. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  100758. get: function () {
  100759. return this._renderOutline;
  100760. },
  100761. set: function (value) {
  100762. if (value) {
  100763. // Lazy Load the component.
  100764. this.getScene().getOutlineRenderer();
  100765. }
  100766. this._renderOutline = value;
  100767. },
  100768. enumerable: true,
  100769. configurable: true
  100770. });
  100771. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  100772. get: function () {
  100773. return this._renderOverlay;
  100774. },
  100775. set: function (value) {
  100776. if (value) {
  100777. // Lazy Load the component.
  100778. this.getScene().getOutlineRenderer();
  100779. }
  100780. this._renderOverlay = value;
  100781. },
  100782. enumerable: true,
  100783. configurable: true
  100784. });
  100785. /**
  100786. * This class is responsible to draw bothe outline/overlay of meshes.
  100787. * It should not be used directly but through the available method on mesh.
  100788. */
  100789. var OutlineRenderer = /** @class */ (function () {
  100790. /**
  100791. * Instantiates a new outline renderer. (There could be only one per scene).
  100792. * @param scene Defines the scene it belongs to
  100793. */
  100794. function OutlineRenderer(scene) {
  100795. /**
  100796. * The name of the component. Each component must have a unique name.
  100797. */
  100798. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  100799. /**
  100800. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  100801. */
  100802. this.zOffset = 1;
  100803. this.scene = scene;
  100804. this._engine = scene.getEngine();
  100805. this.scene._addComponent(this);
  100806. }
  100807. /**
  100808. * Register the component to one instance of a scene.
  100809. */
  100810. OutlineRenderer.prototype.register = function () {
  100811. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  100812. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  100813. };
  100814. /**
  100815. * Rebuilds the elements related to this component in case of
  100816. * context lost for instance.
  100817. */
  100818. OutlineRenderer.prototype.rebuild = function () {
  100819. // Nothing to do here.
  100820. };
  100821. /**
  100822. * Disposes the component and the associated ressources.
  100823. */
  100824. OutlineRenderer.prototype.dispose = function () {
  100825. // Nothing to do here.
  100826. };
  100827. /**
  100828. * Renders the outline in the canvas.
  100829. * @param subMesh Defines the sumesh to render
  100830. * @param batch Defines the batch of meshes in case of instances
  100831. * @param useOverlay Defines if the rendering is for the overlay or the outline
  100832. */
  100833. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  100834. var _this = this;
  100835. if (useOverlay === void 0) { useOverlay = false; }
  100836. var scene = this.scene;
  100837. var engine = scene.getEngine();
  100838. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  100839. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  100840. return;
  100841. }
  100842. var mesh = subMesh.getRenderingMesh();
  100843. var material = subMesh.getMaterial();
  100844. if (!material || !scene.activeCamera) {
  100845. return;
  100846. }
  100847. engine.enableEffect(this._effect);
  100848. // Logarithmic depth
  100849. if (material.useLogarithmicDepth) {
  100850. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  100851. }
  100852. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  100853. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  100854. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  100855. // Bones
  100856. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  100857. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  100858. }
  100859. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  100860. // Alpha test
  100861. if (material && material.needAlphaTesting()) {
  100862. var alphaTexture = material.getAlphaTestTexture();
  100863. if (alphaTexture) {
  100864. this._effect.setTexture("diffuseSampler", alphaTexture);
  100865. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  100866. }
  100867. }
  100868. engine.setZOffset(-this.zOffset);
  100869. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  100870. engine.setZOffset(0);
  100871. };
  100872. /**
  100873. * Returns whether or not the outline renderer is ready for a given submesh.
  100874. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  100875. * @param subMesh Defines the submesh to check readyness for
  100876. * @param useInstances Defines wheter wee are trying to render instances or not
  100877. * @returns true if ready otherwise false
  100878. */
  100879. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  100880. var defines = [];
  100881. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  100882. var mesh = subMesh.getMesh();
  100883. var material = subMesh.getMaterial();
  100884. if (material) {
  100885. // Alpha test
  100886. if (material.needAlphaTesting()) {
  100887. defines.push("#define ALPHATEST");
  100888. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100889. attribs.push(BABYLON.VertexBuffer.UVKind);
  100890. defines.push("#define UV1");
  100891. }
  100892. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  100893. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100894. defines.push("#define UV2");
  100895. }
  100896. }
  100897. //Logarithmic depth
  100898. if (material.useLogarithmicDepth) {
  100899. defines.push("#define LOGARITHMICDEPTH");
  100900. }
  100901. }
  100902. // Bones
  100903. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  100904. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  100905. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  100906. if (mesh.numBoneInfluencers > 4) {
  100907. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  100908. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  100909. }
  100910. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  100911. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  100912. }
  100913. else {
  100914. defines.push("#define NUM_BONE_INFLUENCERS 0");
  100915. }
  100916. // Instances
  100917. if (useInstances) {
  100918. defines.push("#define INSTANCES");
  100919. attribs.push("world0");
  100920. attribs.push("world1");
  100921. attribs.push("world2");
  100922. attribs.push("world3");
  100923. }
  100924. // Get correct effect
  100925. var join = defines.join("\n");
  100926. if (this._cachedDefines !== join) {
  100927. this._cachedDefines = join;
  100928. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  100929. }
  100930. return this._effect.isReady();
  100931. };
  100932. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  100933. // Outline - step 1
  100934. this._savedDepthWrite = this._engine.getDepthWrite();
  100935. if (mesh.renderOutline) {
  100936. this._engine.setDepthWrite(false);
  100937. this.render(subMesh, batch);
  100938. this._engine.setDepthWrite(this._savedDepthWrite);
  100939. }
  100940. };
  100941. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  100942. // Outline - step 2
  100943. if (mesh.renderOutline && this._savedDepthWrite) {
  100944. this._engine.setDepthWrite(true);
  100945. this._engine.setColorWrite(false);
  100946. this.render(subMesh, batch);
  100947. this._engine.setColorWrite(true);
  100948. }
  100949. // Overlay
  100950. if (mesh.renderOverlay) {
  100951. var currentMode = this._engine.getAlphaMode();
  100952. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  100953. this.render(subMesh, batch, true);
  100954. this._engine.setAlphaMode(currentMode);
  100955. }
  100956. };
  100957. return OutlineRenderer;
  100958. }());
  100959. BABYLON.OutlineRenderer = OutlineRenderer;
  100960. })(BABYLON || (BABYLON = {}));
  100961. //# sourceMappingURL=babylon.outlineRenderer.js.map
  100962. var BABYLON;
  100963. (function (BABYLON) {
  100964. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  100965. if (this._edgesRenderer) {
  100966. this._edgesRenderer.dispose();
  100967. this._edgesRenderer = null;
  100968. }
  100969. return this;
  100970. };
  100971. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  100972. if (epsilon === void 0) { epsilon = 0.95; }
  100973. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  100974. this.disableEdgesRendering();
  100975. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  100976. return this;
  100977. };
  100978. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  100979. get: function () {
  100980. return this._edgesRenderer;
  100981. },
  100982. enumerable: true,
  100983. configurable: true
  100984. });
  100985. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  100986. if (epsilon === void 0) { epsilon = 0.95; }
  100987. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  100988. this.disableEdgesRendering();
  100989. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  100990. return this;
  100991. };
  100992. /**
  100993. * FaceAdjacencies Helper class to generate edges
  100994. */
  100995. var FaceAdjacencies = /** @class */ (function () {
  100996. function FaceAdjacencies() {
  100997. this.edges = new Array();
  100998. this.edgesConnectedCount = 0;
  100999. }
  101000. return FaceAdjacencies;
  101001. }());
  101002. /**
  101003. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  101004. */
  101005. var EdgesRenderer = /** @class */ (function () {
  101006. /**
  101007. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  101008. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  101009. * @param source Mesh used to create edges
  101010. * @param epsilon sum of angles in adjacency to check for edge
  101011. * @param checkVerticesInsteadOfIndices
  101012. * @param generateEdgesLines - should generate Lines or only prepare resources.
  101013. */
  101014. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  101015. if (epsilon === void 0) { epsilon = 0.95; }
  101016. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101017. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  101018. var _this = this;
  101019. this.edgesWidthScalerForOrthographic = 1000.0;
  101020. this.edgesWidthScalerForPerspective = 50.0;
  101021. this._linesPositions = new Array();
  101022. this._linesNormals = new Array();
  101023. this._linesIndices = new Array();
  101024. this._buffers = {};
  101025. this._checkVerticesInsteadOfIndices = false;
  101026. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  101027. this.isEnabled = true;
  101028. this._source = source;
  101029. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  101030. this._epsilon = epsilon;
  101031. this._prepareRessources();
  101032. if (generateEdgesLines) {
  101033. this._generateEdgesLines();
  101034. }
  101035. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  101036. _this._rebuild();
  101037. });
  101038. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  101039. _this.dispose();
  101040. });
  101041. }
  101042. EdgesRenderer.prototype._prepareRessources = function () {
  101043. if (this._lineShader) {
  101044. return;
  101045. }
  101046. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  101047. attributes: ["position", "normal"],
  101048. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  101049. });
  101050. this._lineShader.disableDepthWrite = true;
  101051. this._lineShader.backFaceCulling = false;
  101052. };
  101053. /** @hidden */
  101054. EdgesRenderer.prototype._rebuild = function () {
  101055. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101056. if (buffer) {
  101057. buffer._rebuild();
  101058. }
  101059. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101060. if (buffer) {
  101061. buffer._rebuild();
  101062. }
  101063. var scene = this._source.getScene();
  101064. var engine = scene.getEngine();
  101065. this._ib = engine.createIndexBuffer(this._linesIndices);
  101066. };
  101067. /**
  101068. * Releases the required resources for the edges renderer
  101069. */
  101070. EdgesRenderer.prototype.dispose = function () {
  101071. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  101072. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  101073. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101074. if (buffer) {
  101075. buffer.dispose();
  101076. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  101077. }
  101078. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101079. if (buffer) {
  101080. buffer.dispose();
  101081. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  101082. }
  101083. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  101084. this._lineShader.dispose();
  101085. };
  101086. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  101087. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  101088. return 0;
  101089. }
  101090. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  101091. return 1;
  101092. }
  101093. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  101094. return 2;
  101095. }
  101096. return -1;
  101097. };
  101098. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  101099. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  101100. return 0;
  101101. }
  101102. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  101103. return 1;
  101104. }
  101105. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  101106. return 2;
  101107. }
  101108. return -1;
  101109. };
  101110. /**
  101111. * Checks if the pair of p0 and p1 is en edge
  101112. * @param faceIndex
  101113. * @param edge
  101114. * @param faceNormals
  101115. * @param p0
  101116. * @param p1
  101117. * @private
  101118. */
  101119. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  101120. var needToCreateLine;
  101121. if (edge === undefined) {
  101122. needToCreateLine = true;
  101123. }
  101124. else {
  101125. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  101126. needToCreateLine = dotProduct < this._epsilon;
  101127. }
  101128. if (needToCreateLine) {
  101129. var offset = this._linesPositions.length / 3;
  101130. var normal = p0.subtract(p1);
  101131. normal.normalize();
  101132. // Positions
  101133. this._linesPositions.push(p0.x);
  101134. this._linesPositions.push(p0.y);
  101135. this._linesPositions.push(p0.z);
  101136. this._linesPositions.push(p0.x);
  101137. this._linesPositions.push(p0.y);
  101138. this._linesPositions.push(p0.z);
  101139. this._linesPositions.push(p1.x);
  101140. this._linesPositions.push(p1.y);
  101141. this._linesPositions.push(p1.z);
  101142. this._linesPositions.push(p1.x);
  101143. this._linesPositions.push(p1.y);
  101144. this._linesPositions.push(p1.z);
  101145. // Normals
  101146. this._linesNormals.push(p1.x);
  101147. this._linesNormals.push(p1.y);
  101148. this._linesNormals.push(p1.z);
  101149. this._linesNormals.push(-1);
  101150. this._linesNormals.push(p1.x);
  101151. this._linesNormals.push(p1.y);
  101152. this._linesNormals.push(p1.z);
  101153. this._linesNormals.push(1);
  101154. this._linesNormals.push(p0.x);
  101155. this._linesNormals.push(p0.y);
  101156. this._linesNormals.push(p0.z);
  101157. this._linesNormals.push(-1);
  101158. this._linesNormals.push(p0.x);
  101159. this._linesNormals.push(p0.y);
  101160. this._linesNormals.push(p0.z);
  101161. this._linesNormals.push(1);
  101162. // Indices
  101163. this._linesIndices.push(offset);
  101164. this._linesIndices.push(offset + 1);
  101165. this._linesIndices.push(offset + 2);
  101166. this._linesIndices.push(offset);
  101167. this._linesIndices.push(offset + 2);
  101168. this._linesIndices.push(offset + 3);
  101169. }
  101170. };
  101171. /**
  101172. * Generates lines edges from adjacencjes
  101173. * @private
  101174. */
  101175. EdgesRenderer.prototype._generateEdgesLines = function () {
  101176. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101177. var indices = this._source.getIndices();
  101178. if (!indices || !positions) {
  101179. return;
  101180. }
  101181. // First let's find adjacencies
  101182. var adjacencies = new Array();
  101183. var faceNormals = new Array();
  101184. var index;
  101185. var faceAdjacencies;
  101186. // Prepare faces
  101187. for (index = 0; index < indices.length; index += 3) {
  101188. faceAdjacencies = new FaceAdjacencies();
  101189. var p0Index = indices[index];
  101190. var p1Index = indices[index + 1];
  101191. var p2Index = indices[index + 2];
  101192. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  101193. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  101194. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  101195. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  101196. faceNormal.normalize();
  101197. faceNormals.push(faceNormal);
  101198. adjacencies.push(faceAdjacencies);
  101199. }
  101200. // Scan
  101201. for (index = 0; index < adjacencies.length; index++) {
  101202. faceAdjacencies = adjacencies[index];
  101203. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  101204. var otherFaceAdjacencies = adjacencies[otherIndex];
  101205. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  101206. break;
  101207. }
  101208. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  101209. continue;
  101210. }
  101211. var otherP0 = indices[otherIndex * 3];
  101212. var otherP1 = indices[otherIndex * 3 + 1];
  101213. var otherP2 = indices[otherIndex * 3 + 2];
  101214. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  101215. var otherEdgeIndex = 0;
  101216. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  101217. continue;
  101218. }
  101219. switch (edgeIndex) {
  101220. case 0:
  101221. if (this._checkVerticesInsteadOfIndices) {
  101222. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101223. }
  101224. else {
  101225. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  101226. }
  101227. break;
  101228. case 1:
  101229. if (this._checkVerticesInsteadOfIndices) {
  101230. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101231. }
  101232. else {
  101233. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  101234. }
  101235. break;
  101236. case 2:
  101237. if (this._checkVerticesInsteadOfIndices) {
  101238. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101239. }
  101240. else {
  101241. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  101242. }
  101243. break;
  101244. }
  101245. if (otherEdgeIndex === -1) {
  101246. continue;
  101247. }
  101248. faceAdjacencies.edges[edgeIndex] = otherIndex;
  101249. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  101250. faceAdjacencies.edgesConnectedCount++;
  101251. otherFaceAdjacencies.edgesConnectedCount++;
  101252. if (faceAdjacencies.edgesConnectedCount === 3) {
  101253. break;
  101254. }
  101255. }
  101256. }
  101257. }
  101258. // Create lines
  101259. for (index = 0; index < adjacencies.length; index++) {
  101260. // 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
  101261. var current = adjacencies[index];
  101262. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  101263. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  101264. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  101265. }
  101266. // Merge into a single mesh
  101267. var engine = this._source.getScene().getEngine();
  101268. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  101269. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  101270. this._ib = engine.createIndexBuffer(this._linesIndices);
  101271. this._indicesCount = this._linesIndices.length;
  101272. };
  101273. /**
  101274. * Checks wether or not the edges renderer is ready to render.
  101275. * @return true if ready, otherwise false.
  101276. */
  101277. EdgesRenderer.prototype.isReady = function () {
  101278. return this._lineShader.isReady();
  101279. };
  101280. /**
  101281. * Renders the edges of the attached mesh,
  101282. */
  101283. EdgesRenderer.prototype.render = function () {
  101284. var scene = this._source.getScene();
  101285. if (!this.isReady() || !scene.activeCamera) {
  101286. return;
  101287. }
  101288. var engine = scene.getEngine();
  101289. this._lineShader._preBind();
  101290. if (this._source.edgesColor.a !== 1) {
  101291. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  101292. }
  101293. else {
  101294. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  101295. }
  101296. // VBOs
  101297. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  101298. scene.resetCachedMaterial();
  101299. this._lineShader.setColor4("color", this._source.edgesColor);
  101300. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  101301. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  101302. }
  101303. else {
  101304. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  101305. }
  101306. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  101307. this._lineShader.bind(this._source.getWorldMatrix());
  101308. // Draw order
  101309. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  101310. this._lineShader.unbind();
  101311. };
  101312. return EdgesRenderer;
  101313. }());
  101314. BABYLON.EdgesRenderer = EdgesRenderer;
  101315. })(BABYLON || (BABYLON = {}));
  101316. //# sourceMappingURL=babylon.edgesRenderer.js.map
  101317. var BABYLON;
  101318. (function (BABYLON) {
  101319. /**
  101320. * FaceAdjacencies Helper class to generate edges
  101321. */
  101322. var FaceAdjacencies = /** @class */ (function () {
  101323. function FaceAdjacencies() {
  101324. this.edges = new Array();
  101325. this.edgesConnectedCount = 0;
  101326. }
  101327. return FaceAdjacencies;
  101328. }());
  101329. /**
  101330. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  101331. */
  101332. var LineEdgesRenderer = /** @class */ (function (_super) {
  101333. __extends(LineEdgesRenderer, _super);
  101334. /**
  101335. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  101336. * @param source LineMesh used to generate edges
  101337. * @param epsilon not important (specified angle for edge detection)
  101338. * @param checkVerticesInsteadOfIndices not important for LineMesh
  101339. */
  101340. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  101341. if (epsilon === void 0) { epsilon = 0.95; }
  101342. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101343. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  101344. _this._generateEdgesLines();
  101345. return _this;
  101346. }
  101347. /**
  101348. * Always create the edge since its a line so only important things are p0 and p1
  101349. * @param faceIndex not important for LineMesh
  101350. * @param edge not important for LineMesh
  101351. * @param faceNormals not important for LineMesh
  101352. * @param p0 beginnig of line
  101353. * @param p1 end of line
  101354. */
  101355. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  101356. var offset = this._linesPositions.length / 3;
  101357. var normal = p0.subtract(p1);
  101358. normal.normalize();
  101359. // Positions
  101360. this._linesPositions.push(p0.x);
  101361. this._linesPositions.push(p0.y);
  101362. this._linesPositions.push(p0.z);
  101363. this._linesPositions.push(p0.x);
  101364. this._linesPositions.push(p0.y);
  101365. this._linesPositions.push(p0.z);
  101366. this._linesPositions.push(p1.x);
  101367. this._linesPositions.push(p1.y);
  101368. this._linesPositions.push(p1.z);
  101369. this._linesPositions.push(p1.x);
  101370. this._linesPositions.push(p1.y);
  101371. this._linesPositions.push(p1.z);
  101372. // Normals
  101373. this._linesNormals.push(p1.x);
  101374. this._linesNormals.push(p1.y);
  101375. this._linesNormals.push(p1.z);
  101376. this._linesNormals.push(-1);
  101377. this._linesNormals.push(p1.x);
  101378. this._linesNormals.push(p1.y);
  101379. this._linesNormals.push(p1.z);
  101380. this._linesNormals.push(1);
  101381. this._linesNormals.push(p0.x);
  101382. this._linesNormals.push(p0.y);
  101383. this._linesNormals.push(p0.z);
  101384. this._linesNormals.push(-1);
  101385. this._linesNormals.push(p0.x);
  101386. this._linesNormals.push(p0.y);
  101387. this._linesNormals.push(p0.z);
  101388. this._linesNormals.push(1);
  101389. // Indices
  101390. this._linesIndices.push(offset);
  101391. this._linesIndices.push(offset + 1);
  101392. this._linesIndices.push(offset + 2);
  101393. this._linesIndices.push(offset);
  101394. this._linesIndices.push(offset + 2);
  101395. this._linesIndices.push(offset + 3);
  101396. };
  101397. /**
  101398. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  101399. */
  101400. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  101401. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101402. var indices = this._source.getIndices();
  101403. if (!indices || !positions) {
  101404. return;
  101405. }
  101406. // First let's find adjacencies
  101407. var adjacencies = new Array();
  101408. var faceNormals = new Array();
  101409. var index;
  101410. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  101411. var currentAdjecancy = new FaceAdjacencies();
  101412. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  101413. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  101414. adjacencies.push(currentAdjecancy);
  101415. }
  101416. // Create lines
  101417. for (index = 0; index < adjacencies.length; index++) {
  101418. // 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
  101419. var current = adjacencies[index];
  101420. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  101421. }
  101422. // Merge into a single mesh
  101423. var engine = this._source.getScene().getEngine();
  101424. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  101425. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  101426. this._ib = engine.createIndexBuffer(this._linesIndices);
  101427. this._indicesCount = this._linesIndices.length;
  101428. };
  101429. return LineEdgesRenderer;
  101430. }(BABYLON.EdgesRenderer));
  101431. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  101432. })(BABYLON || (BABYLON = {}));
  101433. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  101434. var BABYLON;
  101435. (function (BABYLON) {
  101436. // Adds the parser to the scene parsers.
  101437. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  101438. if (parsedData.effectLayers) {
  101439. if (!container.effectLayers) {
  101440. container.effectLayers = new Array();
  101441. }
  101442. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  101443. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  101444. container.effectLayers.push(effectLayer);
  101445. }
  101446. }
  101447. });
  101448. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  101449. var index = this.effectLayers.indexOf(toRemove);
  101450. if (index !== -1) {
  101451. this.effectLayers.splice(index, 1);
  101452. }
  101453. return index;
  101454. };
  101455. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  101456. this.effectLayers.push(newEffectLayer);
  101457. };
  101458. /**
  101459. * Defines the layer scene component responsible to manage any effect layers
  101460. * in a given scene.
  101461. */
  101462. var EffectLayerSceneComponent = /** @class */ (function () {
  101463. /**
  101464. * Creates a new instance of the component for the given scene
  101465. * @param scene Defines the scene to register the component in
  101466. */
  101467. function EffectLayerSceneComponent(scene) {
  101468. /**
  101469. * The component name helpfull to identify the component in the list of scene components.
  101470. */
  101471. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  101472. this._renderEffects = false;
  101473. this._needStencil = false;
  101474. this._previousStencilState = false;
  101475. this.scene = scene;
  101476. this._engine = scene.getEngine();
  101477. scene.effectLayers = new Array();
  101478. }
  101479. /**
  101480. * Registers the component in a given scene
  101481. */
  101482. EffectLayerSceneComponent.prototype.register = function () {
  101483. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  101484. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  101485. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  101486. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  101487. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  101488. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  101489. };
  101490. /**
  101491. * Rebuilds the elements related to this component in case of
  101492. * context lost for instance.
  101493. */
  101494. EffectLayerSceneComponent.prototype.rebuild = function () {
  101495. var layers = this.scene.effectLayers;
  101496. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  101497. var effectLayer = layers_1[_i];
  101498. effectLayer._rebuild();
  101499. }
  101500. };
  101501. /**
  101502. * Serializes the component data to the specified json object
  101503. * @param serializationObject The object to serialize to
  101504. */
  101505. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  101506. // Effect layers
  101507. serializationObject.effectLayers = [];
  101508. var layers = this.scene.effectLayers;
  101509. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  101510. var effectLayer = layers_2[_i];
  101511. if (effectLayer.serialize) {
  101512. serializationObject.effectLayers.push(effectLayer.serialize());
  101513. }
  101514. }
  101515. };
  101516. /**
  101517. * Adds all the element from the container to the scene
  101518. * @param container the container holding the elements
  101519. */
  101520. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  101521. var _this = this;
  101522. if (!container.effectLayers) {
  101523. return;
  101524. }
  101525. container.effectLayers.forEach(function (o) {
  101526. _this.scene.addEffectLayer(o);
  101527. });
  101528. };
  101529. /**
  101530. * Removes all the elements in the container from the scene
  101531. * @param container contains the elements to remove
  101532. */
  101533. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  101534. var _this = this;
  101535. if (!container.effectLayers) {
  101536. return;
  101537. }
  101538. container.effectLayers.forEach(function (o) {
  101539. _this.scene.removeEffectLayer(o);
  101540. });
  101541. };
  101542. /**
  101543. * Disposes the component and the associated ressources.
  101544. */
  101545. EffectLayerSceneComponent.prototype.dispose = function () {
  101546. var layers = this.scene.effectLayers;
  101547. while (layers.length) {
  101548. layers[0].dispose();
  101549. }
  101550. };
  101551. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  101552. var layers = this.scene.effectLayers;
  101553. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  101554. var layer = layers_3[_i];
  101555. if (!layer.hasMesh(mesh)) {
  101556. continue;
  101557. }
  101558. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  101559. var subMesh = _b[_a];
  101560. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  101561. return false;
  101562. }
  101563. }
  101564. }
  101565. return true;
  101566. };
  101567. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  101568. this._renderEffects = false;
  101569. this._needStencil = false;
  101570. var layers = this.scene.effectLayers;
  101571. if (layers && layers.length > 0) {
  101572. this._previousStencilState = this._engine.getStencilBuffer();
  101573. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  101574. var effectLayer = layers_4[_i];
  101575. if (effectLayer.shouldRender() &&
  101576. (!effectLayer.camera ||
  101577. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  101578. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  101579. this._renderEffects = true;
  101580. this._needStencil = this._needStencil || effectLayer.needStencil();
  101581. var renderTarget = effectLayer._mainTexture;
  101582. if (renderTarget._shouldRender()) {
  101583. this.scene.incrementRenderId();
  101584. renderTarget.render(false, false);
  101585. }
  101586. }
  101587. }
  101588. this.scene.incrementRenderId();
  101589. }
  101590. };
  101591. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  101592. // Activate effect Layer stencil
  101593. if (this._needStencil) {
  101594. this._engine.setStencilBuffer(true);
  101595. }
  101596. };
  101597. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  101598. // Restore effect Layer stencil
  101599. if (this._needStencil) {
  101600. this._engine.setStencilBuffer(this._previousStencilState);
  101601. }
  101602. };
  101603. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  101604. if (this._renderEffects) {
  101605. this._engine.setDepthBuffer(false);
  101606. var layers = this.scene.effectLayers;
  101607. for (var i = 0; i < layers.length; i++) {
  101608. var effectLayer = layers[i];
  101609. if (effectLayer.renderingGroupId === renderingGroupId) {
  101610. if (effectLayer.shouldRender()) {
  101611. effectLayer.render();
  101612. }
  101613. }
  101614. }
  101615. this._engine.setDepthBuffer(true);
  101616. }
  101617. };
  101618. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  101619. if (this._renderEffects) {
  101620. this._draw(-1);
  101621. }
  101622. };
  101623. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  101624. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  101625. this._draw(index);
  101626. }
  101627. };
  101628. return EffectLayerSceneComponent;
  101629. }());
  101630. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  101631. })(BABYLON || (BABYLON = {}));
  101632. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  101633. var __assign = (this && this.__assign) || function () {
  101634. __assign = Object.assign || function(t) {
  101635. for (var s, i = 1, n = arguments.length; i < n; i++) {
  101636. s = arguments[i];
  101637. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  101638. t[p] = s[p];
  101639. }
  101640. return t;
  101641. };
  101642. return __assign.apply(this, arguments);
  101643. };
  101644. var BABYLON;
  101645. (function (BABYLON) {
  101646. /**
  101647. * The effect layer Helps adding post process effect blended with the main pass.
  101648. *
  101649. * This can be for instance use to generate glow or higlight effects on the scene.
  101650. *
  101651. * The effect layer class can not be used directly and is intented to inherited from to be
  101652. * customized per effects.
  101653. */
  101654. var EffectLayer = /** @class */ (function () {
  101655. /**
  101656. * Instantiates a new effect Layer and references it in the scene.
  101657. * @param name The name of the layer
  101658. * @param scene The scene to use the layer in
  101659. */
  101660. function EffectLayer(
  101661. /** The Friendly of the effect in the scene */
  101662. name, scene) {
  101663. this._vertexBuffers = {};
  101664. this._maxSize = 0;
  101665. this._mainTextureDesiredSize = { width: 0, height: 0 };
  101666. this._shouldRender = true;
  101667. this._postProcesses = [];
  101668. this._textures = [];
  101669. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  101670. /**
  101671. * The clear color of the texture used to generate the glow map.
  101672. */
  101673. this.neutralColor = new BABYLON.Color4();
  101674. /**
  101675. * Specifies wether the highlight layer is enabled or not.
  101676. */
  101677. this.isEnabled = true;
  101678. /**
  101679. * An event triggered when the effect layer has been disposed.
  101680. */
  101681. this.onDisposeObservable = new BABYLON.Observable();
  101682. /**
  101683. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  101684. */
  101685. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  101686. /**
  101687. * An event triggered when the generated texture is being merged in the scene.
  101688. */
  101689. this.onBeforeComposeObservable = new BABYLON.Observable();
  101690. /**
  101691. * An event triggered when the generated texture has been merged in the scene.
  101692. */
  101693. this.onAfterComposeObservable = new BABYLON.Observable();
  101694. /**
  101695. * An event triggered when the efffect layer changes its size.
  101696. */
  101697. this.onSizeChangedObservable = new BABYLON.Observable();
  101698. this.name = name;
  101699. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  101700. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  101701. if (!component) {
  101702. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  101703. this._scene._addComponent(component);
  101704. }
  101705. this._engine = this._scene.getEngine();
  101706. this._maxSize = this._engine.getCaps().maxTextureSize;
  101707. this._scene.effectLayers.push(this);
  101708. // Generate Buffers
  101709. this._generateIndexBuffer();
  101710. this._genrateVertexBuffer();
  101711. }
  101712. Object.defineProperty(EffectLayer.prototype, "camera", {
  101713. /**
  101714. * Gets the camera attached to the layer.
  101715. */
  101716. get: function () {
  101717. return this._effectLayerOptions.camera;
  101718. },
  101719. enumerable: true,
  101720. configurable: true
  101721. });
  101722. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  101723. /**
  101724. * Gets the rendering group id the layer should render in.
  101725. */
  101726. get: function () {
  101727. return this._effectLayerOptions.renderingGroupId;
  101728. },
  101729. enumerable: true,
  101730. configurable: true
  101731. });
  101732. /**
  101733. * Initializes the effect layer with the required options.
  101734. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  101735. */
  101736. EffectLayer.prototype._init = function (options) {
  101737. // Adapt options
  101738. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  101739. this._setMainTextureSize();
  101740. this._createMainTexture();
  101741. this._createTextureAndPostProcesses();
  101742. this._mergeEffect = this._createMergeEffect();
  101743. };
  101744. /**
  101745. * Generates the index buffer of the full screen quad blending to the main canvas.
  101746. */
  101747. EffectLayer.prototype._generateIndexBuffer = function () {
  101748. // Indices
  101749. var indices = [];
  101750. indices.push(0);
  101751. indices.push(1);
  101752. indices.push(2);
  101753. indices.push(0);
  101754. indices.push(2);
  101755. indices.push(3);
  101756. this._indexBuffer = this._engine.createIndexBuffer(indices);
  101757. };
  101758. /**
  101759. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  101760. */
  101761. EffectLayer.prototype._genrateVertexBuffer = function () {
  101762. // VBO
  101763. var vertices = [];
  101764. vertices.push(1, 1);
  101765. vertices.push(-1, 1);
  101766. vertices.push(-1, -1);
  101767. vertices.push(1, -1);
  101768. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  101769. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  101770. };
  101771. /**
  101772. * Sets the main texture desired size which is the closest power of two
  101773. * of the engine canvas size.
  101774. */
  101775. EffectLayer.prototype._setMainTextureSize = function () {
  101776. if (this._effectLayerOptions.mainTextureFixedSize) {
  101777. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  101778. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  101779. }
  101780. else {
  101781. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  101782. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  101783. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  101784. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  101785. }
  101786. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  101787. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  101788. };
  101789. /**
  101790. * Creates the main texture for the effect layer.
  101791. */
  101792. EffectLayer.prototype._createMainTexture = function () {
  101793. var _this = this;
  101794. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  101795. width: this._mainTextureDesiredSize.width,
  101796. height: this._mainTextureDesiredSize.height
  101797. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  101798. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  101799. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101800. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101801. this._mainTexture.anisotropicFilteringLevel = 1;
  101802. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101803. this._mainTexture.renderParticles = false;
  101804. this._mainTexture.renderList = null;
  101805. this._mainTexture.ignoreCameraViewport = true;
  101806. // Custom render function
  101807. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  101808. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  101809. var index;
  101810. var engine = _this._scene.getEngine();
  101811. if (depthOnlySubMeshes.length) {
  101812. engine.setColorWrite(false);
  101813. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  101814. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  101815. }
  101816. engine.setColorWrite(true);
  101817. }
  101818. for (index = 0; index < opaqueSubMeshes.length; index++) {
  101819. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  101820. }
  101821. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  101822. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  101823. }
  101824. for (index = 0; index < transparentSubMeshes.length; index++) {
  101825. _this._renderSubMesh(transparentSubMeshes.data[index]);
  101826. }
  101827. };
  101828. this._mainTexture.onClearObservable.add(function (engine) {
  101829. engine.clear(_this.neutralColor, true, true, true);
  101830. });
  101831. };
  101832. /**
  101833. * Checks for the readiness of the element composing the layer.
  101834. * @param subMesh the mesh to check for
  101835. * @param useInstances specify wether or not to use instances to render the mesh
  101836. * @param emissiveTexture the associated emissive texture used to generate the glow
  101837. * @return true if ready otherwise, false
  101838. */
  101839. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  101840. var material = subMesh.getMaterial();
  101841. if (!material) {
  101842. return false;
  101843. }
  101844. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  101845. return false;
  101846. }
  101847. var defines = [];
  101848. var attribs = [BABYLON.VertexBuffer.PositionKind];
  101849. var mesh = subMesh.getMesh();
  101850. var uv1 = false;
  101851. var uv2 = false;
  101852. // Alpha test
  101853. if (material && material.needAlphaTesting()) {
  101854. var alphaTexture = material.getAlphaTestTexture();
  101855. if (alphaTexture) {
  101856. defines.push("#define ALPHATEST");
  101857. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  101858. alphaTexture.coordinatesIndex === 1) {
  101859. defines.push("#define DIFFUSEUV2");
  101860. uv2 = true;
  101861. }
  101862. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  101863. defines.push("#define DIFFUSEUV1");
  101864. uv1 = true;
  101865. }
  101866. }
  101867. }
  101868. // Emissive
  101869. if (emissiveTexture) {
  101870. defines.push("#define EMISSIVE");
  101871. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  101872. emissiveTexture.coordinatesIndex === 1) {
  101873. defines.push("#define EMISSIVEUV2");
  101874. uv2 = true;
  101875. }
  101876. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  101877. defines.push("#define EMISSIVEUV1");
  101878. uv1 = true;
  101879. }
  101880. }
  101881. if (uv1) {
  101882. attribs.push(BABYLON.VertexBuffer.UVKind);
  101883. defines.push("#define UV1");
  101884. }
  101885. if (uv2) {
  101886. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  101887. defines.push("#define UV2");
  101888. }
  101889. // Bones
  101890. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  101891. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  101892. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  101893. if (mesh.numBoneInfluencers > 4) {
  101894. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  101895. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  101896. }
  101897. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  101898. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  101899. }
  101900. else {
  101901. defines.push("#define NUM_BONE_INFLUENCERS 0");
  101902. }
  101903. // Morph targets
  101904. var manager = mesh.morphTargetManager;
  101905. var morphInfluencers = 0;
  101906. if (manager) {
  101907. if (manager.numInfluencers > 0) {
  101908. defines.push("#define MORPHTARGETS");
  101909. morphInfluencers = manager.numInfluencers;
  101910. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  101911. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  101912. }
  101913. }
  101914. // Instances
  101915. if (useInstances) {
  101916. defines.push("#define INSTANCES");
  101917. attribs.push("world0");
  101918. attribs.push("world1");
  101919. attribs.push("world2");
  101920. attribs.push("world3");
  101921. }
  101922. // Get correct effect
  101923. var join = defines.join("\n");
  101924. if (this._cachedDefines !== join) {
  101925. this._cachedDefines = join;
  101926. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  101927. }
  101928. return this._effectLayerMapGenerationEffect.isReady();
  101929. };
  101930. /**
  101931. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  101932. */
  101933. EffectLayer.prototype.render = function () {
  101934. var currentEffect = this._mergeEffect;
  101935. // Check
  101936. if (!currentEffect.isReady())
  101937. return;
  101938. for (var i = 0; i < this._postProcesses.length; i++) {
  101939. if (!this._postProcesses[i].isReady()) {
  101940. return;
  101941. }
  101942. }
  101943. var engine = this._scene.getEngine();
  101944. this.onBeforeComposeObservable.notifyObservers(this);
  101945. // Render
  101946. engine.enableEffect(currentEffect);
  101947. engine.setState(false);
  101948. // VBOs
  101949. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  101950. // Cache
  101951. var previousAlphaMode = engine.getAlphaMode();
  101952. // Go Blend.
  101953. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  101954. // Blends the map on the main canvas.
  101955. this._internalRender(currentEffect);
  101956. // Restore Alpha
  101957. engine.setAlphaMode(previousAlphaMode);
  101958. this.onAfterComposeObservable.notifyObservers(this);
  101959. // Handle size changes.
  101960. var size = this._mainTexture.getSize();
  101961. this._setMainTextureSize();
  101962. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  101963. // Recreate RTT and post processes on size change.
  101964. this.onSizeChangedObservable.notifyObservers(this);
  101965. this._disposeTextureAndPostProcesses();
  101966. this._createMainTexture();
  101967. this._createTextureAndPostProcesses();
  101968. }
  101969. };
  101970. /**
  101971. * Determine if a given mesh will be used in the current effect.
  101972. * @param mesh mesh to test
  101973. * @returns true if the mesh will be used
  101974. */
  101975. EffectLayer.prototype.hasMesh = function (mesh) {
  101976. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  101977. return true;
  101978. }
  101979. return false;
  101980. };
  101981. /**
  101982. * Returns true if the layer contains information to display, otherwise false.
  101983. * @returns true if the glow layer should be rendered
  101984. */
  101985. EffectLayer.prototype.shouldRender = function () {
  101986. return this.isEnabled && this._shouldRender;
  101987. };
  101988. /**
  101989. * Returns true if the mesh should render, otherwise false.
  101990. * @param mesh The mesh to render
  101991. * @returns true if it should render otherwise false
  101992. */
  101993. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  101994. return true;
  101995. };
  101996. /**
  101997. * Returns true if the mesh should render, otherwise false.
  101998. * @param mesh The mesh to render
  101999. * @returns true if it should render otherwise false
  102000. */
  102001. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  102002. return true;
  102003. };
  102004. /**
  102005. * Renders the submesh passed in parameter to the generation map.
  102006. */
  102007. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  102008. var _this = this;
  102009. if (!this.shouldRender()) {
  102010. return;
  102011. }
  102012. var material = subMesh.getMaterial();
  102013. var mesh = subMesh.getRenderingMesh();
  102014. var scene = this._scene;
  102015. var engine = scene.getEngine();
  102016. if (!material) {
  102017. return;
  102018. }
  102019. // Do not block in blend mode.
  102020. if (material.needAlphaBlendingForMesh(mesh)) {
  102021. return;
  102022. }
  102023. // Culling
  102024. engine.setState(material.backFaceCulling);
  102025. // Managing instances
  102026. var batch = mesh._getInstancesRenderList(subMesh._id);
  102027. if (batch.mustReturn) {
  102028. return;
  102029. }
  102030. // Early Exit per mesh
  102031. if (!this._shouldRenderMesh(mesh)) {
  102032. return;
  102033. }
  102034. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  102035. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  102036. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  102037. engine.enableEffect(this._effectLayerMapGenerationEffect);
  102038. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  102039. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  102040. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  102041. // Alpha test
  102042. if (material && material.needAlphaTesting()) {
  102043. var alphaTexture = material.getAlphaTestTexture();
  102044. if (alphaTexture) {
  102045. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  102046. var textureMatrix = alphaTexture.getTextureMatrix();
  102047. if (textureMatrix) {
  102048. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  102049. }
  102050. }
  102051. }
  102052. // Glow emissive only
  102053. if (this._emissiveTextureAndColor.texture) {
  102054. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  102055. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  102056. }
  102057. // Bones
  102058. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  102059. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  102060. }
  102061. // Morph targets
  102062. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  102063. // Draw
  102064. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  102065. }
  102066. else {
  102067. // Need to reset refresh rate of the main map
  102068. this._mainTexture.resetRefreshCounter();
  102069. }
  102070. };
  102071. /**
  102072. * Rebuild the required buffers.
  102073. * @hidden Internal use only.
  102074. */
  102075. EffectLayer.prototype._rebuild = function () {
  102076. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102077. if (vb) {
  102078. vb._rebuild();
  102079. }
  102080. this._generateIndexBuffer();
  102081. };
  102082. /**
  102083. * Dispose only the render target textures and post process.
  102084. */
  102085. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  102086. this._mainTexture.dispose();
  102087. for (var i = 0; i < this._postProcesses.length; i++) {
  102088. if (this._postProcesses[i]) {
  102089. this._postProcesses[i].dispose();
  102090. }
  102091. }
  102092. this._postProcesses = [];
  102093. for (var i = 0; i < this._textures.length; i++) {
  102094. if (this._textures[i]) {
  102095. this._textures[i].dispose();
  102096. }
  102097. }
  102098. this._textures = [];
  102099. };
  102100. /**
  102101. * Dispose the highlight layer and free resources.
  102102. */
  102103. EffectLayer.prototype.dispose = function () {
  102104. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102105. if (vertexBuffer) {
  102106. vertexBuffer.dispose();
  102107. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  102108. }
  102109. if (this._indexBuffer) {
  102110. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  102111. this._indexBuffer = null;
  102112. }
  102113. // Clean textures and post processes
  102114. this._disposeTextureAndPostProcesses();
  102115. // Remove from scene
  102116. var index = this._scene.effectLayers.indexOf(this, 0);
  102117. if (index > -1) {
  102118. this._scene.effectLayers.splice(index, 1);
  102119. }
  102120. // Callback
  102121. this.onDisposeObservable.notifyObservers(this);
  102122. this.onDisposeObservable.clear();
  102123. this.onBeforeRenderMainTextureObservable.clear();
  102124. this.onBeforeComposeObservable.clear();
  102125. this.onAfterComposeObservable.clear();
  102126. this.onSizeChangedObservable.clear();
  102127. };
  102128. /**
  102129. * Gets the class name of the effect layer
  102130. * @returns the string with the class name of the effect layer
  102131. */
  102132. EffectLayer.prototype.getClassName = function () {
  102133. return "EffectLayer";
  102134. };
  102135. /**
  102136. * Creates an effect layer from parsed effect layer data
  102137. * @param parsedEffectLayer defines effect layer data
  102138. * @param scene defines the current scene
  102139. * @param rootUrl defines the root URL containing the effect layer information
  102140. * @returns a parsed effect Layer
  102141. */
  102142. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  102143. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  102144. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  102145. };
  102146. __decorate([
  102147. BABYLON.serialize()
  102148. ], EffectLayer.prototype, "name", void 0);
  102149. __decorate([
  102150. BABYLON.serializeAsColor4()
  102151. ], EffectLayer.prototype, "neutralColor", void 0);
  102152. __decorate([
  102153. BABYLON.serialize()
  102154. ], EffectLayer.prototype, "isEnabled", void 0);
  102155. __decorate([
  102156. BABYLON.serializeAsCameraReference()
  102157. ], EffectLayer.prototype, "camera", null);
  102158. __decorate([
  102159. BABYLON.serialize()
  102160. ], EffectLayer.prototype, "renderingGroupId", null);
  102161. return EffectLayer;
  102162. }());
  102163. BABYLON.EffectLayer = EffectLayer;
  102164. })(BABYLON || (BABYLON = {}));
  102165. //# sourceMappingURL=babylon.effectLayer.js.map
  102166. var BABYLON;
  102167. (function (BABYLON) {
  102168. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  102169. for (var index = 0; index < this.effectLayers.length; index++) {
  102170. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  102171. return this.effectLayers[index];
  102172. }
  102173. }
  102174. return null;
  102175. };
  102176. /**
  102177. * Special Glow Blur post process only blurring the alpha channel
  102178. * It enforces keeping the most luminous color in the color channel.
  102179. */
  102180. var GlowBlurPostProcess = /** @class */ (function (_super) {
  102181. __extends(GlowBlurPostProcess, _super);
  102182. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  102183. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  102184. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  102185. _this.direction = direction;
  102186. _this.kernel = kernel;
  102187. _this.onApplyObservable.add(function (effect) {
  102188. effect.setFloat2("screenSize", _this.width, _this.height);
  102189. effect.setVector2("direction", _this.direction);
  102190. effect.setFloat("blurWidth", _this.kernel);
  102191. });
  102192. return _this;
  102193. }
  102194. return GlowBlurPostProcess;
  102195. }(BABYLON.PostProcess));
  102196. /**
  102197. * The highlight layer Helps adding a glow effect around a mesh.
  102198. *
  102199. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  102200. * glowy meshes to your scene.
  102201. *
  102202. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  102203. */
  102204. var HighlightLayer = /** @class */ (function (_super) {
  102205. __extends(HighlightLayer, _super);
  102206. /**
  102207. * Instantiates a new highlight Layer and references it to the scene..
  102208. * @param name The name of the layer
  102209. * @param scene The scene to use the layer in
  102210. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  102211. */
  102212. function HighlightLayer(name, scene, options) {
  102213. var _this = _super.call(this, name, scene) || this;
  102214. _this.name = name;
  102215. /**
  102216. * Specifies whether or not the inner glow is ACTIVE in the layer.
  102217. */
  102218. _this.innerGlow = true;
  102219. /**
  102220. * Specifies whether or not the outer glow is ACTIVE in the layer.
  102221. */
  102222. _this.outerGlow = true;
  102223. /**
  102224. * An event triggered when the highlight layer is being blurred.
  102225. */
  102226. _this.onBeforeBlurObservable = new BABYLON.Observable();
  102227. /**
  102228. * An event triggered when the highlight layer has been blurred.
  102229. */
  102230. _this.onAfterBlurObservable = new BABYLON.Observable();
  102231. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  102232. _this._meshes = {};
  102233. _this._excludedMeshes = {};
  102234. _this.neutralColor = HighlightLayer.NeutralColor;
  102235. // Warn on stencil
  102236. if (!_this._engine.isStencilEnable) {
  102237. 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 }");
  102238. }
  102239. // Adapt options
  102240. _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);
  102241. // Initialize the layer
  102242. _this._init({
  102243. alphaBlendingMode: _this._options.alphaBlendingMode,
  102244. camera: _this._options.camera,
  102245. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  102246. mainTextureRatio: _this._options.mainTextureRatio,
  102247. renderingGroupId: _this._options.renderingGroupId
  102248. });
  102249. // Do not render as long as no meshes have been added
  102250. _this._shouldRender = false;
  102251. return _this;
  102252. }
  102253. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  102254. /**
  102255. * Gets the horizontal size of the blur.
  102256. */
  102257. get: function () {
  102258. return this._horizontalBlurPostprocess.kernel;
  102259. },
  102260. /**
  102261. * Specifies the horizontal size of the blur.
  102262. */
  102263. set: function (value) {
  102264. this._horizontalBlurPostprocess.kernel = value;
  102265. },
  102266. enumerable: true,
  102267. configurable: true
  102268. });
  102269. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  102270. /**
  102271. * Gets the vertical size of the blur.
  102272. */
  102273. get: function () {
  102274. return this._verticalBlurPostprocess.kernel;
  102275. },
  102276. /**
  102277. * Specifies the vertical size of the blur.
  102278. */
  102279. set: function (value) {
  102280. this._verticalBlurPostprocess.kernel = value;
  102281. },
  102282. enumerable: true,
  102283. configurable: true
  102284. });
  102285. /**
  102286. * Get the effect name of the layer.
  102287. * @return The effect name
  102288. */
  102289. HighlightLayer.prototype.getEffectName = function () {
  102290. return HighlightLayer.EffectName;
  102291. };
  102292. /**
  102293. * Create the merge effect. This is the shader use to blit the information back
  102294. * to the main canvas at the end of the scene rendering.
  102295. */
  102296. HighlightLayer.prototype._createMergeEffect = function () {
  102297. // Effect
  102298. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  102299. };
  102300. /**
  102301. * Creates the render target textures and post processes used in the highlight layer.
  102302. */
  102303. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  102304. var _this = this;
  102305. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  102306. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  102307. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  102308. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  102309. var textureType = 0;
  102310. if (this._engine.getCaps().textureHalfFloatRender) {
  102311. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  102312. }
  102313. else {
  102314. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  102315. }
  102316. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  102317. width: blurTextureWidth,
  102318. height: blurTextureHeight
  102319. }, this._scene, false, true, textureType);
  102320. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102321. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102322. this._blurTexture.anisotropicFilteringLevel = 16;
  102323. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  102324. this._blurTexture.renderParticles = false;
  102325. this._blurTexture.ignoreCameraViewport = true;
  102326. this._textures = [this._blurTexture];
  102327. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  102328. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102329. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  102330. effect.setTexture("textureSampler", _this._mainTexture);
  102331. });
  102332. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102333. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  102334. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  102335. });
  102336. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102337. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  102338. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  102339. });
  102340. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  102341. }
  102342. else {
  102343. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  102344. width: blurTextureWidth,
  102345. height: blurTextureHeight
  102346. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102347. this._horizontalBlurPostprocess.width = blurTextureWidth;
  102348. this._horizontalBlurPostprocess.height = blurTextureHeight;
  102349. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  102350. effect.setTexture("textureSampler", _this._mainTexture);
  102351. });
  102352. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  102353. width: blurTextureWidth,
  102354. height: blurTextureHeight
  102355. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102356. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  102357. }
  102358. this._mainTexture.onAfterUnbindObservable.add(function () {
  102359. _this.onBeforeBlurObservable.notifyObservers(_this);
  102360. var internalTexture = _this._blurTexture.getInternalTexture();
  102361. if (internalTexture) {
  102362. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  102363. }
  102364. _this.onAfterBlurObservable.notifyObservers(_this);
  102365. });
  102366. // Prevent autoClear.
  102367. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  102368. };
  102369. /**
  102370. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  102371. */
  102372. HighlightLayer.prototype.needStencil = function () {
  102373. return true;
  102374. };
  102375. /**
  102376. * Checks for the readiness of the element composing the layer.
  102377. * @param subMesh the mesh to check for
  102378. * @param useInstances specify wether or not to use instances to render the mesh
  102379. * @param emissiveTexture the associated emissive texture used to generate the glow
  102380. * @return true if ready otherwise, false
  102381. */
  102382. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  102383. var material = subMesh.getMaterial();
  102384. var mesh = subMesh.getRenderingMesh();
  102385. if (!material || !mesh || !this._meshes) {
  102386. return false;
  102387. }
  102388. var emissiveTexture = null;
  102389. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  102390. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  102391. emissiveTexture = material.emissiveTexture;
  102392. }
  102393. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  102394. };
  102395. /**
  102396. * Implementation specific of rendering the generating effect on the main canvas.
  102397. * @param effect The effect used to render through
  102398. */
  102399. HighlightLayer.prototype._internalRender = function (effect) {
  102400. // Texture
  102401. effect.setTexture("textureSampler", this._blurTexture);
  102402. // Cache
  102403. var engine = this._engine;
  102404. var previousStencilBuffer = engine.getStencilBuffer();
  102405. var previousStencilFunction = engine.getStencilFunction();
  102406. var previousStencilMask = engine.getStencilMask();
  102407. var previousStencilOperationPass = engine.getStencilOperationPass();
  102408. var previousStencilOperationFail = engine.getStencilOperationFail();
  102409. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  102410. var previousStencilReference = engine.getStencilFunctionReference();
  102411. // Stencil operations
  102412. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  102413. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  102414. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  102415. // Draw order
  102416. engine.setStencilMask(0x00);
  102417. engine.setStencilBuffer(true);
  102418. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  102419. // 2 passes inner outer
  102420. if (this.outerGlow) {
  102421. effect.setFloat("offset", 0);
  102422. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  102423. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102424. }
  102425. if (this.innerGlow) {
  102426. effect.setFloat("offset", 1);
  102427. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  102428. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102429. }
  102430. // Restore Cache
  102431. engine.setStencilFunction(previousStencilFunction);
  102432. engine.setStencilMask(previousStencilMask);
  102433. engine.setStencilBuffer(previousStencilBuffer);
  102434. engine.setStencilOperationPass(previousStencilOperationPass);
  102435. engine.setStencilOperationFail(previousStencilOperationFail);
  102436. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  102437. engine.setStencilFunctionReference(previousStencilReference);
  102438. };
  102439. /**
  102440. * Returns true if the layer contains information to display, otherwise false.
  102441. */
  102442. HighlightLayer.prototype.shouldRender = function () {
  102443. if (_super.prototype.shouldRender.call(this)) {
  102444. return this._meshes ? true : false;
  102445. }
  102446. return false;
  102447. };
  102448. /**
  102449. * Returns true if the mesh should render, otherwise false.
  102450. * @param mesh The mesh to render
  102451. * @returns true if it should render otherwise false
  102452. */
  102453. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  102454. // Excluded Mesh
  102455. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  102456. return false;
  102457. }
  102458. ;
  102459. if (!_super.prototype.hasMesh.call(this, mesh)) {
  102460. return false;
  102461. }
  102462. return true;
  102463. };
  102464. /**
  102465. * Sets the required values for both the emissive texture and and the main color.
  102466. */
  102467. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  102468. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  102469. if (highlightLayerMesh) {
  102470. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  102471. }
  102472. else {
  102473. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  102474. }
  102475. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  102476. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  102477. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  102478. }
  102479. else {
  102480. this._emissiveTextureAndColor.texture = null;
  102481. }
  102482. };
  102483. /**
  102484. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  102485. * @param mesh The mesh to exclude from the highlight layer
  102486. */
  102487. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  102488. if (!this._excludedMeshes) {
  102489. return;
  102490. }
  102491. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  102492. if (!meshExcluded) {
  102493. this._excludedMeshes[mesh.uniqueId] = {
  102494. mesh: mesh,
  102495. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  102496. mesh.getEngine().setStencilBuffer(false);
  102497. }),
  102498. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  102499. mesh.getEngine().setStencilBuffer(true);
  102500. }),
  102501. };
  102502. }
  102503. };
  102504. /**
  102505. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  102506. * @param mesh The mesh to highlight
  102507. */
  102508. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  102509. if (!this._excludedMeshes) {
  102510. return;
  102511. }
  102512. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  102513. if (meshExcluded) {
  102514. if (meshExcluded.beforeRender) {
  102515. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  102516. }
  102517. if (meshExcluded.afterRender) {
  102518. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  102519. }
  102520. }
  102521. this._excludedMeshes[mesh.uniqueId] = null;
  102522. };
  102523. /**
  102524. * Determine if a given mesh will be highlighted by the current HighlightLayer
  102525. * @param mesh mesh to test
  102526. * @returns true if the mesh will be highlighted by the current HighlightLayer
  102527. */
  102528. HighlightLayer.prototype.hasMesh = function (mesh) {
  102529. if (!this._meshes) {
  102530. return false;
  102531. }
  102532. if (!_super.prototype.hasMesh.call(this, mesh)) {
  102533. return false;
  102534. }
  102535. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  102536. };
  102537. /**
  102538. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  102539. * @param mesh The mesh to highlight
  102540. * @param color The color of the highlight
  102541. * @param glowEmissiveOnly Extract the glow from the emissive texture
  102542. */
  102543. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  102544. var _this = this;
  102545. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  102546. if (!this._meshes) {
  102547. return;
  102548. }
  102549. var meshHighlight = this._meshes[mesh.uniqueId];
  102550. if (meshHighlight) {
  102551. meshHighlight.color = color;
  102552. }
  102553. else {
  102554. this._meshes[mesh.uniqueId] = {
  102555. mesh: mesh,
  102556. color: color,
  102557. // Lambda required for capture due to Observable this context
  102558. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  102559. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  102560. _this._defaultStencilReference(mesh);
  102561. }
  102562. else {
  102563. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  102564. }
  102565. }),
  102566. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  102567. glowEmissiveOnly: glowEmissiveOnly
  102568. };
  102569. mesh.onDisposeObservable.add(function () {
  102570. _this._disposeMesh(mesh);
  102571. });
  102572. }
  102573. this._shouldRender = true;
  102574. };
  102575. /**
  102576. * Remove a mesh from the highlight layer in order to make it stop glowing.
  102577. * @param mesh The mesh to highlight
  102578. */
  102579. HighlightLayer.prototype.removeMesh = function (mesh) {
  102580. if (!this._meshes) {
  102581. return;
  102582. }
  102583. var meshHighlight = this._meshes[mesh.uniqueId];
  102584. if (meshHighlight) {
  102585. if (meshHighlight.observerHighlight) {
  102586. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  102587. }
  102588. if (meshHighlight.observerDefault) {
  102589. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  102590. }
  102591. delete this._meshes[mesh.uniqueId];
  102592. }
  102593. this._shouldRender = false;
  102594. for (var meshHighlightToCheck in this._meshes) {
  102595. if (this._meshes[meshHighlightToCheck]) {
  102596. this._shouldRender = true;
  102597. break;
  102598. }
  102599. }
  102600. };
  102601. /**
  102602. * Force the stencil to the normal expected value for none glowing parts
  102603. */
  102604. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  102605. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  102606. };
  102607. /**
  102608. * Free any resources and references associated to a mesh.
  102609. * Internal use
  102610. * @param mesh The mesh to free.
  102611. * @hidden
  102612. */
  102613. HighlightLayer.prototype._disposeMesh = function (mesh) {
  102614. this.removeMesh(mesh);
  102615. this.removeExcludedMesh(mesh);
  102616. };
  102617. /**
  102618. * Dispose the highlight layer and free resources.
  102619. */
  102620. HighlightLayer.prototype.dispose = function () {
  102621. if (this._meshes) {
  102622. // Clean mesh references
  102623. for (var id in this._meshes) {
  102624. var meshHighlight = this._meshes[id];
  102625. if (meshHighlight && meshHighlight.mesh) {
  102626. if (meshHighlight.observerHighlight) {
  102627. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  102628. }
  102629. if (meshHighlight.observerDefault) {
  102630. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  102631. }
  102632. }
  102633. }
  102634. this._meshes = null;
  102635. }
  102636. if (this._excludedMeshes) {
  102637. for (var id in this._excludedMeshes) {
  102638. var meshHighlight = this._excludedMeshes[id];
  102639. if (meshHighlight) {
  102640. if (meshHighlight.beforeRender) {
  102641. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  102642. }
  102643. if (meshHighlight.afterRender) {
  102644. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  102645. }
  102646. }
  102647. }
  102648. this._excludedMeshes = null;
  102649. }
  102650. _super.prototype.dispose.call(this);
  102651. };
  102652. /**
  102653. * Gets the class name of the effect layer
  102654. * @returns the string with the class name of the effect layer
  102655. */
  102656. HighlightLayer.prototype.getClassName = function () {
  102657. return "HighlightLayer";
  102658. };
  102659. /**
  102660. * Serializes this Highlight layer
  102661. * @returns a serialized Highlight layer object
  102662. */
  102663. HighlightLayer.prototype.serialize = function () {
  102664. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  102665. serializationObject.customType = "BABYLON.HighlightLayer";
  102666. // Highlighted meshes
  102667. serializationObject.meshes = [];
  102668. if (this._meshes) {
  102669. for (var m in this._meshes) {
  102670. var mesh = this._meshes[m];
  102671. if (mesh) {
  102672. serializationObject.meshes.push({
  102673. glowEmissiveOnly: mesh.glowEmissiveOnly,
  102674. color: mesh.color.asArray(),
  102675. meshId: mesh.mesh.id
  102676. });
  102677. }
  102678. }
  102679. }
  102680. // Excluded meshes
  102681. serializationObject.excludedMeshes = [];
  102682. if (this._excludedMeshes) {
  102683. for (var e in this._excludedMeshes) {
  102684. var excludedMesh = this._excludedMeshes[e];
  102685. if (excludedMesh) {
  102686. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  102687. }
  102688. }
  102689. }
  102690. return serializationObject;
  102691. };
  102692. /**
  102693. * Creates a Highlight layer from parsed Highlight layer data
  102694. * @param parsedHightlightLayer defines the Highlight layer data
  102695. * @param scene defines the current scene
  102696. * @param rootUrl defines the root URL containing the Highlight layer information
  102697. * @returns a parsed Highlight layer
  102698. */
  102699. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  102700. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  102701. var index;
  102702. // Excluded meshes
  102703. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  102704. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  102705. if (mesh) {
  102706. hl.addExcludedMesh(mesh);
  102707. }
  102708. }
  102709. // Included meshes
  102710. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  102711. var highlightedMesh = parsedHightlightLayer.meshes[index];
  102712. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  102713. if (mesh) {
  102714. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  102715. }
  102716. }
  102717. return hl;
  102718. };
  102719. /**
  102720. * Effect Name of the highlight layer.
  102721. */
  102722. HighlightLayer.EffectName = "HighlightLayer";
  102723. /**
  102724. * The neutral color used during the preparation of the glow effect.
  102725. * This is black by default as the blend operation is a blend operation.
  102726. */
  102727. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  102728. /**
  102729. * Stencil value used for glowing meshes.
  102730. */
  102731. HighlightLayer.GlowingMeshStencilReference = 0x02;
  102732. /**
  102733. * Stencil value used for the other meshes in the scene.
  102734. */
  102735. HighlightLayer.NormalMeshStencilReference = 0x01;
  102736. __decorate([
  102737. BABYLON.serialize()
  102738. ], HighlightLayer.prototype, "innerGlow", void 0);
  102739. __decorate([
  102740. BABYLON.serialize()
  102741. ], HighlightLayer.prototype, "outerGlow", void 0);
  102742. __decorate([
  102743. BABYLON.serialize()
  102744. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  102745. __decorate([
  102746. BABYLON.serialize()
  102747. ], HighlightLayer.prototype, "blurVerticalSize", null);
  102748. __decorate([
  102749. BABYLON.serialize("options")
  102750. ], HighlightLayer.prototype, "_options", void 0);
  102751. return HighlightLayer;
  102752. }(BABYLON.EffectLayer));
  102753. BABYLON.HighlightLayer = HighlightLayer;
  102754. })(BABYLON || (BABYLON = {}));
  102755. //# sourceMappingURL=babylon.highlightLayer.js.map
  102756. var BABYLON;
  102757. (function (BABYLON) {
  102758. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  102759. for (var index = 0; index < this.effectLayers.length; index++) {
  102760. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  102761. return this.effectLayers[index];
  102762. }
  102763. }
  102764. return null;
  102765. };
  102766. /**
  102767. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  102768. *
  102769. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  102770. * glowy meshes to your scene.
  102771. *
  102772. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  102773. */
  102774. var GlowLayer = /** @class */ (function (_super) {
  102775. __extends(GlowLayer, _super);
  102776. /**
  102777. * Instantiates a new glow Layer and references it to the scene.
  102778. * @param name The name of the layer
  102779. * @param scene The scene to use the layer in
  102780. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  102781. */
  102782. function GlowLayer(name, scene, options) {
  102783. var _this = _super.call(this, name, scene) || this;
  102784. _this._intensity = 1.0;
  102785. _this._includedOnlyMeshes = [];
  102786. _this._excludedMeshes = [];
  102787. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  102788. // Adapt options
  102789. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  102790. // Initialize the layer
  102791. _this._init({
  102792. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  102793. camera: _this._options.camera,
  102794. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  102795. mainTextureRatio: _this._options.mainTextureRatio,
  102796. renderingGroupId: _this._options.renderingGroupId
  102797. });
  102798. return _this;
  102799. }
  102800. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  102801. /**
  102802. * Gets the kernel size of the blur.
  102803. */
  102804. get: function () {
  102805. return this._horizontalBlurPostprocess1.kernel;
  102806. },
  102807. /**
  102808. * Sets the kernel size of the blur.
  102809. */
  102810. set: function (value) {
  102811. this._horizontalBlurPostprocess1.kernel = value;
  102812. this._verticalBlurPostprocess1.kernel = value;
  102813. this._horizontalBlurPostprocess2.kernel = value;
  102814. this._verticalBlurPostprocess2.kernel = value;
  102815. },
  102816. enumerable: true,
  102817. configurable: true
  102818. });
  102819. Object.defineProperty(GlowLayer.prototype, "intensity", {
  102820. /**
  102821. * Gets the glow intensity.
  102822. */
  102823. get: function () {
  102824. return this._intensity;
  102825. },
  102826. /**
  102827. * Sets the glow intensity.
  102828. */
  102829. set: function (value) {
  102830. this._intensity = value;
  102831. },
  102832. enumerable: true,
  102833. configurable: true
  102834. });
  102835. /**
  102836. * Get the effect name of the layer.
  102837. * @return The effect name
  102838. */
  102839. GlowLayer.prototype.getEffectName = function () {
  102840. return GlowLayer.EffectName;
  102841. };
  102842. /**
  102843. * Create the merge effect. This is the shader use to blit the information back
  102844. * to the main canvas at the end of the scene rendering.
  102845. */
  102846. GlowLayer.prototype._createMergeEffect = function () {
  102847. // Effect
  102848. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  102849. };
  102850. /**
  102851. * Creates the render target textures and post processes used in the glow layer.
  102852. */
  102853. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  102854. var _this = this;
  102855. var blurTextureWidth = this._mainTextureDesiredSize.width;
  102856. var blurTextureHeight = this._mainTextureDesiredSize.height;
  102857. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  102858. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  102859. var textureType = 0;
  102860. if (this._engine.getCaps().textureHalfFloatRender) {
  102861. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  102862. }
  102863. else {
  102864. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  102865. }
  102866. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  102867. width: blurTextureWidth,
  102868. height: blurTextureHeight
  102869. }, this._scene, false, true, textureType);
  102870. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102871. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102872. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102873. this._blurTexture1.renderParticles = false;
  102874. this._blurTexture1.ignoreCameraViewport = true;
  102875. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  102876. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  102877. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  102878. width: blurTextureWidth2,
  102879. height: blurTextureHeight2
  102880. }, this._scene, false, true, textureType);
  102881. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102882. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102883. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102884. this._blurTexture2.renderParticles = false;
  102885. this._blurTexture2.ignoreCameraViewport = true;
  102886. this._textures = [this._blurTexture1, this._blurTexture2];
  102887. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  102888. width: blurTextureWidth,
  102889. height: blurTextureHeight
  102890. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102891. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  102892. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  102893. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  102894. effect.setTexture("textureSampler", _this._mainTexture);
  102895. });
  102896. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  102897. width: blurTextureWidth,
  102898. height: blurTextureHeight
  102899. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102900. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  102901. width: blurTextureWidth2,
  102902. height: blurTextureHeight2
  102903. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102904. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  102905. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  102906. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  102907. effect.setTexture("textureSampler", _this._blurTexture1);
  102908. });
  102909. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  102910. width: blurTextureWidth2,
  102911. height: blurTextureHeight2
  102912. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102913. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  102914. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  102915. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  102916. this._mainTexture.samples = this._options.mainTextureSamples;
  102917. this._mainTexture.onAfterUnbindObservable.add(function () {
  102918. var internalTexture = _this._blurTexture1.getInternalTexture();
  102919. if (internalTexture) {
  102920. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  102921. internalTexture = _this._blurTexture2.getInternalTexture();
  102922. if (internalTexture) {
  102923. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  102924. }
  102925. }
  102926. });
  102927. // Prevent autoClear.
  102928. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  102929. };
  102930. /**
  102931. * Checks for the readiness of the element composing the layer.
  102932. * @param subMesh the mesh to check for
  102933. * @param useInstances specify wether or not to use instances to render the mesh
  102934. * @param emissiveTexture the associated emissive texture used to generate the glow
  102935. * @return true if ready otherwise, false
  102936. */
  102937. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  102938. var material = subMesh.getMaterial();
  102939. var mesh = subMesh.getRenderingMesh();
  102940. if (!material || !mesh) {
  102941. return false;
  102942. }
  102943. var emissiveTexture = material.emissiveTexture;
  102944. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  102945. };
  102946. /**
  102947. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  102948. */
  102949. GlowLayer.prototype.needStencil = function () {
  102950. return false;
  102951. };
  102952. /**
  102953. * Implementation specific of rendering the generating effect on the main canvas.
  102954. * @param effect The effect used to render through
  102955. */
  102956. GlowLayer.prototype._internalRender = function (effect) {
  102957. // Texture
  102958. effect.setTexture("textureSampler", this._blurTexture1);
  102959. effect.setTexture("textureSampler2", this._blurTexture2);
  102960. effect.setFloat("offset", this._intensity);
  102961. // Cache
  102962. var engine = this._engine;
  102963. var previousStencilBuffer = engine.getStencilBuffer();
  102964. // Draw order
  102965. engine.setStencilBuffer(false);
  102966. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102967. // Draw order
  102968. engine.setStencilBuffer(previousStencilBuffer);
  102969. };
  102970. /**
  102971. * Sets the required values for both the emissive texture and and the main color.
  102972. */
  102973. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  102974. var textureLevel = 1.0;
  102975. if (this.customEmissiveTextureSelector) {
  102976. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  102977. }
  102978. else {
  102979. if (material) {
  102980. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  102981. if (this._emissiveTextureAndColor.texture) {
  102982. textureLevel = this._emissiveTextureAndColor.texture.level;
  102983. }
  102984. }
  102985. else {
  102986. this._emissiveTextureAndColor.texture = null;
  102987. }
  102988. }
  102989. if (this.customEmissiveColorSelector) {
  102990. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  102991. }
  102992. else {
  102993. if (material.emissiveColor) {
  102994. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  102995. }
  102996. else {
  102997. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  102998. }
  102999. }
  103000. };
  103001. /**
  103002. * Returns true if the mesh should render, otherwise false.
  103003. * @param mesh The mesh to render
  103004. * @returns true if it should render otherwise false
  103005. */
  103006. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  103007. return this.hasMesh(mesh);
  103008. };
  103009. /**
  103010. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  103011. * @param mesh The mesh to exclude from the glow layer
  103012. */
  103013. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  103014. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  103015. this._excludedMeshes.push(mesh.uniqueId);
  103016. }
  103017. };
  103018. /**
  103019. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  103020. * @param mesh The mesh to remove
  103021. */
  103022. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  103023. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  103024. if (index !== -1) {
  103025. this._excludedMeshes.splice(index, 1);
  103026. }
  103027. };
  103028. /**
  103029. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  103030. * @param mesh The mesh to include in the glow layer
  103031. */
  103032. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  103033. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  103034. this._includedOnlyMeshes.push(mesh.uniqueId);
  103035. }
  103036. };
  103037. /**
  103038. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  103039. * @param mesh The mesh to remove
  103040. */
  103041. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  103042. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  103043. if (index !== -1) {
  103044. this._includedOnlyMeshes.splice(index, 1);
  103045. }
  103046. };
  103047. /**
  103048. * Determine if a given mesh will be used in the glow layer
  103049. * @param mesh The mesh to test
  103050. * @returns true if the mesh will be highlighted by the current glow layer
  103051. */
  103052. GlowLayer.prototype.hasMesh = function (mesh) {
  103053. if (!_super.prototype.hasMesh.call(this, mesh)) {
  103054. return false;
  103055. }
  103056. // Included Mesh
  103057. if (this._includedOnlyMeshes.length) {
  103058. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  103059. }
  103060. ;
  103061. // Excluded Mesh
  103062. if (this._excludedMeshes.length) {
  103063. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  103064. }
  103065. ;
  103066. return true;
  103067. };
  103068. /**
  103069. * Free any resources and references associated to a mesh.
  103070. * Internal use
  103071. * @param mesh The mesh to free.
  103072. * @hidden
  103073. */
  103074. GlowLayer.prototype._disposeMesh = function (mesh) {
  103075. this.removeIncludedOnlyMesh(mesh);
  103076. this.removeExcludedMesh(mesh);
  103077. };
  103078. /**
  103079. * Gets the class name of the effect layer
  103080. * @returns the string with the class name of the effect layer
  103081. */
  103082. GlowLayer.prototype.getClassName = function () {
  103083. return "GlowLayer";
  103084. };
  103085. /**
  103086. * Serializes this glow layer
  103087. * @returns a serialized glow layer object
  103088. */
  103089. GlowLayer.prototype.serialize = function () {
  103090. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103091. serializationObject.customType = "BABYLON.GlowLayer";
  103092. var index;
  103093. // Included meshes
  103094. serializationObject.includedMeshes = [];
  103095. if (this._includedOnlyMeshes.length) {
  103096. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  103097. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  103098. if (mesh) {
  103099. serializationObject.includedMeshes.push(mesh.id);
  103100. }
  103101. }
  103102. }
  103103. // Excluded meshes
  103104. serializationObject.excludedMeshes = [];
  103105. if (this._excludedMeshes.length) {
  103106. for (index = 0; index < this._excludedMeshes.length; index++) {
  103107. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  103108. if (mesh) {
  103109. serializationObject.excludedMeshes.push(mesh.id);
  103110. }
  103111. }
  103112. }
  103113. return serializationObject;
  103114. };
  103115. /**
  103116. * Creates a Glow Layer from parsed glow layer data
  103117. * @param parsedGlowLayer defines glow layer data
  103118. * @param scene defines the current scene
  103119. * @param rootUrl defines the root URL containing the glow layer information
  103120. * @returns a parsed Glow Layer
  103121. */
  103122. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  103123. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  103124. var index;
  103125. // Excluded meshes
  103126. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  103127. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  103128. if (mesh) {
  103129. gl.addExcludedMesh(mesh);
  103130. }
  103131. }
  103132. // Included meshes
  103133. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  103134. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  103135. if (mesh) {
  103136. gl.addIncludedOnlyMesh(mesh);
  103137. }
  103138. }
  103139. return gl;
  103140. };
  103141. /**
  103142. * Effect Name of the layer.
  103143. */
  103144. GlowLayer.EffectName = "GlowLayer";
  103145. /**
  103146. * The default blur kernel size used for the glow.
  103147. */
  103148. GlowLayer.DefaultBlurKernelSize = 32;
  103149. /**
  103150. * The default texture size ratio used for the glow.
  103151. */
  103152. GlowLayer.DefaultTextureRatio = 0.5;
  103153. __decorate([
  103154. BABYLON.serialize()
  103155. ], GlowLayer.prototype, "blurKernelSize", null);
  103156. __decorate([
  103157. BABYLON.serialize()
  103158. ], GlowLayer.prototype, "intensity", null);
  103159. __decorate([
  103160. BABYLON.serialize("options")
  103161. ], GlowLayer.prototype, "_options", void 0);
  103162. return GlowLayer;
  103163. }(BABYLON.EffectLayer));
  103164. BABYLON.GlowLayer = GlowLayer;
  103165. })(BABYLON || (BABYLON = {}));
  103166. //# sourceMappingURL=babylon.glowLayer.js.map
  103167. var BABYLON;
  103168. (function (BABYLON) {
  103169. /**
  103170. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  103171. */
  103172. var AssetTaskState;
  103173. (function (AssetTaskState) {
  103174. /**
  103175. * Initialization
  103176. */
  103177. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  103178. /**
  103179. * Running
  103180. */
  103181. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  103182. /**
  103183. * Done
  103184. */
  103185. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  103186. /**
  103187. * Error
  103188. */
  103189. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  103190. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  103191. /**
  103192. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  103193. */
  103194. var AbstractAssetTask = /** @class */ (function () {
  103195. /**
  103196. * Creates a new {BABYLON.AssetsManager}
  103197. * @param name defines the name of the task
  103198. */
  103199. function AbstractAssetTask(
  103200. /**
  103201. * Task name
  103202. */ name) {
  103203. this.name = name;
  103204. this._isCompleted = false;
  103205. this._taskState = AssetTaskState.INIT;
  103206. }
  103207. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  103208. /**
  103209. * Get if the task is completed
  103210. */
  103211. get: function () {
  103212. return this._isCompleted;
  103213. },
  103214. enumerable: true,
  103215. configurable: true
  103216. });
  103217. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  103218. /**
  103219. * Gets the current state of the task
  103220. */
  103221. get: function () {
  103222. return this._taskState;
  103223. },
  103224. enumerable: true,
  103225. configurable: true
  103226. });
  103227. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  103228. /**
  103229. * Gets the current error object (if task is in error)
  103230. */
  103231. get: function () {
  103232. return this._errorObject;
  103233. },
  103234. enumerable: true,
  103235. configurable: true
  103236. });
  103237. /**
  103238. * Internal only
  103239. * @hidden
  103240. */
  103241. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  103242. if (this._errorObject) {
  103243. return;
  103244. }
  103245. this._errorObject = {
  103246. message: message,
  103247. exception: exception
  103248. };
  103249. };
  103250. /**
  103251. * Execute the current task
  103252. * @param scene defines the scene where you want your assets to be loaded
  103253. * @param onSuccess is a callback called when the task is successfully executed
  103254. * @param onError is a callback called if an error occurs
  103255. */
  103256. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  103257. var _this = this;
  103258. this._taskState = AssetTaskState.RUNNING;
  103259. this.runTask(scene, function () {
  103260. _this.onDoneCallback(onSuccess, onError);
  103261. }, function (msg, exception) {
  103262. _this.onErrorCallback(onError, msg, exception);
  103263. });
  103264. };
  103265. /**
  103266. * Execute the current task
  103267. * @param scene defines the scene where you want your assets to be loaded
  103268. * @param onSuccess is a callback called when the task is successfully executed
  103269. * @param onError is a callback called if an error occurs
  103270. */
  103271. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103272. throw new Error("runTask is not implemented");
  103273. };
  103274. /**
  103275. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  103276. * This can be used with failed tasks that have the reason for failure fixed.
  103277. */
  103278. AbstractAssetTask.prototype.reset = function () {
  103279. this._taskState = AssetTaskState.INIT;
  103280. };
  103281. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  103282. this._taskState = AssetTaskState.ERROR;
  103283. this._errorObject = {
  103284. message: message,
  103285. exception: exception
  103286. };
  103287. if (this.onError) {
  103288. this.onError(this, message, exception);
  103289. }
  103290. onError();
  103291. };
  103292. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  103293. try {
  103294. this._taskState = AssetTaskState.DONE;
  103295. this._isCompleted = true;
  103296. if (this.onSuccess) {
  103297. this.onSuccess(this);
  103298. }
  103299. onSuccess();
  103300. }
  103301. catch (e) {
  103302. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  103303. }
  103304. };
  103305. return AbstractAssetTask;
  103306. }());
  103307. BABYLON.AbstractAssetTask = AbstractAssetTask;
  103308. /**
  103309. * Class used to share progress information about assets loading
  103310. */
  103311. var AssetsProgressEvent = /** @class */ (function () {
  103312. /**
  103313. * Creates a {BABYLON.AssetsProgressEvent}
  103314. * @param remainingCount defines the number of remaining tasks to process
  103315. * @param totalCount defines the total number of tasks
  103316. * @param task defines the task that was just processed
  103317. */
  103318. function AssetsProgressEvent(remainingCount, totalCount, task) {
  103319. this.remainingCount = remainingCount;
  103320. this.totalCount = totalCount;
  103321. this.task = task;
  103322. }
  103323. return AssetsProgressEvent;
  103324. }());
  103325. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  103326. /**
  103327. * Define a task used by {BABYLON.AssetsManager} to load meshes
  103328. */
  103329. var MeshAssetTask = /** @class */ (function (_super) {
  103330. __extends(MeshAssetTask, _super);
  103331. /**
  103332. * Creates a new {BABYLON.MeshAssetTask}
  103333. * @param name defines the name of the task
  103334. * @param meshesNames defines the list of mesh's names you want to load
  103335. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  103336. * @param sceneFilename defines the filename of the scene to load from
  103337. */
  103338. function MeshAssetTask(
  103339. /**
  103340. * Defines the name of the task
  103341. */
  103342. name,
  103343. /**
  103344. * Defines the list of mesh's names you want to load
  103345. */
  103346. meshesNames,
  103347. /**
  103348. * Defines the root url to use as a base to load your meshes and associated resources
  103349. */
  103350. rootUrl,
  103351. /**
  103352. * Defines the filename of the scene to load from
  103353. */
  103354. sceneFilename) {
  103355. var _this = _super.call(this, name) || this;
  103356. _this.name = name;
  103357. _this.meshesNames = meshesNames;
  103358. _this.rootUrl = rootUrl;
  103359. _this.sceneFilename = sceneFilename;
  103360. return _this;
  103361. }
  103362. /**
  103363. * Execute the current task
  103364. * @param scene defines the scene where you want your assets to be loaded
  103365. * @param onSuccess is a callback called when the task is successfully executed
  103366. * @param onError is a callback called if an error occurs
  103367. */
  103368. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103369. var _this = this;
  103370. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  103371. _this.loadedMeshes = meshes;
  103372. _this.loadedParticleSystems = particleSystems;
  103373. _this.loadedSkeletons = skeletons;
  103374. onSuccess();
  103375. }, null, function (scene, message, exception) {
  103376. onError(message, exception);
  103377. });
  103378. };
  103379. return MeshAssetTask;
  103380. }(AbstractAssetTask));
  103381. BABYLON.MeshAssetTask = MeshAssetTask;
  103382. /**
  103383. * Define a task used by {BABYLON.AssetsManager} to load text content
  103384. */
  103385. var TextFileAssetTask = /** @class */ (function (_super) {
  103386. __extends(TextFileAssetTask, _super);
  103387. /**
  103388. * Creates a new TextFileAssetTask object
  103389. * @param name defines the name of the task
  103390. * @param url defines the location of the file to load
  103391. */
  103392. function TextFileAssetTask(
  103393. /**
  103394. * Defines the name of the task
  103395. */
  103396. name,
  103397. /**
  103398. * Defines the location of the file to load
  103399. */
  103400. url) {
  103401. var _this = _super.call(this, name) || this;
  103402. _this.name = name;
  103403. _this.url = url;
  103404. return _this;
  103405. }
  103406. /**
  103407. * Execute the current task
  103408. * @param scene defines the scene where you want your assets to be loaded
  103409. * @param onSuccess is a callback called when the task is successfully executed
  103410. * @param onError is a callback called if an error occurs
  103411. */
  103412. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103413. var _this = this;
  103414. scene._loadFile(this.url, function (data) {
  103415. _this.text = data;
  103416. onSuccess();
  103417. }, undefined, false, false, function (request, exception) {
  103418. if (request) {
  103419. onError(request.status + " " + request.statusText, exception);
  103420. }
  103421. });
  103422. };
  103423. return TextFileAssetTask;
  103424. }(AbstractAssetTask));
  103425. BABYLON.TextFileAssetTask = TextFileAssetTask;
  103426. /**
  103427. * Define a task used by {BABYLON.AssetsManager} to load binary data
  103428. */
  103429. var BinaryFileAssetTask = /** @class */ (function (_super) {
  103430. __extends(BinaryFileAssetTask, _super);
  103431. /**
  103432. * Creates a new BinaryFileAssetTask object
  103433. * @param name defines the name of the new task
  103434. * @param url defines the location of the file to load
  103435. */
  103436. function BinaryFileAssetTask(
  103437. /**
  103438. * Defines the name of the task
  103439. */
  103440. name,
  103441. /**
  103442. * Defines the location of the file to load
  103443. */
  103444. url) {
  103445. var _this = _super.call(this, name) || this;
  103446. _this.name = name;
  103447. _this.url = url;
  103448. return _this;
  103449. }
  103450. /**
  103451. * Execute the current task
  103452. * @param scene defines the scene where you want your assets to be loaded
  103453. * @param onSuccess is a callback called when the task is successfully executed
  103454. * @param onError is a callback called if an error occurs
  103455. */
  103456. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103457. var _this = this;
  103458. scene._loadFile(this.url, function (data) {
  103459. _this.data = data;
  103460. onSuccess();
  103461. }, undefined, true, true, function (request, exception) {
  103462. if (request) {
  103463. onError(request.status + " " + request.statusText, exception);
  103464. }
  103465. });
  103466. };
  103467. return BinaryFileAssetTask;
  103468. }(AbstractAssetTask));
  103469. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  103470. /**
  103471. * Define a task used by {BABYLON.AssetsManager} to load images
  103472. */
  103473. var ImageAssetTask = /** @class */ (function (_super) {
  103474. __extends(ImageAssetTask, _super);
  103475. /**
  103476. * Creates a new ImageAssetTask
  103477. * @param name defines the name of the task
  103478. * @param url defines the location of the image to load
  103479. */
  103480. function ImageAssetTask(
  103481. /**
  103482. * Defines the name of the task
  103483. */
  103484. name,
  103485. /**
  103486. * Defines the location of the image to load
  103487. */
  103488. url) {
  103489. var _this = _super.call(this, name) || this;
  103490. _this.name = name;
  103491. _this.url = url;
  103492. return _this;
  103493. }
  103494. /**
  103495. * Execute the current task
  103496. * @param scene defines the scene where you want your assets to be loaded
  103497. * @param onSuccess is a callback called when the task is successfully executed
  103498. * @param onError is a callback called if an error occurs
  103499. */
  103500. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103501. var _this = this;
  103502. var img = new Image();
  103503. BABYLON.Tools.SetCorsBehavior(this.url, img);
  103504. img.onload = function () {
  103505. _this.image = img;
  103506. onSuccess();
  103507. };
  103508. img.onerror = function (err) {
  103509. onError("Error loading image", err);
  103510. };
  103511. img.src = this.url;
  103512. };
  103513. return ImageAssetTask;
  103514. }(AbstractAssetTask));
  103515. BABYLON.ImageAssetTask = ImageAssetTask;
  103516. /**
  103517. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  103518. */
  103519. var TextureAssetTask = /** @class */ (function (_super) {
  103520. __extends(TextureAssetTask, _super);
  103521. /**
  103522. * Creates a new TextureAssetTask object
  103523. * @param name defines the name of the task
  103524. * @param url defines the location of the file to load
  103525. * @param noMipmap defines if mipmap should not be generated (default is false)
  103526. * @param invertY defines if texture must be inverted on Y axis (default is false)
  103527. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  103528. */
  103529. function TextureAssetTask(
  103530. /**
  103531. * Defines the name of the task
  103532. */
  103533. name,
  103534. /**
  103535. * Defines the location of the file to load
  103536. */
  103537. url,
  103538. /**
  103539. * Defines if mipmap should not be generated (default is false)
  103540. */
  103541. noMipmap,
  103542. /**
  103543. * Defines if texture must be inverted on Y axis (default is false)
  103544. */
  103545. invertY,
  103546. /**
  103547. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  103548. */
  103549. samplingMode) {
  103550. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  103551. var _this = _super.call(this, name) || this;
  103552. _this.name = name;
  103553. _this.url = url;
  103554. _this.noMipmap = noMipmap;
  103555. _this.invertY = invertY;
  103556. _this.samplingMode = samplingMode;
  103557. return _this;
  103558. }
  103559. /**
  103560. * Execute the current task
  103561. * @param scene defines the scene where you want your assets to be loaded
  103562. * @param onSuccess is a callback called when the task is successfully executed
  103563. * @param onError is a callback called if an error occurs
  103564. */
  103565. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103566. var onload = function () {
  103567. onSuccess();
  103568. };
  103569. var onerror = function (message, exception) {
  103570. onError(message, exception);
  103571. };
  103572. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  103573. };
  103574. return TextureAssetTask;
  103575. }(AbstractAssetTask));
  103576. BABYLON.TextureAssetTask = TextureAssetTask;
  103577. /**
  103578. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  103579. */
  103580. var CubeTextureAssetTask = /** @class */ (function (_super) {
  103581. __extends(CubeTextureAssetTask, _super);
  103582. /**
  103583. * Creates a new CubeTextureAssetTask
  103584. * @param name defines the name of the task
  103585. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  103586. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  103587. * @param noMipmap defines if mipmaps should not be generated (default is false)
  103588. * @param files defines the explicit list of files (undefined by default)
  103589. */
  103590. function CubeTextureAssetTask(
  103591. /**
  103592. * Defines the name of the task
  103593. */
  103594. name,
  103595. /**
  103596. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  103597. */
  103598. url,
  103599. /**
  103600. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  103601. */
  103602. extensions,
  103603. /**
  103604. * Defines if mipmaps should not be generated (default is false)
  103605. */
  103606. noMipmap,
  103607. /**
  103608. * Defines the explicit list of files (undefined by default)
  103609. */
  103610. files) {
  103611. var _this = _super.call(this, name) || this;
  103612. _this.name = name;
  103613. _this.url = url;
  103614. _this.extensions = extensions;
  103615. _this.noMipmap = noMipmap;
  103616. _this.files = files;
  103617. return _this;
  103618. }
  103619. /**
  103620. * Execute the current task
  103621. * @param scene defines the scene where you want your assets to be loaded
  103622. * @param onSuccess is a callback called when the task is successfully executed
  103623. * @param onError is a callback called if an error occurs
  103624. */
  103625. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103626. var onload = function () {
  103627. onSuccess();
  103628. };
  103629. var onerror = function (message, exception) {
  103630. onError(message, exception);
  103631. };
  103632. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  103633. };
  103634. return CubeTextureAssetTask;
  103635. }(AbstractAssetTask));
  103636. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  103637. /**
  103638. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  103639. */
  103640. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  103641. __extends(HDRCubeTextureAssetTask, _super);
  103642. /**
  103643. * Creates a new HDRCubeTextureAssetTask object
  103644. * @param name defines the name of the task
  103645. * @param url defines the location of the file to load
  103646. * @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.
  103647. * @param noMipmap defines if mipmaps should not be generated (default is false)
  103648. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  103649. * @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)
  103650. * @param reserved Internal use only
  103651. */
  103652. function HDRCubeTextureAssetTask(
  103653. /**
  103654. * Defines the name of the task
  103655. */
  103656. name,
  103657. /**
  103658. * Defines the location of the file to load
  103659. */
  103660. url,
  103661. /**
  103662. * Defines the desired size (the more it increases the longer the generation will be)
  103663. */
  103664. size,
  103665. /**
  103666. * Defines if mipmaps should not be generated (default is false)
  103667. */
  103668. noMipmap,
  103669. /**
  103670. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  103671. */
  103672. generateHarmonics,
  103673. /**
  103674. * 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)
  103675. */
  103676. gammaSpace,
  103677. /**
  103678. * Internal Use Only
  103679. */
  103680. reserved) {
  103681. if (noMipmap === void 0) { noMipmap = false; }
  103682. if (generateHarmonics === void 0) { generateHarmonics = true; }
  103683. if (gammaSpace === void 0) { gammaSpace = false; }
  103684. if (reserved === void 0) { reserved = false; }
  103685. var _this = _super.call(this, name) || this;
  103686. _this.name = name;
  103687. _this.url = url;
  103688. _this.size = size;
  103689. _this.noMipmap = noMipmap;
  103690. _this.generateHarmonics = generateHarmonics;
  103691. _this.gammaSpace = gammaSpace;
  103692. _this.reserved = reserved;
  103693. return _this;
  103694. }
  103695. /**
  103696. * Execute the current task
  103697. * @param scene defines the scene where you want your assets to be loaded
  103698. * @param onSuccess is a callback called when the task is successfully executed
  103699. * @param onError is a callback called if an error occurs
  103700. */
  103701. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  103702. var onload = function () {
  103703. onSuccess();
  103704. };
  103705. var onerror = function (message, exception) {
  103706. onError(message, exception);
  103707. };
  103708. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  103709. };
  103710. return HDRCubeTextureAssetTask;
  103711. }(AbstractAssetTask));
  103712. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  103713. /**
  103714. * This class can be used to easily import assets into a scene
  103715. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  103716. */
  103717. var AssetsManager = /** @class */ (function () {
  103718. /**
  103719. * Creates a new AssetsManager
  103720. * @param scene defines the scene to work on
  103721. */
  103722. function AssetsManager(scene) {
  103723. this._isLoading = false;
  103724. this._tasks = new Array();
  103725. this._waitingTasksCount = 0;
  103726. this._totalTasksCount = 0;
  103727. /**
  103728. * Observable called when all tasks are processed
  103729. */
  103730. this.onTaskSuccessObservable = new BABYLON.Observable();
  103731. /**
  103732. * Observable called when a task had an error
  103733. */
  103734. this.onTaskErrorObservable = new BABYLON.Observable();
  103735. /**
  103736. * Observable called when a task is successful
  103737. */
  103738. this.onTasksDoneObservable = new BABYLON.Observable();
  103739. /**
  103740. * Observable called when a task is done (whatever the result is)
  103741. */
  103742. this.onProgressObservable = new BABYLON.Observable();
  103743. /**
  103744. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  103745. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  103746. */
  103747. this.useDefaultLoadingScreen = true;
  103748. this._scene = scene;
  103749. }
  103750. /**
  103751. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  103752. * @param taskName defines the name of the new task
  103753. * @param meshesNames defines the name of meshes to load
  103754. * @param rootUrl defines the root url to use to locate files
  103755. * @param sceneFilename defines the filename of the scene file
  103756. * @returns a new {BABYLON.MeshAssetTask} object
  103757. */
  103758. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  103759. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  103760. this._tasks.push(task);
  103761. return task;
  103762. };
  103763. /**
  103764. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  103765. * @param taskName defines the name of the new task
  103766. * @param url defines the url of the file to load
  103767. * @returns a new {BABYLON.TextFileAssetTask} object
  103768. */
  103769. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  103770. var task = new TextFileAssetTask(taskName, url);
  103771. this._tasks.push(task);
  103772. return task;
  103773. };
  103774. /**
  103775. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  103776. * @param taskName defines the name of the new task
  103777. * @param url defines the url of the file to load
  103778. * @returns a new {BABYLON.BinaryFileAssetTask} object
  103779. */
  103780. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  103781. var task = new BinaryFileAssetTask(taskName, url);
  103782. this._tasks.push(task);
  103783. return task;
  103784. };
  103785. /**
  103786. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  103787. * @param taskName defines the name of the new task
  103788. * @param url defines the url of the file to load
  103789. * @returns a new {BABYLON.ImageAssetTask} object
  103790. */
  103791. AssetsManager.prototype.addImageTask = function (taskName, url) {
  103792. var task = new ImageAssetTask(taskName, url);
  103793. this._tasks.push(task);
  103794. return task;
  103795. };
  103796. /**
  103797. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  103798. * @param taskName defines the name of the new task
  103799. * @param url defines the url of the file to load
  103800. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  103801. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  103802. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  103803. * @returns a new {BABYLON.TextureAssetTask} object
  103804. */
  103805. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  103806. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  103807. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  103808. this._tasks.push(task);
  103809. return task;
  103810. };
  103811. /**
  103812. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  103813. * @param taskName defines the name of the new task
  103814. * @param url defines the url of the file to load
  103815. * @param extensions defines the extension to use to load the cube map (can be null)
  103816. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  103817. * @param files defines the list of files to load (can be null)
  103818. * @returns a new {BABYLON.CubeTextureAssetTask} object
  103819. */
  103820. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  103821. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  103822. this._tasks.push(task);
  103823. return task;
  103824. };
  103825. /**
  103826. *
  103827. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  103828. * @param taskName defines the name of the new task
  103829. * @param url defines the url of the file to load
  103830. * @param size defines the size you want for the cubemap (can be null)
  103831. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  103832. * @param generateHarmonics defines if you want to automatically generate (true by default)
  103833. * @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)
  103834. * @param reserved Internal use only
  103835. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  103836. */
  103837. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  103838. if (noMipmap === void 0) { noMipmap = false; }
  103839. if (generateHarmonics === void 0) { generateHarmonics = true; }
  103840. if (gammaSpace === void 0) { gammaSpace = false; }
  103841. if (reserved === void 0) { reserved = false; }
  103842. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  103843. this._tasks.push(task);
  103844. return task;
  103845. };
  103846. /**
  103847. * Remove a task from the assets manager.
  103848. * @param task the task to remove
  103849. */
  103850. AssetsManager.prototype.removeTask = function (task) {
  103851. var index = this._tasks.indexOf(task);
  103852. if (index > -1) {
  103853. this._tasks.splice(index, 1);
  103854. }
  103855. };
  103856. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  103857. this._waitingTasksCount--;
  103858. try {
  103859. if (this.onProgress) {
  103860. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  103861. }
  103862. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  103863. }
  103864. catch (e) {
  103865. BABYLON.Tools.Error("Error running progress callbacks.");
  103866. console.log(e);
  103867. }
  103868. if (this._waitingTasksCount === 0) {
  103869. try {
  103870. if (this.onFinish) {
  103871. this.onFinish(this._tasks);
  103872. }
  103873. // Let's remove successfull tasks
  103874. var currentTasks = this._tasks.slice();
  103875. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  103876. var task = currentTasks_1[_i];
  103877. if (task.taskState === AssetTaskState.DONE) {
  103878. var index = this._tasks.indexOf(task);
  103879. if (index > -1) {
  103880. this._tasks.splice(index, 1);
  103881. }
  103882. }
  103883. }
  103884. this.onTasksDoneObservable.notifyObservers(this._tasks);
  103885. }
  103886. catch (e) {
  103887. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  103888. console.log(e);
  103889. }
  103890. this._isLoading = false;
  103891. this._scene.getEngine().hideLoadingUI();
  103892. }
  103893. };
  103894. AssetsManager.prototype._runTask = function (task) {
  103895. var _this = this;
  103896. var done = function () {
  103897. try {
  103898. if (_this.onTaskSuccess) {
  103899. _this.onTaskSuccess(task);
  103900. }
  103901. _this.onTaskSuccessObservable.notifyObservers(task);
  103902. _this._decreaseWaitingTasksCount(task);
  103903. }
  103904. catch (e) {
  103905. error("Error executing task success callbacks", e);
  103906. }
  103907. };
  103908. var error = function (message, exception) {
  103909. task._setErrorObject(message, exception);
  103910. if (_this.onTaskError) {
  103911. _this.onTaskError(task);
  103912. }
  103913. _this.onTaskErrorObservable.notifyObservers(task);
  103914. _this._decreaseWaitingTasksCount(task);
  103915. };
  103916. task.run(this._scene, done, error);
  103917. };
  103918. /**
  103919. * Reset the {BABYLON.AssetsManager} and remove all tasks
  103920. * @return the current instance of the {BABYLON.AssetsManager}
  103921. */
  103922. AssetsManager.prototype.reset = function () {
  103923. this._isLoading = false;
  103924. this._tasks = new Array();
  103925. return this;
  103926. };
  103927. /**
  103928. * Start the loading process
  103929. * @return the current instance of the {BABYLON.AssetsManager}
  103930. */
  103931. AssetsManager.prototype.load = function () {
  103932. if (this._isLoading) {
  103933. return this;
  103934. }
  103935. this._isLoading = true;
  103936. this._waitingTasksCount = this._tasks.length;
  103937. this._totalTasksCount = this._tasks.length;
  103938. if (this._waitingTasksCount === 0) {
  103939. this._isLoading = false;
  103940. if (this.onFinish) {
  103941. this.onFinish(this._tasks);
  103942. }
  103943. this.onTasksDoneObservable.notifyObservers(this._tasks);
  103944. return this;
  103945. }
  103946. if (this.useDefaultLoadingScreen) {
  103947. this._scene.getEngine().displayLoadingUI();
  103948. }
  103949. for (var index = 0; index < this._tasks.length; index++) {
  103950. var task = this._tasks[index];
  103951. if (task.taskState === AssetTaskState.INIT) {
  103952. this._runTask(task);
  103953. }
  103954. }
  103955. return this;
  103956. };
  103957. return AssetsManager;
  103958. }());
  103959. BABYLON.AssetsManager = AssetsManager;
  103960. })(BABYLON || (BABYLON = {}));
  103961. //# sourceMappingURL=babylon.assetsManager.js.map
  103962. var BABYLON;
  103963. (function (BABYLON) {
  103964. var serializedGeometries = [];
  103965. var serializeGeometry = function (geometry, serializationGeometries) {
  103966. if (serializedGeometries[geometry.id]) {
  103967. return;
  103968. }
  103969. if (geometry.doNotSerialize) {
  103970. return;
  103971. }
  103972. if (geometry instanceof BABYLON.BoxGeometry) {
  103973. serializationGeometries.boxes.push(geometry.serialize());
  103974. }
  103975. else if (geometry instanceof BABYLON.SphereGeometry) {
  103976. serializationGeometries.spheres.push(geometry.serialize());
  103977. }
  103978. else if (geometry instanceof BABYLON.CylinderGeometry) {
  103979. serializationGeometries.cylinders.push(geometry.serialize());
  103980. }
  103981. else if (geometry instanceof BABYLON.TorusGeometry) {
  103982. serializationGeometries.toruses.push(geometry.serialize());
  103983. }
  103984. else if (geometry instanceof BABYLON.GroundGeometry) {
  103985. serializationGeometries.grounds.push(geometry.serialize());
  103986. }
  103987. else if (geometry instanceof BABYLON.Plane) {
  103988. serializationGeometries.planes.push(geometry.serialize());
  103989. }
  103990. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  103991. serializationGeometries.torusKnots.push(geometry.serialize());
  103992. }
  103993. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  103994. throw new Error("Unknown primitive type");
  103995. }
  103996. else {
  103997. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  103998. }
  103999. serializedGeometries[geometry.id] = true;
  104000. };
  104001. var serializeMesh = function (mesh, serializationScene) {
  104002. var serializationObject = {};
  104003. // Geometry
  104004. var geometry = mesh._geometry;
  104005. if (geometry) {
  104006. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  104007. // 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
  104008. serializeGeometry(geometry, serializationScene.geometries);
  104009. }
  104010. }
  104011. // Custom
  104012. if (mesh.serialize) {
  104013. mesh.serialize(serializationObject);
  104014. }
  104015. return serializationObject;
  104016. };
  104017. var finalizeSingleMesh = function (mesh, serializationObject) {
  104018. //only works if the mesh is already loaded
  104019. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  104020. //serialize material
  104021. if (mesh.material) {
  104022. if (mesh.material instanceof BABYLON.MultiMaterial) {
  104023. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  104024. serializationObject.materials = serializationObject.materials || [];
  104025. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  104026. serializationObject.multiMaterials.push(mesh.material.serialize());
  104027. var _loop_1 = function (submaterial) {
  104028. if (submaterial) {
  104029. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  104030. serializationObject.materials.push(submaterial.serialize());
  104031. }
  104032. }
  104033. };
  104034. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  104035. var submaterial = _a[_i];
  104036. _loop_1(submaterial);
  104037. }
  104038. }
  104039. }
  104040. else {
  104041. serializationObject.materials = serializationObject.materials || [];
  104042. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  104043. serializationObject.materials.push(mesh.material.serialize());
  104044. }
  104045. }
  104046. }
  104047. //serialize geometry
  104048. var geometry = mesh._geometry;
  104049. if (geometry) {
  104050. if (!serializationObject.geometries) {
  104051. serializationObject.geometries = {};
  104052. serializationObject.geometries.boxes = [];
  104053. serializationObject.geometries.spheres = [];
  104054. serializationObject.geometries.cylinders = [];
  104055. serializationObject.geometries.toruses = [];
  104056. serializationObject.geometries.grounds = [];
  104057. serializationObject.geometries.planes = [];
  104058. serializationObject.geometries.torusKnots = [];
  104059. serializationObject.geometries.vertexData = [];
  104060. }
  104061. serializeGeometry(geometry, serializationObject.geometries);
  104062. }
  104063. // Skeletons
  104064. if (mesh.skeleton) {
  104065. serializationObject.skeletons = serializationObject.skeletons || [];
  104066. serializationObject.skeletons.push(mesh.skeleton.serialize());
  104067. }
  104068. //serialize the actual mesh
  104069. serializationObject.meshes = serializationObject.meshes || [];
  104070. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  104071. }
  104072. };
  104073. var SceneSerializer = /** @class */ (function () {
  104074. function SceneSerializer() {
  104075. }
  104076. SceneSerializer.ClearCache = function () {
  104077. serializedGeometries = [];
  104078. };
  104079. SceneSerializer.Serialize = function (scene) {
  104080. var serializationObject = {};
  104081. SceneSerializer.ClearCache();
  104082. // Scene
  104083. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  104084. serializationObject.autoClear = scene.autoClear;
  104085. serializationObject.clearColor = scene.clearColor.asArray();
  104086. serializationObject.ambientColor = scene.ambientColor.asArray();
  104087. serializationObject.gravity = scene.gravity.asArray();
  104088. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  104089. serializationObject.workerCollisions = scene.workerCollisions;
  104090. // Fog
  104091. if (scene.fogMode && scene.fogMode !== 0) {
  104092. serializationObject.fogMode = scene.fogMode;
  104093. serializationObject.fogColor = scene.fogColor.asArray();
  104094. serializationObject.fogStart = scene.fogStart;
  104095. serializationObject.fogEnd = scene.fogEnd;
  104096. serializationObject.fogDensity = scene.fogDensity;
  104097. }
  104098. //Physics
  104099. if (scene.isPhysicsEnabled()) {
  104100. var physicEngine = scene.getPhysicsEngine();
  104101. if (physicEngine) {
  104102. serializationObject.physicsEnabled = true;
  104103. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  104104. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  104105. }
  104106. }
  104107. // Metadata
  104108. if (scene.metadata) {
  104109. serializationObject.metadata = scene.metadata;
  104110. }
  104111. // Morph targets
  104112. serializationObject.morphTargetManagers = [];
  104113. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  104114. var abstractMesh = _a[_i];
  104115. var manager = abstractMesh.morphTargetManager;
  104116. if (manager) {
  104117. serializationObject.morphTargetManagers.push(manager.serialize());
  104118. }
  104119. }
  104120. // Lights
  104121. serializationObject.lights = [];
  104122. var index;
  104123. var light;
  104124. for (index = 0; index < scene.lights.length; index++) {
  104125. light = scene.lights[index];
  104126. if (!light.doNotSerialize) {
  104127. serializationObject.lights.push(light.serialize());
  104128. }
  104129. }
  104130. // Cameras
  104131. serializationObject.cameras = [];
  104132. for (index = 0; index < scene.cameras.length; index++) {
  104133. var camera = scene.cameras[index];
  104134. if (!camera.doNotSerialize) {
  104135. serializationObject.cameras.push(camera.serialize());
  104136. }
  104137. }
  104138. if (scene.activeCamera) {
  104139. serializationObject.activeCameraID = scene.activeCamera.id;
  104140. }
  104141. // Animations
  104142. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  104143. // Materials
  104144. serializationObject.materials = [];
  104145. serializationObject.multiMaterials = [];
  104146. var material;
  104147. for (index = 0; index < scene.materials.length; index++) {
  104148. material = scene.materials[index];
  104149. if (!material.doNotSerialize) {
  104150. serializationObject.materials.push(material.serialize());
  104151. }
  104152. }
  104153. // MultiMaterials
  104154. serializationObject.multiMaterials = [];
  104155. for (index = 0; index < scene.multiMaterials.length; index++) {
  104156. var multiMaterial = scene.multiMaterials[index];
  104157. serializationObject.multiMaterials.push(multiMaterial.serialize());
  104158. }
  104159. // Environment texture
  104160. if (scene.environmentTexture) {
  104161. serializationObject.environmentTexture = scene.environmentTexture.name;
  104162. }
  104163. // Skeletons
  104164. serializationObject.skeletons = [];
  104165. for (index = 0; index < scene.skeletons.length; index++) {
  104166. var skeleton = scene.skeletons[index];
  104167. if (!skeleton.doNotSerialize) {
  104168. serializationObject.skeletons.push(skeleton.serialize());
  104169. }
  104170. }
  104171. // Transform nodes
  104172. serializationObject.transformNodes = [];
  104173. for (index = 0; index < scene.transformNodes.length; index++) {
  104174. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  104175. }
  104176. // Geometries
  104177. serializationObject.geometries = {};
  104178. serializationObject.geometries.boxes = [];
  104179. serializationObject.geometries.spheres = [];
  104180. serializationObject.geometries.cylinders = [];
  104181. serializationObject.geometries.toruses = [];
  104182. serializationObject.geometries.grounds = [];
  104183. serializationObject.geometries.planes = [];
  104184. serializationObject.geometries.torusKnots = [];
  104185. serializationObject.geometries.vertexData = [];
  104186. serializedGeometries = [];
  104187. var geometries = scene.getGeometries();
  104188. for (index = 0; index < geometries.length; index++) {
  104189. var geometry = geometries[index];
  104190. if (geometry.isReady()) {
  104191. serializeGeometry(geometry, serializationObject.geometries);
  104192. }
  104193. }
  104194. // Meshes
  104195. serializationObject.meshes = [];
  104196. for (index = 0; index < scene.meshes.length; index++) {
  104197. var abstractMesh = scene.meshes[index];
  104198. if (abstractMesh instanceof BABYLON.Mesh) {
  104199. var mesh = abstractMesh;
  104200. if (!mesh.doNotSerialize) {
  104201. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  104202. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  104203. }
  104204. }
  104205. }
  104206. }
  104207. // Particles Systems
  104208. serializationObject.particleSystems = [];
  104209. for (index = 0; index < scene.particleSystems.length; index++) {
  104210. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  104211. }
  104212. // Action Manager
  104213. if (scene.actionManager) {
  104214. serializationObject.actions = scene.actionManager.serialize("scene");
  104215. }
  104216. // Audio
  104217. serializationObject.sounds = [];
  104218. for (index = 0; index < scene.soundTracks.length; index++) {
  104219. var soundtrack = scene.soundTracks[index];
  104220. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  104221. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  104222. }
  104223. }
  104224. // Components
  104225. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  104226. var component = _c[_b];
  104227. component.serialize(serializationObject);
  104228. }
  104229. return serializationObject;
  104230. };
  104231. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  104232. if (withParents === void 0) { withParents = false; }
  104233. if (withChildren === void 0) { withChildren = false; }
  104234. var serializationObject = {};
  104235. SceneSerializer.ClearCache();
  104236. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  104237. if (withParents || withChildren) {
  104238. //deliberate for loop! not for each, appended should be processed as well.
  104239. for (var i = 0; i < toSerialize.length; ++i) {
  104240. if (withChildren) {
  104241. toSerialize[i].getDescendants().forEach(function (node) {
  104242. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  104243. toSerialize.push(node);
  104244. }
  104245. });
  104246. }
  104247. //make sure the array doesn't contain the object already
  104248. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  104249. toSerialize.push(toSerialize[i].parent);
  104250. }
  104251. }
  104252. }
  104253. toSerialize.forEach(function (mesh) {
  104254. finalizeSingleMesh(mesh, serializationObject);
  104255. });
  104256. return serializationObject;
  104257. };
  104258. return SceneSerializer;
  104259. }());
  104260. BABYLON.SceneSerializer = SceneSerializer;
  104261. })(BABYLON || (BABYLON = {}));
  104262. //# sourceMappingURL=babylon.sceneSerializer.js.map
  104263. var BABYLON;
  104264. (function (BABYLON) {
  104265. /**
  104266. * Class used to generate realtime reflection / refraction cube textures
  104267. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  104268. */
  104269. var ReflectionProbe = /** @class */ (function () {
  104270. /**
  104271. * Creates a new reflection probe
  104272. * @param name defines the name of the probe
  104273. * @param size defines the texture resolution (for each face)
  104274. * @param scene defines the hosting scene
  104275. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  104276. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  104277. */
  104278. function ReflectionProbe(
  104279. /** defines the name of the probe */
  104280. name, size, scene, generateMipMaps, useFloat) {
  104281. if (generateMipMaps === void 0) { generateMipMaps = true; }
  104282. if (useFloat === void 0) { useFloat = false; }
  104283. var _this = this;
  104284. this.name = name;
  104285. this._viewMatrix = BABYLON.Matrix.Identity();
  104286. this._target = BABYLON.Vector3.Zero();
  104287. this._add = BABYLON.Vector3.Zero();
  104288. this._invertYAxis = false;
  104289. /** Gets or sets probe position (center of the cube map) */
  104290. this.position = BABYLON.Vector3.Zero();
  104291. this._scene = scene;
  104292. // Create the scene field if not exist.
  104293. if (!this._scene.reflectionProbes) {
  104294. this._scene.reflectionProbes = new Array();
  104295. }
  104296. this._scene.reflectionProbes.push(this);
  104297. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  104298. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  104299. switch (faceIndex) {
  104300. case 0:
  104301. _this._add.copyFromFloats(1, 0, 0);
  104302. break;
  104303. case 1:
  104304. _this._add.copyFromFloats(-1, 0, 0);
  104305. break;
  104306. case 2:
  104307. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  104308. break;
  104309. case 3:
  104310. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  104311. break;
  104312. case 4:
  104313. _this._add.copyFromFloats(0, 0, 1);
  104314. break;
  104315. case 5:
  104316. _this._add.copyFromFloats(0, 0, -1);
  104317. break;
  104318. }
  104319. if (_this._attachedMesh) {
  104320. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  104321. }
  104322. _this.position.addToRef(_this._add, _this._target);
  104323. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  104324. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  104325. scene._forcedViewPosition = _this.position;
  104326. });
  104327. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  104328. scene._forcedViewPosition = null;
  104329. scene.updateTransformMatrix(true);
  104330. });
  104331. if (scene.activeCamera) {
  104332. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  104333. }
  104334. }
  104335. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  104336. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  104337. get: function () {
  104338. return this._renderTargetTexture.samples;
  104339. },
  104340. set: function (value) {
  104341. this._renderTargetTexture.samples = value;
  104342. },
  104343. enumerable: true,
  104344. configurable: true
  104345. });
  104346. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  104347. /** Gets or sets the refresh rate to use (on every frame by default) */
  104348. get: function () {
  104349. return this._renderTargetTexture.refreshRate;
  104350. },
  104351. set: function (value) {
  104352. this._renderTargetTexture.refreshRate = value;
  104353. },
  104354. enumerable: true,
  104355. configurable: true
  104356. });
  104357. /**
  104358. * Gets the hosting scene
  104359. * @returns a Scene
  104360. */
  104361. ReflectionProbe.prototype.getScene = function () {
  104362. return this._scene;
  104363. };
  104364. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  104365. /** Gets the internal CubeTexture used to render to */
  104366. get: function () {
  104367. return this._renderTargetTexture;
  104368. },
  104369. enumerable: true,
  104370. configurable: true
  104371. });
  104372. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  104373. /** Gets the list of meshes to render */
  104374. get: function () {
  104375. return this._renderTargetTexture.renderList;
  104376. },
  104377. enumerable: true,
  104378. configurable: true
  104379. });
  104380. /**
  104381. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  104382. * @param mesh defines the mesh to attach to
  104383. */
  104384. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  104385. this._attachedMesh = mesh;
  104386. };
  104387. /**
  104388. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  104389. * @param renderingGroupId The rendering group id corresponding to its index
  104390. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  104391. */
  104392. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  104393. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  104394. };
  104395. /**
  104396. * Clean all associated resources
  104397. */
  104398. ReflectionProbe.prototype.dispose = function () {
  104399. var index = this._scene.reflectionProbes.indexOf(this);
  104400. if (index !== -1) {
  104401. // Remove from the scene if found
  104402. this._scene.reflectionProbes.splice(index, 1);
  104403. }
  104404. if (this._renderTargetTexture) {
  104405. this._renderTargetTexture.dispose();
  104406. this._renderTargetTexture = null;
  104407. }
  104408. };
  104409. return ReflectionProbe;
  104410. }());
  104411. BABYLON.ReflectionProbe = ReflectionProbe;
  104412. })(BABYLON || (BABYLON = {}));
  104413. //# sourceMappingURL=babylon.reflectionProbe.js.map
  104414. var BABYLON;
  104415. (function (BABYLON) {
  104416. /**
  104417. * Defines the layer scene component responsible to manage any layers
  104418. * in a given scene.
  104419. */
  104420. var LayerSceneComponent = /** @class */ (function () {
  104421. /**
  104422. * Creates a new instance of the component for the given scene
  104423. * @param scene Defines the scene to register the component in
  104424. */
  104425. function LayerSceneComponent(scene) {
  104426. /**
  104427. * The component name helpfull to identify the component in the list of scene components.
  104428. */
  104429. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  104430. this.scene = scene;
  104431. this._engine = scene.getEngine();
  104432. scene.layers = new Array();
  104433. }
  104434. /**
  104435. * Registers the component in a given scene
  104436. */
  104437. LayerSceneComponent.prototype.register = function () {
  104438. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  104439. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  104440. };
  104441. /**
  104442. * Rebuilds the elements related to this component in case of
  104443. * context lost for instance.
  104444. */
  104445. LayerSceneComponent.prototype.rebuild = function () {
  104446. var layers = this.scene.layers;
  104447. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  104448. var layer = layers_1[_i];
  104449. layer._rebuild();
  104450. }
  104451. };
  104452. /**
  104453. * Disposes the component and the associated ressources.
  104454. */
  104455. LayerSceneComponent.prototype.dispose = function () {
  104456. var layers = this.scene.layers;
  104457. while (layers.length) {
  104458. layers[0].dispose();
  104459. }
  104460. };
  104461. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  104462. var layers = this.scene.layers;
  104463. if (layers.length) {
  104464. this._engine.setDepthBuffer(false);
  104465. var cameraLayerMask = camera.layerMask;
  104466. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  104467. var layer = layers_2[_i];
  104468. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  104469. layer.render();
  104470. }
  104471. }
  104472. this._engine.setDepthBuffer(true);
  104473. }
  104474. };
  104475. LayerSceneComponent.prototype._drawBackground = function (camera) {
  104476. this._draw(camera, true);
  104477. };
  104478. LayerSceneComponent.prototype._drawForeground = function (camera) {
  104479. this._draw(camera, false);
  104480. };
  104481. return LayerSceneComponent;
  104482. }());
  104483. BABYLON.LayerSceneComponent = LayerSceneComponent;
  104484. })(BABYLON || (BABYLON = {}));
  104485. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  104486. var BABYLON;
  104487. (function (BABYLON) {
  104488. var Layer = /** @class */ (function () {
  104489. function Layer(name, imgUrl, scene, isBackground, color) {
  104490. this.name = name;
  104491. this.scale = new BABYLON.Vector2(1, 1);
  104492. this.offset = new BABYLON.Vector2(0, 0);
  104493. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  104494. this.layerMask = 0x0FFFFFFF;
  104495. this._vertexBuffers = {};
  104496. // Events
  104497. /**
  104498. * An event triggered when the layer is disposed.
  104499. */
  104500. this.onDisposeObservable = new BABYLON.Observable();
  104501. /**
  104502. * An event triggered before rendering the scene
  104503. */
  104504. this.onBeforeRenderObservable = new BABYLON.Observable();
  104505. /**
  104506. * An event triggered after rendering the scene
  104507. */
  104508. this.onAfterRenderObservable = new BABYLON.Observable();
  104509. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  104510. this.isBackground = isBackground === undefined ? true : isBackground;
  104511. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  104512. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  104513. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  104514. if (!layerComponent) {
  104515. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  104516. this._scene._addComponent(layerComponent);
  104517. }
  104518. this._scene.layers.push(this);
  104519. var engine = this._scene.getEngine();
  104520. // VBO
  104521. var vertices = [];
  104522. vertices.push(1, 1);
  104523. vertices.push(-1, 1);
  104524. vertices.push(-1, -1);
  104525. vertices.push(1, -1);
  104526. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  104527. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  104528. this._createIndexBuffer();
  104529. // Effects
  104530. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  104531. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  104532. }
  104533. Object.defineProperty(Layer.prototype, "onDispose", {
  104534. set: function (callback) {
  104535. if (this._onDisposeObserver) {
  104536. this.onDisposeObservable.remove(this._onDisposeObserver);
  104537. }
  104538. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  104539. },
  104540. enumerable: true,
  104541. configurable: true
  104542. });
  104543. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  104544. set: function (callback) {
  104545. if (this._onBeforeRenderObserver) {
  104546. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  104547. }
  104548. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  104549. },
  104550. enumerable: true,
  104551. configurable: true
  104552. });
  104553. Object.defineProperty(Layer.prototype, "onAfterRender", {
  104554. set: function (callback) {
  104555. if (this._onAfterRenderObserver) {
  104556. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  104557. }
  104558. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  104559. },
  104560. enumerable: true,
  104561. configurable: true
  104562. });
  104563. Layer.prototype._createIndexBuffer = function () {
  104564. var engine = this._scene.getEngine();
  104565. // Indices
  104566. var indices = [];
  104567. indices.push(0);
  104568. indices.push(1);
  104569. indices.push(2);
  104570. indices.push(0);
  104571. indices.push(2);
  104572. indices.push(3);
  104573. this._indexBuffer = engine.createIndexBuffer(indices);
  104574. };
  104575. /** @hidden */
  104576. Layer.prototype._rebuild = function () {
  104577. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  104578. if (vb) {
  104579. vb._rebuild();
  104580. }
  104581. this._createIndexBuffer();
  104582. };
  104583. Layer.prototype.render = function () {
  104584. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  104585. // Check
  104586. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  104587. return;
  104588. var engine = this._scene.getEngine();
  104589. this.onBeforeRenderObservable.notifyObservers(this);
  104590. // Render
  104591. engine.enableEffect(currentEffect);
  104592. engine.setState(false);
  104593. // Texture
  104594. currentEffect.setTexture("textureSampler", this.texture);
  104595. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  104596. // Color
  104597. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  104598. // Scale / offset
  104599. currentEffect.setVector2("offset", this.offset);
  104600. currentEffect.setVector2("scale", this.scale);
  104601. // VBOs
  104602. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  104603. // Draw order
  104604. if (!this.alphaTest) {
  104605. engine.setAlphaMode(this.alphaBlendingMode);
  104606. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  104607. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  104608. }
  104609. else {
  104610. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  104611. }
  104612. this.onAfterRenderObservable.notifyObservers(this);
  104613. };
  104614. Layer.prototype.dispose = function () {
  104615. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  104616. if (vertexBuffer) {
  104617. vertexBuffer.dispose();
  104618. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  104619. }
  104620. if (this._indexBuffer) {
  104621. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  104622. this._indexBuffer = null;
  104623. }
  104624. if (this.texture) {
  104625. this.texture.dispose();
  104626. this.texture = null;
  104627. }
  104628. // Remove from scene
  104629. var index = this._scene.layers.indexOf(this);
  104630. this._scene.layers.splice(index, 1);
  104631. // Callback
  104632. this.onDisposeObservable.notifyObservers(this);
  104633. this.onDisposeObservable.clear();
  104634. this.onAfterRenderObservable.clear();
  104635. this.onBeforeRenderObservable.clear();
  104636. };
  104637. return Layer;
  104638. }());
  104639. BABYLON.Layer = Layer;
  104640. })(BABYLON || (BABYLON = {}));
  104641. //# sourceMappingURL=babylon.layer.js.map
  104642. var BABYLON;
  104643. (function (BABYLON) {
  104644. var TextureTools = /** @class */ (function () {
  104645. function TextureTools() {
  104646. }
  104647. /**
  104648. * Uses the GPU to create a copy texture rescaled at a given size
  104649. * @param texture Texture to copy from
  104650. * @param width Desired width
  104651. * @param height Desired height
  104652. * @return Generated texture
  104653. */
  104654. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  104655. if (useBilinearMode === void 0) { useBilinearMode = true; }
  104656. var scene = texture.getScene();
  104657. var engine = scene.getEngine();
  104658. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  104659. rtt.wrapU = texture.wrapU;
  104660. rtt.wrapV = texture.wrapV;
  104661. rtt.uOffset = texture.uOffset;
  104662. rtt.vOffset = texture.vOffset;
  104663. rtt.uScale = texture.uScale;
  104664. rtt.vScale = texture.vScale;
  104665. rtt.uAng = texture.uAng;
  104666. rtt.vAng = texture.vAng;
  104667. rtt.wAng = texture.wAng;
  104668. rtt.coordinatesIndex = texture.coordinatesIndex;
  104669. rtt.level = texture.level;
  104670. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  104671. rtt._texture.isReady = false;
  104672. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104673. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104674. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  104675. passPostProcess.getEffect().executeWhenCompiled(function () {
  104676. passPostProcess.onApply = function (effect) {
  104677. effect.setTexture("textureSampler", texture);
  104678. };
  104679. var internalTexture = rtt.getInternalTexture();
  104680. if (internalTexture) {
  104681. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  104682. engine.unBindFramebuffer(internalTexture);
  104683. rtt.disposeFramebufferObjects();
  104684. passPostProcess.dispose();
  104685. internalTexture.isReady = true;
  104686. }
  104687. });
  104688. return rtt;
  104689. };
  104690. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  104691. if (!scene._environmentBRDFTexture) {
  104692. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  104693. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104694. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104695. scene._environmentBRDFTexture = texture;
  104696. }
  104697. return scene._environmentBRDFTexture;
  104698. };
  104699. 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=";
  104700. return TextureTools;
  104701. }());
  104702. BABYLON.TextureTools = TextureTools;
  104703. })(BABYLON || (BABYLON = {}));
  104704. //# sourceMappingURL=babylon.textureTools.js.map
  104705. var BABYLON;
  104706. (function (BABYLON) {
  104707. var FramingBehavior = /** @class */ (function () {
  104708. function FramingBehavior() {
  104709. this._mode = FramingBehavior.FitFrustumSidesMode;
  104710. this._radiusScale = 1.0;
  104711. this._positionScale = 0.5;
  104712. this._defaultElevation = 0.3;
  104713. this._elevationReturnTime = 1500;
  104714. this._elevationReturnWaitTime = 1000;
  104715. this._zoomStopsAnimation = false;
  104716. this._framingTime = 1500;
  104717. this._isPointerDown = false;
  104718. this._lastInteractionTime = -Infinity;
  104719. // Framing control
  104720. this._animatables = new Array();
  104721. this._betaIsAnimating = false;
  104722. }
  104723. Object.defineProperty(FramingBehavior.prototype, "name", {
  104724. get: function () {
  104725. return "Framing";
  104726. },
  104727. enumerable: true,
  104728. configurable: true
  104729. });
  104730. Object.defineProperty(FramingBehavior.prototype, "mode", {
  104731. /**
  104732. * Gets current mode used by the behavior.
  104733. */
  104734. get: function () {
  104735. return this._mode;
  104736. },
  104737. /**
  104738. * Sets the current mode used by the behavior
  104739. */
  104740. set: function (mode) {
  104741. this._mode = mode;
  104742. },
  104743. enumerable: true,
  104744. configurable: true
  104745. });
  104746. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  104747. /**
  104748. * Gets the scale applied to the radius
  104749. */
  104750. get: function () {
  104751. return this._radiusScale;
  104752. },
  104753. /**
  104754. * Sets the scale applied to the radius (1 by default)
  104755. */
  104756. set: function (radius) {
  104757. this._radiusScale = radius;
  104758. },
  104759. enumerable: true,
  104760. configurable: true
  104761. });
  104762. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  104763. /**
  104764. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  104765. */
  104766. get: function () {
  104767. return this._positionScale;
  104768. },
  104769. /**
  104770. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  104771. */
  104772. set: function (scale) {
  104773. this._positionScale = scale;
  104774. },
  104775. enumerable: true,
  104776. configurable: true
  104777. });
  104778. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  104779. /**
  104780. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  104781. * behaviour is triggered, in radians.
  104782. */
  104783. get: function () {
  104784. return this._defaultElevation;
  104785. },
  104786. /**
  104787. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  104788. * behaviour is triggered, in radians.
  104789. */
  104790. set: function (elevation) {
  104791. this._defaultElevation = elevation;
  104792. },
  104793. enumerable: true,
  104794. configurable: true
  104795. });
  104796. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  104797. /**
  104798. * Gets the time (in milliseconds) taken to return to the default beta position.
  104799. * Negative value indicates camera should not return to default.
  104800. */
  104801. get: function () {
  104802. return this._elevationReturnTime;
  104803. },
  104804. /**
  104805. * Sets the time (in milliseconds) taken to return to the default beta position.
  104806. * Negative value indicates camera should not return to default.
  104807. */
  104808. set: function (speed) {
  104809. this._elevationReturnTime = speed;
  104810. },
  104811. enumerable: true,
  104812. configurable: true
  104813. });
  104814. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  104815. /**
  104816. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  104817. */
  104818. get: function () {
  104819. return this._elevationReturnWaitTime;
  104820. },
  104821. /**
  104822. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  104823. */
  104824. set: function (time) {
  104825. this._elevationReturnWaitTime = time;
  104826. },
  104827. enumerable: true,
  104828. configurable: true
  104829. });
  104830. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  104831. /**
  104832. * Gets the flag that indicates if user zooming should stop animation.
  104833. */
  104834. get: function () {
  104835. return this._zoomStopsAnimation;
  104836. },
  104837. /**
  104838. * Sets the flag that indicates if user zooming should stop animation.
  104839. */
  104840. set: function (flag) {
  104841. this._zoomStopsAnimation = flag;
  104842. },
  104843. enumerable: true,
  104844. configurable: true
  104845. });
  104846. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  104847. /**
  104848. * Gets the transition time when framing the mesh, in milliseconds
  104849. */
  104850. get: function () {
  104851. return this._framingTime;
  104852. },
  104853. /**
  104854. * Sets the transition time when framing the mesh, in milliseconds
  104855. */
  104856. set: function (time) {
  104857. this._framingTime = time;
  104858. },
  104859. enumerable: true,
  104860. configurable: true
  104861. });
  104862. FramingBehavior.prototype.init = function () {
  104863. // Do notihng
  104864. };
  104865. FramingBehavior.prototype.attach = function (camera) {
  104866. var _this = this;
  104867. this._attachedCamera = camera;
  104868. var scene = this._attachedCamera.getScene();
  104869. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  104870. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  104871. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  104872. _this._isPointerDown = true;
  104873. return;
  104874. }
  104875. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  104876. _this._isPointerDown = false;
  104877. }
  104878. });
  104879. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  104880. if (mesh) {
  104881. _this.zoomOnMesh(mesh);
  104882. }
  104883. });
  104884. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  104885. // Stop the animation if there is user interaction and the animation should stop for this interaction
  104886. _this._applyUserInteraction();
  104887. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  104888. // back to the default position after a given timeout
  104889. _this._maintainCameraAboveGround();
  104890. });
  104891. };
  104892. FramingBehavior.prototype.detach = function () {
  104893. if (!this._attachedCamera) {
  104894. return;
  104895. }
  104896. var scene = this._attachedCamera.getScene();
  104897. if (this._onPrePointerObservableObserver) {
  104898. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  104899. }
  104900. if (this._onAfterCheckInputsObserver) {
  104901. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  104902. }
  104903. if (this._onMeshTargetChangedObserver) {
  104904. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  104905. }
  104906. this._attachedCamera = null;
  104907. };
  104908. /**
  104909. * Targets the given mesh and updates zoom level accordingly.
  104910. * @param mesh The mesh to target.
  104911. * @param radius Optional. If a cached radius position already exists, overrides default.
  104912. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104913. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104914. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104915. */
  104916. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  104917. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104918. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104919. mesh.computeWorldMatrix(true);
  104920. var boundingBox = mesh.getBoundingInfo().boundingBox;
  104921. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  104922. };
  104923. /**
  104924. * Targets the given mesh with its children and updates zoom level accordingly.
  104925. * @param mesh The mesh to target.
  104926. * @param radius Optional. If a cached radius position already exists, overrides default.
  104927. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104928. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104929. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104930. */
  104931. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  104932. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104933. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104934. mesh.computeWorldMatrix(true);
  104935. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  104936. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  104937. };
  104938. /**
  104939. * Targets the given meshes with their children and updates zoom level accordingly.
  104940. * @param meshes The mesh to target.
  104941. * @param radius Optional. If a cached radius position already exists, overrides default.
  104942. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104943. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104944. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104945. */
  104946. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  104947. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104948. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104949. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  104950. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  104951. for (var i = 0; i < meshes.length; i++) {
  104952. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  104953. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  104954. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  104955. }
  104956. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  104957. };
  104958. /**
  104959. * Targets the given mesh and updates zoom level accordingly.
  104960. * @param mesh The mesh to target.
  104961. * @param radius Optional. If a cached radius position already exists, overrides default.
  104962. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104963. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104964. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104965. */
  104966. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  104967. var _this = this;
  104968. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104969. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104970. var zoomTarget;
  104971. if (!this._attachedCamera) {
  104972. return;
  104973. }
  104974. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  104975. var bottom = minimumWorld.y;
  104976. var top = maximumWorld.y;
  104977. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  104978. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  104979. if (focusOnOriginXZ) {
  104980. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  104981. }
  104982. else {
  104983. var centerWorld = minimumWorld.add(radiusWorld);
  104984. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  104985. }
  104986. if (!this._vectorTransition) {
  104987. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  104988. }
  104989. this._betaIsAnimating = true;
  104990. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  104991. if (animatable) {
  104992. this._animatables.push(animatable);
  104993. }
  104994. // sets the radius and lower radius bounds
  104995. // Small delta ensures camera is not always at lower zoom limit.
  104996. var radius = 0;
  104997. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  104998. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  104999. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  105000. radius = position;
  105001. }
  105002. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  105003. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  105004. if (this._attachedCamera.lowerRadiusLimit === null) {
  105005. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  105006. }
  105007. }
  105008. // Set sensibilities
  105009. var extend = maximumWorld.subtract(minimumWorld).length();
  105010. this._attachedCamera.panningSensibility = 5000 / extend;
  105011. this._attachedCamera.wheelPrecision = 100 / radius;
  105012. // transition to new radius
  105013. if (!this._radiusTransition) {
  105014. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  105015. }
  105016. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  105017. _this.stopAllAnimations();
  105018. if (onAnimationEnd) {
  105019. onAnimationEnd();
  105020. }
  105021. if (_this._attachedCamera) {
  105022. _this._attachedCamera.storeState();
  105023. }
  105024. });
  105025. if (animatable) {
  105026. this._animatables.push(animatable);
  105027. }
  105028. };
  105029. /**
  105030. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  105031. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  105032. * frustum width.
  105033. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  105034. * to fully enclose the mesh in the viewing frustum.
  105035. */
  105036. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  105037. var size = maximumWorld.subtract(minimumWorld);
  105038. var boxVectorGlobalDiagonal = size.length();
  105039. var frustumSlope = this._getFrustumSlope();
  105040. // Formula for setting distance
  105041. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  105042. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  105043. // Horizon distance
  105044. var radius = radiusWithoutFraming * this._radiusScale;
  105045. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  105046. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  105047. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  105048. var camera = this._attachedCamera;
  105049. if (!camera) {
  105050. return 0;
  105051. }
  105052. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  105053. // Don't exceed the requested limit
  105054. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  105055. }
  105056. // Don't exceed the upper radius limit
  105057. if (camera.upperRadiusLimit) {
  105058. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  105059. }
  105060. return distance;
  105061. };
  105062. /**
  105063. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  105064. * is automatically returned to its default position (expected to be above ground plane).
  105065. */
  105066. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  105067. var _this = this;
  105068. if (this._elevationReturnTime < 0) {
  105069. return;
  105070. }
  105071. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  105072. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  105073. var limitBeta = Math.PI * 0.5;
  105074. // Bring the camera back up if below the ground plane
  105075. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  105076. this._betaIsAnimating = true;
  105077. //Transition to new position
  105078. this.stopAllAnimations();
  105079. if (!this._betaTransition) {
  105080. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  105081. }
  105082. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  105083. _this._clearAnimationLocks();
  105084. _this.stopAllAnimations();
  105085. });
  105086. if (animatabe) {
  105087. this._animatables.push(animatabe);
  105088. }
  105089. }
  105090. };
  105091. /**
  105092. * Returns the frustum slope based on the canvas ratio and camera FOV
  105093. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  105094. */
  105095. FramingBehavior.prototype._getFrustumSlope = function () {
  105096. // Calculate the viewport ratio
  105097. // Aspect Ratio is Height/Width.
  105098. var camera = this._attachedCamera;
  105099. if (!camera) {
  105100. return BABYLON.Vector2.Zero();
  105101. }
  105102. var engine = camera.getScene().getEngine();
  105103. var aspectRatio = engine.getAspectRatio(camera);
  105104. // Camera FOV is the vertical field of view (top-bottom) in radians.
  105105. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  105106. var frustumSlopeY = Math.tan(camera.fov / 2);
  105107. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  105108. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  105109. // along the forward vector.
  105110. var frustumSlopeX = frustumSlopeY * aspectRatio;
  105111. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  105112. };
  105113. /**
  105114. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  105115. */
  105116. FramingBehavior.prototype._clearAnimationLocks = function () {
  105117. this._betaIsAnimating = false;
  105118. };
  105119. /**
  105120. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  105121. */
  105122. FramingBehavior.prototype._applyUserInteraction = function () {
  105123. if (this.isUserIsMoving) {
  105124. this._lastInteractionTime = BABYLON.Tools.Now;
  105125. this.stopAllAnimations();
  105126. this._clearAnimationLocks();
  105127. }
  105128. };
  105129. /**
  105130. * Stops and removes all animations that have been applied to the camera
  105131. */
  105132. FramingBehavior.prototype.stopAllAnimations = function () {
  105133. if (this._attachedCamera) {
  105134. this._attachedCamera.animations = [];
  105135. }
  105136. while (this._animatables.length) {
  105137. if (this._animatables[0]) {
  105138. this._animatables[0].onAnimationEnd = null;
  105139. this._animatables[0].stop();
  105140. }
  105141. this._animatables.shift();
  105142. }
  105143. };
  105144. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  105145. /**
  105146. * Gets a value indicating if the user is moving the camera
  105147. */
  105148. get: function () {
  105149. if (!this._attachedCamera) {
  105150. return false;
  105151. }
  105152. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  105153. this._attachedCamera.inertialBetaOffset !== 0 ||
  105154. this._attachedCamera.inertialRadiusOffset !== 0 ||
  105155. this._attachedCamera.inertialPanningX !== 0 ||
  105156. this._attachedCamera.inertialPanningY !== 0 ||
  105157. this._isPointerDown;
  105158. },
  105159. enumerable: true,
  105160. configurable: true
  105161. });
  105162. /**
  105163. * The easing function used by animations
  105164. */
  105165. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  105166. /**
  105167. * The easing mode used by animations
  105168. */
  105169. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  105170. // Statics
  105171. /**
  105172. * The camera can move all the way towards the mesh.
  105173. */
  105174. FramingBehavior.IgnoreBoundsSizeMode = 0;
  105175. /**
  105176. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  105177. */
  105178. FramingBehavior.FitFrustumSidesMode = 1;
  105179. return FramingBehavior;
  105180. }());
  105181. BABYLON.FramingBehavior = FramingBehavior;
  105182. })(BABYLON || (BABYLON = {}));
  105183. //# sourceMappingURL=babylon.framingBehavior.js.map
  105184. var BABYLON;
  105185. (function (BABYLON) {
  105186. /**
  105187. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  105188. */
  105189. var BouncingBehavior = /** @class */ (function () {
  105190. function BouncingBehavior() {
  105191. /**
  105192. * The duration of the animation, in milliseconds
  105193. */
  105194. this.transitionDuration = 450;
  105195. /**
  105196. * Length of the distance animated by the transition when lower radius is reached
  105197. */
  105198. this.lowerRadiusTransitionRange = 2;
  105199. /**
  105200. * Length of the distance animated by the transition when upper radius is reached
  105201. */
  105202. this.upperRadiusTransitionRange = -2;
  105203. this._autoTransitionRange = false;
  105204. // Animations
  105205. this._radiusIsAnimating = false;
  105206. this._radiusBounceTransition = null;
  105207. this._animatables = new Array();
  105208. }
  105209. Object.defineProperty(BouncingBehavior.prototype, "name", {
  105210. get: function () {
  105211. return "Bouncing";
  105212. },
  105213. enumerable: true,
  105214. configurable: true
  105215. });
  105216. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  105217. /**
  105218. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  105219. */
  105220. get: function () {
  105221. return this._autoTransitionRange;
  105222. },
  105223. /**
  105224. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  105225. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  105226. */
  105227. set: function (value) {
  105228. var _this = this;
  105229. if (this._autoTransitionRange === value) {
  105230. return;
  105231. }
  105232. this._autoTransitionRange = value;
  105233. var camera = this._attachedCamera;
  105234. if (!camera) {
  105235. return;
  105236. }
  105237. if (value) {
  105238. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  105239. if (!mesh) {
  105240. return;
  105241. }
  105242. mesh.computeWorldMatrix(true);
  105243. var diagonal = mesh.getBoundingInfo().diagonalLength;
  105244. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  105245. _this.upperRadiusTransitionRange = diagonal * 0.05;
  105246. });
  105247. }
  105248. else if (this._onMeshTargetChangedObserver) {
  105249. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105250. }
  105251. },
  105252. enumerable: true,
  105253. configurable: true
  105254. });
  105255. BouncingBehavior.prototype.init = function () {
  105256. // Do notihng
  105257. };
  105258. BouncingBehavior.prototype.attach = function (camera) {
  105259. var _this = this;
  105260. this._attachedCamera = camera;
  105261. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105262. if (!_this._attachedCamera) {
  105263. return;
  105264. }
  105265. // Add the bounce animation to the lower radius limit
  105266. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  105267. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  105268. }
  105269. // Add the bounce animation to the upper radius limit
  105270. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  105271. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  105272. }
  105273. });
  105274. };
  105275. BouncingBehavior.prototype.detach = function () {
  105276. if (!this._attachedCamera) {
  105277. return;
  105278. }
  105279. if (this._onAfterCheckInputsObserver) {
  105280. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  105281. }
  105282. if (this._onMeshTargetChangedObserver) {
  105283. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105284. }
  105285. this._attachedCamera = null;
  105286. };
  105287. /**
  105288. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  105289. * @param radiusLimit The limit to check against.
  105290. * @return Bool to indicate if at limit.
  105291. */
  105292. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  105293. if (!this._attachedCamera) {
  105294. return false;
  105295. }
  105296. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  105297. return true;
  105298. }
  105299. return false;
  105300. };
  105301. /**
  105302. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  105303. * @param radiusDelta The delta by which to animate to. Can be negative.
  105304. */
  105305. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  105306. var _this = this;
  105307. if (!this._attachedCamera) {
  105308. return;
  105309. }
  105310. if (!this._radiusBounceTransition) {
  105311. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  105312. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  105313. }
  105314. // Prevent zoom until bounce has completed
  105315. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  105316. this._attachedCamera.wheelPrecision = Infinity;
  105317. this._attachedCamera.inertialRadiusOffset = 0;
  105318. // Animate to the radius limit
  105319. this.stopAllAnimations();
  105320. this._radiusIsAnimating = true;
  105321. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  105322. if (animatable) {
  105323. this._animatables.push(animatable);
  105324. }
  105325. };
  105326. /**
  105327. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  105328. */
  105329. BouncingBehavior.prototype._clearAnimationLocks = function () {
  105330. this._radiusIsAnimating = false;
  105331. if (this._attachedCamera) {
  105332. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  105333. }
  105334. };
  105335. /**
  105336. * Stops and removes all animations that have been applied to the camera
  105337. */
  105338. BouncingBehavior.prototype.stopAllAnimations = function () {
  105339. if (this._attachedCamera) {
  105340. this._attachedCamera.animations = [];
  105341. }
  105342. while (this._animatables.length) {
  105343. this._animatables[0].onAnimationEnd = null;
  105344. this._animatables[0].stop();
  105345. this._animatables.shift();
  105346. }
  105347. };
  105348. /**
  105349. * The easing function used by animations
  105350. */
  105351. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  105352. /**
  105353. * The easing mode used by animations
  105354. */
  105355. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  105356. return BouncingBehavior;
  105357. }());
  105358. BABYLON.BouncingBehavior = BouncingBehavior;
  105359. })(BABYLON || (BABYLON = {}));
  105360. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  105361. var BABYLON;
  105362. (function (BABYLON) {
  105363. var AutoRotationBehavior = /** @class */ (function () {
  105364. function AutoRotationBehavior() {
  105365. this._zoomStopsAnimation = false;
  105366. this._idleRotationSpeed = 0.05;
  105367. this._idleRotationWaitTime = 2000;
  105368. this._idleRotationSpinupTime = 2000;
  105369. this._isPointerDown = false;
  105370. this._lastFrameTime = null;
  105371. this._lastInteractionTime = -Infinity;
  105372. this._cameraRotationSpeed = 0;
  105373. this._lastFrameRadius = 0;
  105374. }
  105375. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  105376. get: function () {
  105377. return "AutoRotation";
  105378. },
  105379. enumerable: true,
  105380. configurable: true
  105381. });
  105382. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  105383. /**
  105384. * Gets the flag that indicates if user zooming should stop animation.
  105385. */
  105386. get: function () {
  105387. return this._zoomStopsAnimation;
  105388. },
  105389. /**
  105390. * Sets the flag that indicates if user zooming should stop animation.
  105391. */
  105392. set: function (flag) {
  105393. this._zoomStopsAnimation = flag;
  105394. },
  105395. enumerable: true,
  105396. configurable: true
  105397. });
  105398. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  105399. /**
  105400. * Gets the default speed at which the camera rotates around the model.
  105401. */
  105402. get: function () {
  105403. return this._idleRotationSpeed;
  105404. },
  105405. /**
  105406. * Sets the default speed at which the camera rotates around the model.
  105407. */
  105408. set: function (speed) {
  105409. this._idleRotationSpeed = speed;
  105410. },
  105411. enumerable: true,
  105412. configurable: true
  105413. });
  105414. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  105415. /**
  105416. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  105417. */
  105418. get: function () {
  105419. return this._idleRotationWaitTime;
  105420. },
  105421. /**
  105422. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  105423. */
  105424. set: function (time) {
  105425. this._idleRotationWaitTime = time;
  105426. },
  105427. enumerable: true,
  105428. configurable: true
  105429. });
  105430. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  105431. /**
  105432. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  105433. */
  105434. get: function () {
  105435. return this._idleRotationSpinupTime;
  105436. },
  105437. /**
  105438. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  105439. */
  105440. set: function (time) {
  105441. this._idleRotationSpinupTime = time;
  105442. },
  105443. enumerable: true,
  105444. configurable: true
  105445. });
  105446. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  105447. /**
  105448. * Gets a value indicating if the camera is currently rotating because of this behavior
  105449. */
  105450. get: function () {
  105451. return Math.abs(this._cameraRotationSpeed) > 0;
  105452. },
  105453. enumerable: true,
  105454. configurable: true
  105455. });
  105456. AutoRotationBehavior.prototype.init = function () {
  105457. // Do notihng
  105458. };
  105459. AutoRotationBehavior.prototype.attach = function (camera) {
  105460. var _this = this;
  105461. this._attachedCamera = camera;
  105462. var scene = this._attachedCamera.getScene();
  105463. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  105464. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  105465. _this._isPointerDown = true;
  105466. return;
  105467. }
  105468. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  105469. _this._isPointerDown = false;
  105470. }
  105471. });
  105472. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105473. var now = BABYLON.Tools.Now;
  105474. var dt = 0;
  105475. if (_this._lastFrameTime != null) {
  105476. dt = now - _this._lastFrameTime;
  105477. }
  105478. _this._lastFrameTime = now;
  105479. // Stop the animation if there is user interaction and the animation should stop for this interaction
  105480. _this._applyUserInteraction();
  105481. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  105482. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  105483. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  105484. // Step camera rotation by rotation speed
  105485. if (_this._attachedCamera) {
  105486. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  105487. }
  105488. });
  105489. };
  105490. AutoRotationBehavior.prototype.detach = function () {
  105491. if (!this._attachedCamera) {
  105492. return;
  105493. }
  105494. var scene = this._attachedCamera.getScene();
  105495. if (this._onPrePointerObservableObserver) {
  105496. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  105497. }
  105498. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  105499. this._attachedCamera = null;
  105500. };
  105501. /**
  105502. * Returns true if user is scrolling.
  105503. * @return true if user is scrolling.
  105504. */
  105505. AutoRotationBehavior.prototype._userIsZooming = function () {
  105506. if (!this._attachedCamera) {
  105507. return false;
  105508. }
  105509. return this._attachedCamera.inertialRadiusOffset !== 0;
  105510. };
  105511. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  105512. if (!this._attachedCamera) {
  105513. return false;
  105514. }
  105515. var zoomHasHitLimit = false;
  105516. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  105517. zoomHasHitLimit = true;
  105518. }
  105519. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  105520. this._lastFrameRadius = this._attachedCamera.radius;
  105521. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  105522. };
  105523. /**
  105524. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  105525. */
  105526. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  105527. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  105528. this._lastInteractionTime = BABYLON.Tools.Now;
  105529. }
  105530. };
  105531. // Tools
  105532. AutoRotationBehavior.prototype._userIsMoving = function () {
  105533. if (!this._attachedCamera) {
  105534. return false;
  105535. }
  105536. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  105537. this._attachedCamera.inertialBetaOffset !== 0 ||
  105538. this._attachedCamera.inertialRadiusOffset !== 0 ||
  105539. this._attachedCamera.inertialPanningX !== 0 ||
  105540. this._attachedCamera.inertialPanningY !== 0 ||
  105541. this._isPointerDown;
  105542. };
  105543. return AutoRotationBehavior;
  105544. }());
  105545. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  105546. })(BABYLON || (BABYLON = {}));
  105547. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  105548. var BABYLON;
  105549. (function (BABYLON) {
  105550. var NullEngineOptions = /** @class */ (function () {
  105551. function NullEngineOptions() {
  105552. this.renderWidth = 512;
  105553. this.renderHeight = 256;
  105554. this.textureSize = 512;
  105555. this.deterministicLockstep = false;
  105556. this.lockstepMaxSteps = 4;
  105557. }
  105558. return NullEngineOptions;
  105559. }());
  105560. BABYLON.NullEngineOptions = NullEngineOptions;
  105561. /**
  105562. * The null engine class provides support for headless version of babylon.js.
  105563. * This can be used in server side scenario or for testing purposes
  105564. */
  105565. var NullEngine = /** @class */ (function (_super) {
  105566. __extends(NullEngine, _super);
  105567. function NullEngine(options) {
  105568. if (options === void 0) { options = new NullEngineOptions(); }
  105569. var _this = _super.call(this, null) || this;
  105570. if (options.deterministicLockstep === undefined) {
  105571. options.deterministicLockstep = false;
  105572. }
  105573. if (options.lockstepMaxSteps === undefined) {
  105574. options.lockstepMaxSteps = 4;
  105575. }
  105576. _this._options = options;
  105577. // Init caps
  105578. // We consider we are on a webgl1 capable device
  105579. _this._caps = new BABYLON.EngineCapabilities();
  105580. _this._caps.maxTexturesImageUnits = 16;
  105581. _this._caps.maxVertexTextureImageUnits = 16;
  105582. _this._caps.maxTextureSize = 512;
  105583. _this._caps.maxCubemapTextureSize = 512;
  105584. _this._caps.maxRenderTextureSize = 512;
  105585. _this._caps.maxVertexAttribs = 16;
  105586. _this._caps.maxVaryingVectors = 16;
  105587. _this._caps.maxFragmentUniformVectors = 16;
  105588. _this._caps.maxVertexUniformVectors = 16;
  105589. // Extensions
  105590. _this._caps.standardDerivatives = false;
  105591. _this._caps.astc = null;
  105592. _this._caps.s3tc = null;
  105593. _this._caps.pvrtc = null;
  105594. _this._caps.etc1 = null;
  105595. _this._caps.etc2 = null;
  105596. _this._caps.textureAnisotropicFilterExtension = null;
  105597. _this._caps.maxAnisotropy = 0;
  105598. _this._caps.uintIndices = false;
  105599. _this._caps.fragmentDepthSupported = false;
  105600. _this._caps.highPrecisionShaderSupported = true;
  105601. _this._caps.colorBufferFloat = false;
  105602. _this._caps.textureFloat = false;
  105603. _this._caps.textureFloatLinearFiltering = false;
  105604. _this._caps.textureFloatRender = false;
  105605. _this._caps.textureHalfFloat = false;
  105606. _this._caps.textureHalfFloatLinearFiltering = false;
  105607. _this._caps.textureHalfFloatRender = false;
  105608. _this._caps.textureLOD = false;
  105609. _this._caps.drawBuffersExtension = false;
  105610. _this._caps.depthTextureExtension = false;
  105611. _this._caps.vertexArrayObject = false;
  105612. _this._caps.instancedArrays = false;
  105613. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  105614. // Wrappers
  105615. if (typeof URL === "undefined") {
  105616. URL = {
  105617. createObjectURL: function () { },
  105618. revokeObjectURL: function () { }
  105619. };
  105620. }
  105621. if (typeof Blob === "undefined") {
  105622. Blob = function () { };
  105623. }
  105624. return _this;
  105625. }
  105626. NullEngine.prototype.isDeterministicLockStep = function () {
  105627. return this._options.deterministicLockstep;
  105628. };
  105629. NullEngine.prototype.getLockstepMaxSteps = function () {
  105630. return this._options.lockstepMaxSteps;
  105631. };
  105632. NullEngine.prototype.getHardwareScalingLevel = function () {
  105633. return 1.0;
  105634. };
  105635. NullEngine.prototype.createVertexBuffer = function (vertices) {
  105636. return {
  105637. capacity: 0,
  105638. references: 1,
  105639. is32Bits: false
  105640. };
  105641. };
  105642. NullEngine.prototype.createIndexBuffer = function (indices) {
  105643. return {
  105644. capacity: 0,
  105645. references: 1,
  105646. is32Bits: false
  105647. };
  105648. };
  105649. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  105650. if (stencil === void 0) { stencil = false; }
  105651. };
  105652. NullEngine.prototype.getRenderWidth = function (useScreen) {
  105653. if (useScreen === void 0) { useScreen = false; }
  105654. if (!useScreen && this._currentRenderTarget) {
  105655. return this._currentRenderTarget.width;
  105656. }
  105657. return this._options.renderWidth;
  105658. };
  105659. NullEngine.prototype.getRenderHeight = function (useScreen) {
  105660. if (useScreen === void 0) { useScreen = false; }
  105661. if (!useScreen && this._currentRenderTarget) {
  105662. return this._currentRenderTarget.height;
  105663. }
  105664. return this._options.renderHeight;
  105665. };
  105666. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  105667. this._cachedViewport = viewport;
  105668. };
  105669. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  105670. return {
  105671. transformFeedback: null,
  105672. __SPECTOR_rebuildProgram: null
  105673. };
  105674. };
  105675. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  105676. return [];
  105677. };
  105678. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  105679. return [];
  105680. };
  105681. NullEngine.prototype.bindSamplers = function (effect) {
  105682. this._currentEffect = null;
  105683. };
  105684. NullEngine.prototype.enableEffect = function (effect) {
  105685. this._currentEffect = effect;
  105686. if (effect.onBind) {
  105687. effect.onBind(effect);
  105688. }
  105689. if (effect._onBindObservable) {
  105690. effect._onBindObservable.notifyObservers(effect);
  105691. }
  105692. };
  105693. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  105694. if (zOffset === void 0) { zOffset = 0; }
  105695. if (reverseSide === void 0) { reverseSide = false; }
  105696. };
  105697. NullEngine.prototype.setIntArray = function (uniform, array) {
  105698. };
  105699. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  105700. };
  105701. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  105702. };
  105703. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  105704. };
  105705. NullEngine.prototype.setFloatArray = function (uniform, array) {
  105706. };
  105707. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  105708. };
  105709. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  105710. };
  105711. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  105712. };
  105713. NullEngine.prototype.setArray = function (uniform, array) {
  105714. };
  105715. NullEngine.prototype.setArray2 = function (uniform, array) {
  105716. };
  105717. NullEngine.prototype.setArray3 = function (uniform, array) {
  105718. };
  105719. NullEngine.prototype.setArray4 = function (uniform, array) {
  105720. };
  105721. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  105722. };
  105723. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  105724. };
  105725. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  105726. };
  105727. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  105728. };
  105729. NullEngine.prototype.setFloat = function (uniform, value) {
  105730. };
  105731. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  105732. };
  105733. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  105734. };
  105735. NullEngine.prototype.setBool = function (uniform, bool) {
  105736. };
  105737. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  105738. };
  105739. NullEngine.prototype.setColor3 = function (uniform, color3) {
  105740. };
  105741. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  105742. };
  105743. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  105744. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  105745. if (this._alphaMode === mode) {
  105746. return;
  105747. }
  105748. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  105749. if (!noDepthWriteChange) {
  105750. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  105751. }
  105752. this._alphaMode = mode;
  105753. };
  105754. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  105755. };
  105756. NullEngine.prototype.wipeCaches = function (bruteForce) {
  105757. if (this.preventCacheWipeBetweenFrames) {
  105758. return;
  105759. }
  105760. this.resetTextureCache();
  105761. this._currentEffect = null;
  105762. if (bruteForce) {
  105763. this._currentProgram = null;
  105764. this._stencilState.reset();
  105765. this._depthCullingState.reset();
  105766. this._alphaState.reset();
  105767. }
  105768. this._cachedVertexBuffers = null;
  105769. this._cachedIndexBuffer = null;
  105770. this._cachedEffectForVertexBuffers = null;
  105771. };
  105772. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  105773. };
  105774. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  105775. };
  105776. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  105777. };
  105778. /** @hidden */
  105779. NullEngine.prototype._createTexture = function () {
  105780. return {};
  105781. };
  105782. /** @hidden */
  105783. NullEngine.prototype._releaseTexture = function (texture) {
  105784. };
  105785. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  105786. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  105787. if (onLoad === void 0) { onLoad = null; }
  105788. if (onError === void 0) { onError = null; }
  105789. if (buffer === void 0) { buffer = null; }
  105790. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  105791. var url = String(urlArg);
  105792. texture.url = url;
  105793. texture.generateMipMaps = !noMipmap;
  105794. texture.samplingMode = samplingMode;
  105795. texture.invertY = invertY;
  105796. texture.baseWidth = this._options.textureSize;
  105797. texture.baseHeight = this._options.textureSize;
  105798. texture.width = this._options.textureSize;
  105799. texture.height = this._options.textureSize;
  105800. if (format) {
  105801. texture.format = format;
  105802. }
  105803. texture.isReady = true;
  105804. if (onLoad) {
  105805. onLoad();
  105806. }
  105807. this._internalTexturesCache.push(texture);
  105808. return texture;
  105809. };
  105810. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  105811. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  105812. if (options !== undefined && typeof options === "object") {
  105813. fullOptions.generateMipMaps = options.generateMipMaps;
  105814. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  105815. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  105816. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  105817. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  105818. }
  105819. else {
  105820. fullOptions.generateMipMaps = options;
  105821. fullOptions.generateDepthBuffer = true;
  105822. fullOptions.generateStencilBuffer = false;
  105823. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  105824. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  105825. }
  105826. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  105827. var width = size.width || size;
  105828. var height = size.height || size;
  105829. texture._depthStencilBuffer = {};
  105830. texture._framebuffer = {};
  105831. texture.baseWidth = width;
  105832. texture.baseHeight = height;
  105833. texture.width = width;
  105834. texture.height = height;
  105835. texture.isReady = true;
  105836. texture.samples = 1;
  105837. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  105838. texture.samplingMode = fullOptions.samplingMode;
  105839. texture.type = fullOptions.type;
  105840. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  105841. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  105842. this._internalTexturesCache.push(texture);
  105843. return texture;
  105844. };
  105845. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  105846. texture.samplingMode = samplingMode;
  105847. };
  105848. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  105849. if (this._currentRenderTarget) {
  105850. this.unBindFramebuffer(this._currentRenderTarget);
  105851. }
  105852. this._currentRenderTarget = texture;
  105853. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  105854. if (this._cachedViewport && !forceFullscreenViewport) {
  105855. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  105856. }
  105857. };
  105858. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  105859. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  105860. this._currentRenderTarget = null;
  105861. if (onBeforeUnbind) {
  105862. if (texture._MSAAFramebuffer) {
  105863. this._currentFramebuffer = texture._framebuffer;
  105864. }
  105865. onBeforeUnbind();
  105866. }
  105867. this._currentFramebuffer = null;
  105868. };
  105869. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  105870. var vbo = {
  105871. capacity: 1,
  105872. references: 1,
  105873. is32Bits: false
  105874. };
  105875. return vbo;
  105876. };
  105877. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  105878. if (premulAlpha === void 0) { premulAlpha = false; }
  105879. };
  105880. /**
  105881. * @hidden
  105882. * Get the current error code of the webGL context
  105883. * @returns the error code
  105884. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  105885. */
  105886. NullEngine.prototype.getError = function () {
  105887. return 0;
  105888. };
  105889. /** @hidden */
  105890. NullEngine.prototype._getUnpackAlignement = function () {
  105891. return 1;
  105892. };
  105893. /** @hidden */
  105894. NullEngine.prototype._unpackFlipY = function (value) {
  105895. };
  105896. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  105897. if (offset === void 0) { offset = 0; }
  105898. };
  105899. /**
  105900. * Updates a dynamic vertex buffer.
  105901. * @param vertexBuffer the vertex buffer to update
  105902. * @param data the data used to update the vertex buffer
  105903. * @param byteOffset the byte offset of the data (optional)
  105904. * @param byteLength the byte length of the data (optional)
  105905. */
  105906. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  105907. };
  105908. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  105909. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  105910. this._boundTexturesCache[this._activeChannel] = texture;
  105911. return true;
  105912. }
  105913. return false;
  105914. };
  105915. /** @hidden */
  105916. NullEngine.prototype._bindTexture = function (channel, texture) {
  105917. if (channel < 0) {
  105918. return;
  105919. }
  105920. this._bindTextureDirectly(0, texture);
  105921. };
  105922. /** @hidden */
  105923. NullEngine.prototype._releaseBuffer = function (buffer) {
  105924. buffer.references--;
  105925. if (buffer.references === 0) {
  105926. return true;
  105927. }
  105928. return false;
  105929. };
  105930. NullEngine.prototype.releaseEffects = function () {
  105931. };
  105932. NullEngine.prototype.displayLoadingUI = function () {
  105933. };
  105934. NullEngine.prototype.hideLoadingUI = function () {
  105935. };
  105936. /** @hidden */
  105937. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  105938. if (faceIndex === void 0) { faceIndex = 0; }
  105939. if (lod === void 0) { lod = 0; }
  105940. };
  105941. /** @hidden */
  105942. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  105943. if (faceIndex === void 0) { faceIndex = 0; }
  105944. if (lod === void 0) { lod = 0; }
  105945. };
  105946. /** @hidden */
  105947. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  105948. if (faceIndex === void 0) { faceIndex = 0; }
  105949. if (lod === void 0) { lod = 0; }
  105950. };
  105951. /** @hidden */
  105952. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  105953. if (faceIndex === void 0) { faceIndex = 0; }
  105954. if (lod === void 0) { lod = 0; }
  105955. };
  105956. return NullEngine;
  105957. }(BABYLON.Engine));
  105958. BABYLON.NullEngine = NullEngine;
  105959. })(BABYLON || (BABYLON = {}));
  105960. //# sourceMappingURL=babylon.nullEngine.js.map
  105961. var BABYLON;
  105962. (function (BABYLON) {
  105963. /**
  105964. * This class can be used to get instrumentation data from a Babylon engine
  105965. */
  105966. var EngineInstrumentation = /** @class */ (function () {
  105967. function EngineInstrumentation(engine) {
  105968. this.engine = engine;
  105969. this._captureGPUFrameTime = false;
  105970. this._gpuFrameTime = new BABYLON.PerfCounter();
  105971. this._captureShaderCompilationTime = false;
  105972. this._shaderCompilationTime = new BABYLON.PerfCounter();
  105973. // Observers
  105974. this._onBeginFrameObserver = null;
  105975. this._onEndFrameObserver = null;
  105976. this._onBeforeShaderCompilationObserver = null;
  105977. this._onAfterShaderCompilationObserver = null;
  105978. }
  105979. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  105980. // Properties
  105981. /**
  105982. * Gets the perf counter used for GPU frame time
  105983. */
  105984. get: function () {
  105985. return this._gpuFrameTime;
  105986. },
  105987. enumerable: true,
  105988. configurable: true
  105989. });
  105990. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  105991. /**
  105992. * Gets the GPU frame time capture status
  105993. */
  105994. get: function () {
  105995. return this._captureGPUFrameTime;
  105996. },
  105997. /**
  105998. * Enable or disable the GPU frame time capture
  105999. */
  106000. set: function (value) {
  106001. var _this = this;
  106002. if (value === this._captureGPUFrameTime) {
  106003. return;
  106004. }
  106005. this._captureGPUFrameTime = value;
  106006. if (value) {
  106007. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  106008. if (!_this._gpuFrameTimeToken) {
  106009. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  106010. }
  106011. });
  106012. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  106013. if (!_this._gpuFrameTimeToken) {
  106014. return;
  106015. }
  106016. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  106017. if (time > -1) {
  106018. _this._gpuFrameTimeToken = null;
  106019. _this._gpuFrameTime.fetchNewFrame();
  106020. _this._gpuFrameTime.addCount(time, true);
  106021. }
  106022. });
  106023. }
  106024. else {
  106025. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  106026. this._onBeginFrameObserver = null;
  106027. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  106028. this._onEndFrameObserver = null;
  106029. }
  106030. },
  106031. enumerable: true,
  106032. configurable: true
  106033. });
  106034. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  106035. /**
  106036. * Gets the perf counter used for shader compilation time
  106037. */
  106038. get: function () {
  106039. return this._shaderCompilationTime;
  106040. },
  106041. enumerable: true,
  106042. configurable: true
  106043. });
  106044. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  106045. /**
  106046. * Gets the shader compilation time capture status
  106047. */
  106048. get: function () {
  106049. return this._captureShaderCompilationTime;
  106050. },
  106051. /**
  106052. * Enable or disable the shader compilation time capture
  106053. */
  106054. set: function (value) {
  106055. var _this = this;
  106056. if (value === this._captureShaderCompilationTime) {
  106057. return;
  106058. }
  106059. this._captureShaderCompilationTime = value;
  106060. if (value) {
  106061. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  106062. _this._shaderCompilationTime.fetchNewFrame();
  106063. _this._shaderCompilationTime.beginMonitoring();
  106064. });
  106065. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  106066. _this._shaderCompilationTime.endMonitoring();
  106067. });
  106068. }
  106069. else {
  106070. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106071. this._onBeforeShaderCompilationObserver = null;
  106072. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106073. this._onAfterShaderCompilationObserver = null;
  106074. }
  106075. },
  106076. enumerable: true,
  106077. configurable: true
  106078. });
  106079. EngineInstrumentation.prototype.dispose = function () {
  106080. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  106081. this._onBeginFrameObserver = null;
  106082. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  106083. this._onEndFrameObserver = null;
  106084. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106085. this._onBeforeShaderCompilationObserver = null;
  106086. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106087. this._onAfterShaderCompilationObserver = null;
  106088. this.engine = null;
  106089. };
  106090. return EngineInstrumentation;
  106091. }());
  106092. BABYLON.EngineInstrumentation = EngineInstrumentation;
  106093. })(BABYLON || (BABYLON = {}));
  106094. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  106095. var BABYLON;
  106096. (function (BABYLON) {
  106097. /**
  106098. * This class can be used to get instrumentation data from a Babylon engine
  106099. */
  106100. var SceneInstrumentation = /** @class */ (function () {
  106101. function SceneInstrumentation(scene) {
  106102. var _this = this;
  106103. this.scene = scene;
  106104. this._captureActiveMeshesEvaluationTime = false;
  106105. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  106106. this._captureRenderTargetsRenderTime = false;
  106107. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  106108. this._captureFrameTime = false;
  106109. this._frameTime = new BABYLON.PerfCounter();
  106110. this._captureRenderTime = false;
  106111. this._renderTime = new BABYLON.PerfCounter();
  106112. this._captureInterFrameTime = false;
  106113. this._interFrameTime = new BABYLON.PerfCounter();
  106114. this._captureParticlesRenderTime = false;
  106115. this._particlesRenderTime = new BABYLON.PerfCounter();
  106116. this._captureSpritesRenderTime = false;
  106117. this._spritesRenderTime = new BABYLON.PerfCounter();
  106118. this._capturePhysicsTime = false;
  106119. this._physicsTime = new BABYLON.PerfCounter();
  106120. this._captureAnimationsTime = false;
  106121. this._animationsTime = new BABYLON.PerfCounter();
  106122. this._captureCameraRenderTime = false;
  106123. this._cameraRenderTime = new BABYLON.PerfCounter();
  106124. // Observers
  106125. this._onBeforeActiveMeshesEvaluationObserver = null;
  106126. this._onAfterActiveMeshesEvaluationObserver = null;
  106127. this._onBeforeRenderTargetsRenderObserver = null;
  106128. this._onAfterRenderTargetsRenderObserver = null;
  106129. this._onAfterRenderObserver = null;
  106130. this._onBeforeDrawPhaseObserver = null;
  106131. this._onAfterDrawPhaseObserver = null;
  106132. this._onBeforeAnimationsObserver = null;
  106133. this._onBeforeParticlesRenderingObserver = null;
  106134. this._onAfterParticlesRenderingObserver = null;
  106135. this._onBeforeSpritesRenderingObserver = null;
  106136. this._onAfterSpritesRenderingObserver = null;
  106137. this._onBeforePhysicsObserver = null;
  106138. this._onAfterPhysicsObserver = null;
  106139. this._onAfterAnimationsObserver = null;
  106140. this._onBeforeCameraRenderObserver = null;
  106141. this._onAfterCameraRenderObserver = null;
  106142. // Before render
  106143. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  106144. if (_this._captureActiveMeshesEvaluationTime) {
  106145. _this._activeMeshesEvaluationTime.fetchNewFrame();
  106146. }
  106147. if (_this._captureRenderTargetsRenderTime) {
  106148. _this._renderTargetsRenderTime.fetchNewFrame();
  106149. }
  106150. if (_this._captureFrameTime) {
  106151. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  106152. _this._frameTime.beginMonitoring();
  106153. }
  106154. if (_this._captureInterFrameTime) {
  106155. _this._interFrameTime.endMonitoring();
  106156. }
  106157. if (_this._captureParticlesRenderTime) {
  106158. _this._particlesRenderTime.fetchNewFrame();
  106159. }
  106160. if (_this._captureSpritesRenderTime) {
  106161. _this._spritesRenderTime.fetchNewFrame();
  106162. }
  106163. if (_this._captureAnimationsTime) {
  106164. _this._animationsTime.beginMonitoring();
  106165. }
  106166. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  106167. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  106168. });
  106169. // After render
  106170. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  106171. if (_this._captureFrameTime) {
  106172. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  106173. _this._frameTime.endMonitoring();
  106174. }
  106175. if (_this._captureRenderTime) {
  106176. _this._renderTime.endMonitoring(false);
  106177. }
  106178. if (_this._captureInterFrameTime) {
  106179. _this._interFrameTime.beginMonitoring();
  106180. }
  106181. });
  106182. }
  106183. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  106184. // Properties
  106185. /**
  106186. * Gets the perf counter used for active meshes evaluation time
  106187. */
  106188. get: function () {
  106189. return this._activeMeshesEvaluationTime;
  106190. },
  106191. enumerable: true,
  106192. configurable: true
  106193. });
  106194. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  106195. /**
  106196. * Gets the active meshes evaluation time capture status
  106197. */
  106198. get: function () {
  106199. return this._captureActiveMeshesEvaluationTime;
  106200. },
  106201. /**
  106202. * Enable or disable the active meshes evaluation time capture
  106203. */
  106204. set: function (value) {
  106205. var _this = this;
  106206. if (value === this._captureActiveMeshesEvaluationTime) {
  106207. return;
  106208. }
  106209. this._captureActiveMeshesEvaluationTime = value;
  106210. if (value) {
  106211. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  106212. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  106213. _this._activeMeshesEvaluationTime.beginMonitoring();
  106214. });
  106215. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  106216. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  106217. _this._activeMeshesEvaluationTime.endMonitoring();
  106218. });
  106219. }
  106220. else {
  106221. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  106222. this._onBeforeActiveMeshesEvaluationObserver = null;
  106223. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  106224. this._onAfterActiveMeshesEvaluationObserver = null;
  106225. }
  106226. },
  106227. enumerable: true,
  106228. configurable: true
  106229. });
  106230. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  106231. /**
  106232. * Gets the perf counter used for render targets render time
  106233. */
  106234. get: function () {
  106235. return this._renderTargetsRenderTime;
  106236. },
  106237. enumerable: true,
  106238. configurable: true
  106239. });
  106240. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  106241. /**
  106242. * Gets the render targets render time capture status
  106243. */
  106244. get: function () {
  106245. return this._captureRenderTargetsRenderTime;
  106246. },
  106247. /**
  106248. * Enable or disable the render targets render time capture
  106249. */
  106250. set: function (value) {
  106251. var _this = this;
  106252. if (value === this._captureRenderTargetsRenderTime) {
  106253. return;
  106254. }
  106255. this._captureRenderTargetsRenderTime = value;
  106256. if (value) {
  106257. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  106258. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  106259. _this._renderTargetsRenderTime.beginMonitoring();
  106260. });
  106261. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  106262. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  106263. _this._renderTargetsRenderTime.endMonitoring(false);
  106264. });
  106265. }
  106266. else {
  106267. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  106268. this._onBeforeRenderTargetsRenderObserver = null;
  106269. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  106270. this._onAfterRenderTargetsRenderObserver = null;
  106271. }
  106272. },
  106273. enumerable: true,
  106274. configurable: true
  106275. });
  106276. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  106277. /**
  106278. * Gets the perf counter used for particles render time
  106279. */
  106280. get: function () {
  106281. return this._particlesRenderTime;
  106282. },
  106283. enumerable: true,
  106284. configurable: true
  106285. });
  106286. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  106287. /**
  106288. * Gets the particles render time capture status
  106289. */
  106290. get: function () {
  106291. return this._captureParticlesRenderTime;
  106292. },
  106293. /**
  106294. * Enable or disable the particles render time capture
  106295. */
  106296. set: function (value) {
  106297. var _this = this;
  106298. if (value === this._captureParticlesRenderTime) {
  106299. return;
  106300. }
  106301. this._captureParticlesRenderTime = value;
  106302. if (value) {
  106303. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  106304. BABYLON.Tools.StartPerformanceCounter("Particles");
  106305. _this._particlesRenderTime.beginMonitoring();
  106306. });
  106307. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  106308. BABYLON.Tools.EndPerformanceCounter("Particles");
  106309. _this._particlesRenderTime.endMonitoring(false);
  106310. });
  106311. }
  106312. else {
  106313. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  106314. this._onBeforeParticlesRenderingObserver = null;
  106315. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  106316. this._onAfterParticlesRenderingObserver = null;
  106317. }
  106318. },
  106319. enumerable: true,
  106320. configurable: true
  106321. });
  106322. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  106323. /**
  106324. * Gets the perf counter used for sprites render time
  106325. */
  106326. get: function () {
  106327. return this._spritesRenderTime;
  106328. },
  106329. enumerable: true,
  106330. configurable: true
  106331. });
  106332. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  106333. /**
  106334. * Gets the sprites render time capture status
  106335. */
  106336. get: function () {
  106337. return this._captureSpritesRenderTime;
  106338. },
  106339. /**
  106340. * Enable or disable the sprites render time capture
  106341. */
  106342. set: function (value) {
  106343. var _this = this;
  106344. if (value === this._captureSpritesRenderTime) {
  106345. return;
  106346. }
  106347. this._captureSpritesRenderTime = value;
  106348. if (!this.scene.spriteManagers) {
  106349. return;
  106350. }
  106351. if (value) {
  106352. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  106353. BABYLON.Tools.StartPerformanceCounter("Sprites");
  106354. _this._spritesRenderTime.beginMonitoring();
  106355. });
  106356. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  106357. BABYLON.Tools.EndPerformanceCounter("Sprites");
  106358. _this._spritesRenderTime.endMonitoring(false);
  106359. });
  106360. }
  106361. else {
  106362. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  106363. this._onBeforeSpritesRenderingObserver = null;
  106364. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  106365. this._onAfterSpritesRenderingObserver = null;
  106366. }
  106367. },
  106368. enumerable: true,
  106369. configurable: true
  106370. });
  106371. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  106372. /**
  106373. * Gets the perf counter used for physics time
  106374. */
  106375. get: function () {
  106376. return this._physicsTime;
  106377. },
  106378. enumerable: true,
  106379. configurable: true
  106380. });
  106381. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  106382. /**
  106383. * Gets the physics time capture status
  106384. */
  106385. get: function () {
  106386. return this._capturePhysicsTime;
  106387. },
  106388. /**
  106389. * Enable or disable the physics time capture
  106390. */
  106391. set: function (value) {
  106392. var _this = this;
  106393. if (value === this._capturePhysicsTime) {
  106394. return;
  106395. }
  106396. this._capturePhysicsTime = value;
  106397. if (value) {
  106398. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  106399. BABYLON.Tools.StartPerformanceCounter("Physics");
  106400. _this._physicsTime.beginMonitoring();
  106401. });
  106402. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  106403. BABYLON.Tools.EndPerformanceCounter("Physics");
  106404. _this._physicsTime.endMonitoring();
  106405. });
  106406. }
  106407. else {
  106408. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  106409. this._onBeforePhysicsObserver = null;
  106410. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  106411. this._onAfterPhysicsObserver = null;
  106412. }
  106413. },
  106414. enumerable: true,
  106415. configurable: true
  106416. });
  106417. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  106418. /**
  106419. * Gets the perf counter used for animations time
  106420. */
  106421. get: function () {
  106422. return this._animationsTime;
  106423. },
  106424. enumerable: true,
  106425. configurable: true
  106426. });
  106427. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  106428. /**
  106429. * Gets the animations time capture status
  106430. */
  106431. get: function () {
  106432. return this._captureAnimationsTime;
  106433. },
  106434. /**
  106435. * Enable or disable the animations time capture
  106436. */
  106437. set: function (value) {
  106438. var _this = this;
  106439. if (value === this._captureAnimationsTime) {
  106440. return;
  106441. }
  106442. this._captureAnimationsTime = value;
  106443. if (value) {
  106444. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  106445. _this._animationsTime.endMonitoring();
  106446. });
  106447. }
  106448. else {
  106449. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  106450. this._onAfterAnimationsObserver = null;
  106451. }
  106452. },
  106453. enumerable: true,
  106454. configurable: true
  106455. });
  106456. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  106457. /**
  106458. * Gets the perf counter used for frame time capture
  106459. */
  106460. get: function () {
  106461. return this._frameTime;
  106462. },
  106463. enumerable: true,
  106464. configurable: true
  106465. });
  106466. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  106467. /**
  106468. * Gets the frame time capture status
  106469. */
  106470. get: function () {
  106471. return this._captureFrameTime;
  106472. },
  106473. /**
  106474. * Enable or disable the frame time capture
  106475. */
  106476. set: function (value) {
  106477. this._captureFrameTime = value;
  106478. },
  106479. enumerable: true,
  106480. configurable: true
  106481. });
  106482. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  106483. /**
  106484. * Gets the perf counter used for inter-frames time capture
  106485. */
  106486. get: function () {
  106487. return this._interFrameTime;
  106488. },
  106489. enumerable: true,
  106490. configurable: true
  106491. });
  106492. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  106493. /**
  106494. * Gets the inter-frames time capture status
  106495. */
  106496. get: function () {
  106497. return this._captureInterFrameTime;
  106498. },
  106499. /**
  106500. * Enable or disable the inter-frames time capture
  106501. */
  106502. set: function (value) {
  106503. this._captureInterFrameTime = value;
  106504. },
  106505. enumerable: true,
  106506. configurable: true
  106507. });
  106508. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  106509. /**
  106510. * Gets the perf counter used for render time capture
  106511. */
  106512. get: function () {
  106513. return this._renderTime;
  106514. },
  106515. enumerable: true,
  106516. configurable: true
  106517. });
  106518. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  106519. /**
  106520. * Gets the render time capture status
  106521. */
  106522. get: function () {
  106523. return this._captureRenderTime;
  106524. },
  106525. /**
  106526. * Enable or disable the render time capture
  106527. */
  106528. set: function (value) {
  106529. var _this = this;
  106530. if (value === this._captureRenderTime) {
  106531. return;
  106532. }
  106533. this._captureRenderTime = value;
  106534. if (value) {
  106535. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  106536. _this._renderTime.beginMonitoring();
  106537. BABYLON.Tools.StartPerformanceCounter("Main render");
  106538. });
  106539. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  106540. _this._renderTime.endMonitoring(false);
  106541. BABYLON.Tools.EndPerformanceCounter("Main render");
  106542. });
  106543. }
  106544. else {
  106545. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  106546. this._onBeforeDrawPhaseObserver = null;
  106547. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  106548. this._onAfterDrawPhaseObserver = null;
  106549. }
  106550. },
  106551. enumerable: true,
  106552. configurable: true
  106553. });
  106554. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  106555. /**
  106556. * Gets the perf counter used for camera render time capture
  106557. */
  106558. get: function () {
  106559. return this._cameraRenderTime;
  106560. },
  106561. enumerable: true,
  106562. configurable: true
  106563. });
  106564. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  106565. /**
  106566. * Gets the camera render time capture status
  106567. */
  106568. get: function () {
  106569. return this._captureCameraRenderTime;
  106570. },
  106571. /**
  106572. * Enable or disable the camera render time capture
  106573. */
  106574. set: function (value) {
  106575. var _this = this;
  106576. if (value === this._captureCameraRenderTime) {
  106577. return;
  106578. }
  106579. this._captureCameraRenderTime = value;
  106580. if (value) {
  106581. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  106582. _this._cameraRenderTime.beginMonitoring();
  106583. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  106584. });
  106585. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  106586. _this._cameraRenderTime.endMonitoring(false);
  106587. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  106588. });
  106589. }
  106590. else {
  106591. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  106592. this._onBeforeCameraRenderObserver = null;
  106593. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  106594. this._onAfterCameraRenderObserver = null;
  106595. }
  106596. },
  106597. enumerable: true,
  106598. configurable: true
  106599. });
  106600. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  106601. /**
  106602. * Gets the perf counter used for draw calls
  106603. */
  106604. get: function () {
  106605. return this.scene.getEngine()._drawCalls;
  106606. },
  106607. enumerable: true,
  106608. configurable: true
  106609. });
  106610. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  106611. /**
  106612. * Gets the perf counter used for texture collisions
  106613. */
  106614. get: function () {
  106615. return this.scene.getEngine()._textureCollisions;
  106616. },
  106617. enumerable: true,
  106618. configurable: true
  106619. });
  106620. SceneInstrumentation.prototype.dispose = function () {
  106621. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  106622. this._onAfterRenderObserver = null;
  106623. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  106624. this._onBeforeActiveMeshesEvaluationObserver = null;
  106625. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  106626. this._onAfterActiveMeshesEvaluationObserver = null;
  106627. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  106628. this._onBeforeRenderTargetsRenderObserver = null;
  106629. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  106630. this._onAfterRenderTargetsRenderObserver = null;
  106631. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  106632. this._onBeforeAnimationsObserver = null;
  106633. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  106634. this._onBeforeParticlesRenderingObserver = null;
  106635. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  106636. this._onAfterParticlesRenderingObserver = null;
  106637. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  106638. this._onBeforeSpritesRenderingObserver = null;
  106639. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  106640. this._onAfterSpritesRenderingObserver = null;
  106641. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  106642. this._onBeforeDrawPhaseObserver = null;
  106643. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  106644. this._onAfterDrawPhaseObserver = null;
  106645. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  106646. this._onBeforePhysicsObserver = null;
  106647. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  106648. this._onAfterPhysicsObserver = null;
  106649. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  106650. this._onAfterAnimationsObserver = null;
  106651. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  106652. this._onBeforeCameraRenderObserver = null;
  106653. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  106654. this._onAfterCameraRenderObserver = null;
  106655. this.scene = null;
  106656. };
  106657. return SceneInstrumentation;
  106658. }());
  106659. BABYLON.SceneInstrumentation = SceneInstrumentation;
  106660. })(BABYLON || (BABYLON = {}));
  106661. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  106662. var BABYLON;
  106663. (function (BABYLON) {
  106664. /**
  106665. * @hidden
  106666. **/
  106667. var _TimeToken = /** @class */ (function () {
  106668. function _TimeToken() {
  106669. this._timeElapsedQueryEnded = false;
  106670. }
  106671. return _TimeToken;
  106672. }());
  106673. BABYLON._TimeToken = _TimeToken;
  106674. })(BABYLON || (BABYLON = {}));
  106675. //# sourceMappingURL=babylon.timeToken.js.map
  106676. var BABYLON;
  106677. (function (BABYLON) {
  106678. /**
  106679. * Background material defines definition.
  106680. * @hidden Mainly internal Use
  106681. */
  106682. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  106683. __extends(BackgroundMaterialDefines, _super);
  106684. /**
  106685. * Constructor of the defines.
  106686. */
  106687. function BackgroundMaterialDefines() {
  106688. var _this = _super.call(this) || this;
  106689. /**
  106690. * True if the diffuse texture is in use.
  106691. */
  106692. _this.DIFFUSE = false;
  106693. /**
  106694. * The direct UV channel to use.
  106695. */
  106696. _this.DIFFUSEDIRECTUV = 0;
  106697. /**
  106698. * True if the diffuse texture is in gamma space.
  106699. */
  106700. _this.GAMMADIFFUSE = false;
  106701. /**
  106702. * True if the diffuse texture has opacity in the alpha channel.
  106703. */
  106704. _this.DIFFUSEHASALPHA = false;
  106705. /**
  106706. * True if you want the material to fade to transparent at grazing angle.
  106707. */
  106708. _this.OPACITYFRESNEL = false;
  106709. /**
  106710. * True if an extra blur needs to be added in the reflection.
  106711. */
  106712. _this.REFLECTIONBLUR = false;
  106713. /**
  106714. * True if you want the material to fade to reflection at grazing angle.
  106715. */
  106716. _this.REFLECTIONFRESNEL = false;
  106717. /**
  106718. * True if you want the material to falloff as far as you move away from the scene center.
  106719. */
  106720. _this.REFLECTIONFALLOFF = false;
  106721. /**
  106722. * False if the current Webgl implementation does not support the texture lod extension.
  106723. */
  106724. _this.TEXTURELODSUPPORT = false;
  106725. /**
  106726. * True to ensure the data are premultiplied.
  106727. */
  106728. _this.PREMULTIPLYALPHA = false;
  106729. /**
  106730. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  106731. */
  106732. _this.USERGBCOLOR = false;
  106733. /**
  106734. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  106735. * stays aligned with the desired configuration.
  106736. */
  106737. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  106738. /**
  106739. * True to add noise in order to reduce the banding effect.
  106740. */
  106741. _this.NOISE = false;
  106742. /**
  106743. * is the reflection texture in BGR color scheme?
  106744. * Mainly used to solve a bug in ios10 video tag
  106745. */
  106746. _this.REFLECTIONBGR = false;
  106747. _this.IMAGEPROCESSING = false;
  106748. _this.VIGNETTE = false;
  106749. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  106750. _this.VIGNETTEBLENDMODEOPAQUE = false;
  106751. _this.TONEMAPPING = false;
  106752. _this.TONEMAPPING_ACES = false;
  106753. _this.CONTRAST = false;
  106754. _this.COLORCURVES = false;
  106755. _this.COLORGRADING = false;
  106756. _this.COLORGRADING3D = false;
  106757. _this.SAMPLER3DGREENDEPTH = false;
  106758. _this.SAMPLER3DBGRMAP = false;
  106759. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  106760. _this.EXPOSURE = false;
  106761. // Reflection.
  106762. _this.REFLECTION = false;
  106763. _this.REFLECTIONMAP_3D = false;
  106764. _this.REFLECTIONMAP_SPHERICAL = false;
  106765. _this.REFLECTIONMAP_PLANAR = false;
  106766. _this.REFLECTIONMAP_CUBIC = false;
  106767. _this.REFLECTIONMAP_PROJECTION = false;
  106768. _this.REFLECTIONMAP_SKYBOX = false;
  106769. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  106770. _this.REFLECTIONMAP_EXPLICIT = false;
  106771. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  106772. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  106773. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  106774. _this.INVERTCUBICMAP = false;
  106775. _this.REFLECTIONMAP_OPPOSITEZ = false;
  106776. _this.LODINREFLECTIONALPHA = false;
  106777. _this.GAMMAREFLECTION = false;
  106778. _this.RGBDREFLECTION = false;
  106779. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  106780. // Default BJS.
  106781. _this.MAINUV1 = false;
  106782. _this.MAINUV2 = false;
  106783. _this.UV1 = false;
  106784. _this.UV2 = false;
  106785. _this.CLIPPLANE = false;
  106786. _this.CLIPPLANE2 = false;
  106787. _this.CLIPPLANE3 = false;
  106788. _this.CLIPPLANE4 = false;
  106789. _this.POINTSIZE = false;
  106790. _this.FOG = false;
  106791. _this.NORMAL = false;
  106792. _this.NUM_BONE_INFLUENCERS = 0;
  106793. _this.BonesPerMesh = 0;
  106794. _this.INSTANCES = false;
  106795. _this.SHADOWFLOAT = false;
  106796. _this.rebuild();
  106797. return _this;
  106798. }
  106799. return BackgroundMaterialDefines;
  106800. }(BABYLON.MaterialDefines));
  106801. /**
  106802. * Background material used to create an efficient environement around your scene.
  106803. */
  106804. var BackgroundMaterial = /** @class */ (function (_super) {
  106805. __extends(BackgroundMaterial, _super);
  106806. /**
  106807. * Instantiates a Background Material in the given scene
  106808. * @param name The friendly name of the material
  106809. * @param scene The scene to add the material to
  106810. */
  106811. function BackgroundMaterial(name, scene) {
  106812. var _this = _super.call(this, name, scene) || this;
  106813. /**
  106814. * Key light Color (multiply against the environement texture)
  106815. */
  106816. _this.primaryColor = BABYLON.Color3.White();
  106817. _this._primaryColorShadowLevel = 0;
  106818. _this._primaryColorHighlightLevel = 0;
  106819. /**
  106820. * Reflection Texture used in the material.
  106821. * Should be author in a specific way for the best result (refer to the documentation).
  106822. */
  106823. _this.reflectionTexture = null;
  106824. /**
  106825. * Reflection Texture level of blur.
  106826. *
  106827. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  106828. * texture twice.
  106829. */
  106830. _this.reflectionBlur = 0;
  106831. /**
  106832. * Diffuse Texture used in the material.
  106833. * Should be author in a specific way for the best result (refer to the documentation).
  106834. */
  106835. _this.diffuseTexture = null;
  106836. _this._shadowLights = null;
  106837. /**
  106838. * Specify the list of lights casting shadow on the material.
  106839. * All scene shadow lights will be included if null.
  106840. */
  106841. _this.shadowLights = null;
  106842. /**
  106843. * Helps adjusting the shadow to a softer level if required.
  106844. * 0 means black shadows and 1 means no shadows.
  106845. */
  106846. _this.shadowLevel = 0;
  106847. /**
  106848. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  106849. * It is usually zero but might be interesting to modify according to your setup.
  106850. */
  106851. _this.sceneCenter = BABYLON.Vector3.Zero();
  106852. /**
  106853. * This helps specifying that the material is falling off to the sky box at grazing angle.
  106854. * This helps ensuring a nice transition when the camera goes under the ground.
  106855. */
  106856. _this.opacityFresnel = true;
  106857. /**
  106858. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  106859. * This helps adding a mirror texture on the ground.
  106860. */
  106861. _this.reflectionFresnel = false;
  106862. /**
  106863. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  106864. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  106865. */
  106866. _this.reflectionFalloffDistance = 0.0;
  106867. /**
  106868. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  106869. */
  106870. _this.reflectionAmount = 1.0;
  106871. /**
  106872. * This specifies the weight of the reflection at grazing angle.
  106873. */
  106874. _this.reflectionReflectance0 = 0.05;
  106875. /**
  106876. * This specifies the weight of the reflection at a perpendicular point of view.
  106877. */
  106878. _this.reflectionReflectance90 = 0.5;
  106879. /**
  106880. * Helps to directly use the maps channels instead of their level.
  106881. */
  106882. _this.useRGBColor = true;
  106883. /**
  106884. * This helps reducing the banding effect that could occur on the background.
  106885. */
  106886. _this.enableNoise = false;
  106887. _this._fovMultiplier = 1.0;
  106888. /**
  106889. * Enable the FOV adjustment feature controlled by fovMultiplier.
  106890. */
  106891. _this.useEquirectangularFOV = false;
  106892. _this._maxSimultaneousLights = 4;
  106893. /**
  106894. * Number of Simultaneous lights allowed on the material.
  106895. */
  106896. _this.maxSimultaneousLights = 4;
  106897. /**
  106898. * Keep track of the image processing observer to allow dispose and replace.
  106899. */
  106900. _this._imageProcessingObserver = null;
  106901. /**
  106902. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  106903. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  106904. */
  106905. _this.switchToBGR = false;
  106906. // Temp values kept as cache in the material.
  106907. _this._renderTargets = new BABYLON.SmartArray(16);
  106908. _this._reflectionControls = BABYLON.Vector4.Zero();
  106909. _this._white = BABYLON.Color3.White();
  106910. _this._primaryShadowColor = BABYLON.Color3.Black();
  106911. _this._primaryHighlightColor = BABYLON.Color3.Black();
  106912. // Setup the default processing configuration to the scene.
  106913. _this._attachImageProcessingConfiguration(null);
  106914. _this.getRenderTargetTextures = function () {
  106915. _this._renderTargets.reset();
  106916. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  106917. _this._renderTargets.push(_this._diffuseTexture);
  106918. }
  106919. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  106920. _this._renderTargets.push(_this._reflectionTexture);
  106921. }
  106922. return _this._renderTargets;
  106923. };
  106924. return _this;
  106925. }
  106926. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  106927. /**
  106928. * Experimental Internal Use Only.
  106929. *
  106930. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  106931. * This acts as a helper to set the primary color to a more "human friendly" value.
  106932. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  106933. * output color as close as possible from the chosen value.
  106934. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  106935. * part of lighting setup.)
  106936. */
  106937. get: function () {
  106938. return this.__perceptualColor;
  106939. },
  106940. set: function (value) {
  106941. this.__perceptualColor = value;
  106942. this._computePrimaryColorFromPerceptualColor();
  106943. this._markAllSubMeshesAsLightsDirty();
  106944. },
  106945. enumerable: true,
  106946. configurable: true
  106947. });
  106948. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  106949. /**
  106950. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  106951. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  106952. */
  106953. get: function () {
  106954. return this._primaryColorShadowLevel;
  106955. },
  106956. set: function (value) {
  106957. this._primaryColorShadowLevel = value;
  106958. this._computePrimaryColors();
  106959. this._markAllSubMeshesAsLightsDirty();
  106960. },
  106961. enumerable: true,
  106962. configurable: true
  106963. });
  106964. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  106965. /**
  106966. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  106967. * The primary color is used at the level chosen to define what the white area would look.
  106968. */
  106969. get: function () {
  106970. return this._primaryColorHighlightLevel;
  106971. },
  106972. set: function (value) {
  106973. this._primaryColorHighlightLevel = value;
  106974. this._computePrimaryColors();
  106975. this._markAllSubMeshesAsLightsDirty();
  106976. },
  106977. enumerable: true,
  106978. configurable: true
  106979. });
  106980. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  106981. /**
  106982. * Sets the reflection reflectance fresnel values according to the default standard
  106983. * empirically know to work well :-)
  106984. */
  106985. set: function (value) {
  106986. var reflectionWeight = value;
  106987. if (reflectionWeight < 0.5) {
  106988. reflectionWeight = reflectionWeight * 2.0;
  106989. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  106990. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  106991. }
  106992. else {
  106993. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  106994. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  106995. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  106996. }
  106997. },
  106998. enumerable: true,
  106999. configurable: true
  107000. });
  107001. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  107002. /**
  107003. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  107004. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  107005. * Recommended to be keep at 1.0 except for special cases.
  107006. */
  107007. get: function () {
  107008. return this._fovMultiplier;
  107009. },
  107010. set: function (value) {
  107011. if (isNaN(value)) {
  107012. value = 1.0;
  107013. }
  107014. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  107015. },
  107016. enumerable: true,
  107017. configurable: true
  107018. });
  107019. /**
  107020. * Attaches a new image processing configuration to the PBR Material.
  107021. * @param configuration (if null the scene configuration will be use)
  107022. */
  107023. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  107024. var _this = this;
  107025. if (configuration === this._imageProcessingConfiguration) {
  107026. return;
  107027. }
  107028. // Detaches observer.
  107029. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  107030. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  107031. }
  107032. // Pick the scene configuration if needed.
  107033. if (!configuration) {
  107034. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  107035. }
  107036. else {
  107037. this._imageProcessingConfiguration = configuration;
  107038. }
  107039. // Attaches observer.
  107040. if (this._imageProcessingConfiguration) {
  107041. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  107042. _this._computePrimaryColorFromPerceptualColor();
  107043. _this._markAllSubMeshesAsImageProcessingDirty();
  107044. });
  107045. }
  107046. };
  107047. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  107048. /**
  107049. * Gets the image processing configuration used either in this material.
  107050. */
  107051. get: function () {
  107052. return this._imageProcessingConfiguration;
  107053. },
  107054. /**
  107055. * Sets the Default image processing configuration used either in the this material.
  107056. *
  107057. * If sets to null, the scene one is in use.
  107058. */
  107059. set: function (value) {
  107060. this._attachImageProcessingConfiguration(value);
  107061. // Ensure the effect will be rebuilt.
  107062. this._markAllSubMeshesAsTexturesDirty();
  107063. },
  107064. enumerable: true,
  107065. configurable: true
  107066. });
  107067. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  107068. /**
  107069. * Gets wether the color curves effect is enabled.
  107070. */
  107071. get: function () {
  107072. return this.imageProcessingConfiguration.colorCurvesEnabled;
  107073. },
  107074. /**
  107075. * Sets wether the color curves effect is enabled.
  107076. */
  107077. set: function (value) {
  107078. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  107079. },
  107080. enumerable: true,
  107081. configurable: true
  107082. });
  107083. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  107084. /**
  107085. * Gets wether the color grading effect is enabled.
  107086. */
  107087. get: function () {
  107088. return this.imageProcessingConfiguration.colorGradingEnabled;
  107089. },
  107090. /**
  107091. * Gets wether the color grading effect is enabled.
  107092. */
  107093. set: function (value) {
  107094. this.imageProcessingConfiguration.colorGradingEnabled = value;
  107095. },
  107096. enumerable: true,
  107097. configurable: true
  107098. });
  107099. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  107100. /**
  107101. * Gets wether tonemapping is enabled or not.
  107102. */
  107103. get: function () {
  107104. return this._imageProcessingConfiguration.toneMappingEnabled;
  107105. },
  107106. /**
  107107. * Sets wether tonemapping is enabled or not
  107108. */
  107109. set: function (value) {
  107110. this._imageProcessingConfiguration.toneMappingEnabled = value;
  107111. },
  107112. enumerable: true,
  107113. configurable: true
  107114. });
  107115. ;
  107116. ;
  107117. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  107118. /**
  107119. * The camera exposure used on this material.
  107120. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107121. * This corresponds to a photographic exposure.
  107122. */
  107123. get: function () {
  107124. return this._imageProcessingConfiguration.exposure;
  107125. },
  107126. /**
  107127. * The camera exposure used on this material.
  107128. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107129. * This corresponds to a photographic exposure.
  107130. */
  107131. set: function (value) {
  107132. this._imageProcessingConfiguration.exposure = value;
  107133. },
  107134. enumerable: true,
  107135. configurable: true
  107136. });
  107137. ;
  107138. ;
  107139. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  107140. /**
  107141. * Gets The camera contrast used on this material.
  107142. */
  107143. get: function () {
  107144. return this._imageProcessingConfiguration.contrast;
  107145. },
  107146. /**
  107147. * Sets The camera contrast used on this material.
  107148. */
  107149. set: function (value) {
  107150. this._imageProcessingConfiguration.contrast = value;
  107151. },
  107152. enumerable: true,
  107153. configurable: true
  107154. });
  107155. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  107156. /**
  107157. * Gets the Color Grading 2D Lookup Texture.
  107158. */
  107159. get: function () {
  107160. return this._imageProcessingConfiguration.colorGradingTexture;
  107161. },
  107162. /**
  107163. * Sets the Color Grading 2D Lookup Texture.
  107164. */
  107165. set: function (value) {
  107166. this.imageProcessingConfiguration.colorGradingTexture = value;
  107167. },
  107168. enumerable: true,
  107169. configurable: true
  107170. });
  107171. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  107172. /**
  107173. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  107174. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  107175. * 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;
  107176. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  107177. */
  107178. get: function () {
  107179. return this.imageProcessingConfiguration.colorCurves;
  107180. },
  107181. /**
  107182. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  107183. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  107184. * 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;
  107185. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  107186. */
  107187. set: function (value) {
  107188. this.imageProcessingConfiguration.colorCurves = value;
  107189. },
  107190. enumerable: true,
  107191. configurable: true
  107192. });
  107193. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  107194. /**
  107195. * Gets a boolean indicating that current material needs to register RTT
  107196. */
  107197. get: function () {
  107198. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  107199. return true;
  107200. }
  107201. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  107202. return true;
  107203. }
  107204. return false;
  107205. },
  107206. enumerable: true,
  107207. configurable: true
  107208. });
  107209. /**
  107210. * The entire material has been created in order to prevent overdraw.
  107211. * @returns false
  107212. */
  107213. BackgroundMaterial.prototype.needAlphaTesting = function () {
  107214. return true;
  107215. };
  107216. /**
  107217. * The entire material has been created in order to prevent overdraw.
  107218. * @returns true if blending is enable
  107219. */
  107220. BackgroundMaterial.prototype.needAlphaBlending = function () {
  107221. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  107222. };
  107223. /**
  107224. * Checks wether the material is ready to be rendered for a given mesh.
  107225. * @param mesh The mesh to render
  107226. * @param subMesh The submesh to check against
  107227. * @param useInstances Specify wether or not the material is used with instances
  107228. * @returns true if all the dependencies are ready (Textures, Effects...)
  107229. */
  107230. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  107231. var _this = this;
  107232. if (useInstances === void 0) { useInstances = false; }
  107233. if (subMesh.effect && this.isFrozen) {
  107234. if (this._wasPreviouslyReady) {
  107235. return true;
  107236. }
  107237. }
  107238. if (!subMesh._materialDefines) {
  107239. subMesh._materialDefines = new BackgroundMaterialDefines();
  107240. }
  107241. var scene = this.getScene();
  107242. var defines = subMesh._materialDefines;
  107243. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  107244. if (defines._renderId === scene.getRenderId()) {
  107245. return true;
  107246. }
  107247. }
  107248. var engine = scene.getEngine();
  107249. // Lights
  107250. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  107251. defines._needNormals = true;
  107252. // Textures
  107253. if (defines._areTexturesDirty) {
  107254. defines._needUVs = false;
  107255. if (scene.texturesEnabled) {
  107256. if (scene.getEngine().getCaps().textureLOD) {
  107257. defines.TEXTURELODSUPPORT = true;
  107258. }
  107259. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  107260. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  107261. return false;
  107262. }
  107263. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  107264. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  107265. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  107266. defines.OPACITYFRESNEL = this._opacityFresnel;
  107267. }
  107268. else {
  107269. defines.DIFFUSE = false;
  107270. defines.DIFFUSEHASALPHA = false;
  107271. defines.GAMMADIFFUSE = false;
  107272. defines.OPACITYFRESNEL = false;
  107273. }
  107274. var reflectionTexture = this._reflectionTexture;
  107275. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  107276. if (!reflectionTexture.isReadyOrNotBlocking()) {
  107277. return false;
  107278. }
  107279. defines.REFLECTION = true;
  107280. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  107281. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  107282. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  107283. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  107284. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  107285. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  107286. defines.REFLECTIONBGR = this.switchToBGR;
  107287. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  107288. defines.INVERTCUBICMAP = true;
  107289. }
  107290. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  107291. switch (reflectionTexture.coordinatesMode) {
  107292. case BABYLON.Texture.EXPLICIT_MODE:
  107293. defines.REFLECTIONMAP_EXPLICIT = true;
  107294. break;
  107295. case BABYLON.Texture.PLANAR_MODE:
  107296. defines.REFLECTIONMAP_PLANAR = true;
  107297. break;
  107298. case BABYLON.Texture.PROJECTION_MODE:
  107299. defines.REFLECTIONMAP_PROJECTION = true;
  107300. break;
  107301. case BABYLON.Texture.SKYBOX_MODE:
  107302. defines.REFLECTIONMAP_SKYBOX = true;
  107303. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  107304. break;
  107305. case BABYLON.Texture.SPHERICAL_MODE:
  107306. defines.REFLECTIONMAP_SPHERICAL = true;
  107307. break;
  107308. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  107309. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  107310. break;
  107311. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  107312. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  107313. break;
  107314. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  107315. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  107316. break;
  107317. case BABYLON.Texture.CUBIC_MODE:
  107318. case BABYLON.Texture.INVCUBIC_MODE:
  107319. default:
  107320. defines.REFLECTIONMAP_CUBIC = true;
  107321. break;
  107322. }
  107323. if (this.reflectionFresnel) {
  107324. defines.REFLECTIONFRESNEL = true;
  107325. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  107326. this._reflectionControls.x = this.reflectionAmount;
  107327. this._reflectionControls.y = this.reflectionReflectance0;
  107328. this._reflectionControls.z = this.reflectionReflectance90;
  107329. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  107330. }
  107331. else {
  107332. defines.REFLECTIONFRESNEL = false;
  107333. defines.REFLECTIONFALLOFF = false;
  107334. }
  107335. }
  107336. else {
  107337. defines.REFLECTION = false;
  107338. defines.REFLECTIONFRESNEL = false;
  107339. defines.REFLECTIONFALLOFF = false;
  107340. defines.REFLECTIONBLUR = false;
  107341. defines.REFLECTIONMAP_3D = false;
  107342. defines.REFLECTIONMAP_SPHERICAL = false;
  107343. defines.REFLECTIONMAP_PLANAR = false;
  107344. defines.REFLECTIONMAP_CUBIC = false;
  107345. defines.REFLECTIONMAP_PROJECTION = false;
  107346. defines.REFLECTIONMAP_SKYBOX = false;
  107347. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  107348. defines.REFLECTIONMAP_EXPLICIT = false;
  107349. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  107350. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  107351. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  107352. defines.INVERTCUBICMAP = false;
  107353. defines.REFLECTIONMAP_OPPOSITEZ = false;
  107354. defines.LODINREFLECTIONALPHA = false;
  107355. defines.GAMMAREFLECTION = false;
  107356. defines.RGBDREFLECTION = false;
  107357. }
  107358. }
  107359. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  107360. defines.USERGBCOLOR = this._useRGBColor;
  107361. defines.NOISE = this._enableNoise;
  107362. }
  107363. if (defines._areLightsDirty) {
  107364. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  107365. }
  107366. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  107367. if (!this._imageProcessingConfiguration.isReady()) {
  107368. return false;
  107369. }
  107370. this._imageProcessingConfiguration.prepareDefines(defines);
  107371. }
  107372. // Misc.
  107373. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  107374. // Values that need to be evaluated on every frame
  107375. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  107376. // Attribs
  107377. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  107378. if (mesh) {
  107379. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  107380. mesh.createNormals(true);
  107381. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  107382. }
  107383. }
  107384. }
  107385. // Get correct effect
  107386. if (defines.isDirty) {
  107387. defines.markAsProcessed();
  107388. scene.resetCachedMaterial();
  107389. // Fallbacks
  107390. var fallbacks = new BABYLON.EffectFallbacks();
  107391. if (defines.FOG) {
  107392. fallbacks.addFallback(0, "FOG");
  107393. }
  107394. if (defines.POINTSIZE) {
  107395. fallbacks.addFallback(1, "POINTSIZE");
  107396. }
  107397. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  107398. if (defines.NUM_BONE_INFLUENCERS > 0) {
  107399. fallbacks.addCPUSkinningFallback(0, mesh);
  107400. }
  107401. //Attributes
  107402. var attribs = [BABYLON.VertexBuffer.PositionKind];
  107403. if (defines.NORMAL) {
  107404. attribs.push(BABYLON.VertexBuffer.NormalKind);
  107405. }
  107406. if (defines.UV1) {
  107407. attribs.push(BABYLON.VertexBuffer.UVKind);
  107408. }
  107409. if (defines.UV2) {
  107410. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  107411. }
  107412. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  107413. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  107414. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  107415. "vFogInfos", "vFogColor", "pointSize",
  107416. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  107417. "vPrimaryColor", "vPrimaryColorShadow",
  107418. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  107419. "shadowLevel", "alpha",
  107420. "vBackgroundCenter", "vReflectionControl",
  107421. "vDiffuseInfos", "diffuseMatrix",
  107422. ];
  107423. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  107424. var uniformBuffers = ["Material", "Scene"];
  107425. if (BABYLON.ImageProcessingConfiguration) {
  107426. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  107427. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  107428. }
  107429. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  107430. uniformsNames: uniforms,
  107431. uniformBuffersNames: uniformBuffers,
  107432. samplers: samplers,
  107433. defines: defines,
  107434. maxSimultaneousLights: this._maxSimultaneousLights
  107435. });
  107436. var onCompiled = function (effect) {
  107437. if (_this.onCompiled) {
  107438. _this.onCompiled(effect);
  107439. }
  107440. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  107441. };
  107442. var join = defines.toString();
  107443. subMesh.setEffect(scene.getEngine().createEffect("background", {
  107444. attributes: attribs,
  107445. uniformsNames: uniforms,
  107446. uniformBuffersNames: uniformBuffers,
  107447. samplers: samplers,
  107448. defines: join,
  107449. fallbacks: fallbacks,
  107450. onCompiled: onCompiled,
  107451. onError: this.onError,
  107452. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  107453. }, engine), defines);
  107454. this.buildUniformLayout();
  107455. }
  107456. if (!subMesh.effect || !subMesh.effect.isReady()) {
  107457. return false;
  107458. }
  107459. defines._renderId = scene.getRenderId();
  107460. this._wasPreviouslyReady = true;
  107461. return true;
  107462. };
  107463. /**
  107464. * Compute the primary color according to the chosen perceptual color.
  107465. */
  107466. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  107467. if (!this.__perceptualColor) {
  107468. return;
  107469. }
  107470. this._primaryColor.copyFrom(this.__perceptualColor);
  107471. // Revert gamma space.
  107472. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  107473. // Revert image processing configuration.
  107474. if (this._imageProcessingConfiguration) {
  107475. // Revert Exposure.
  107476. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  107477. }
  107478. this._computePrimaryColors();
  107479. };
  107480. /**
  107481. * Compute the highlights and shadow colors according to their chosen levels.
  107482. */
  107483. BackgroundMaterial.prototype._computePrimaryColors = function () {
  107484. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  107485. return;
  107486. }
  107487. // Find the highlight color based on the configuration.
  107488. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  107489. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  107490. // Find the shadow color based on the configuration.
  107491. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  107492. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  107493. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  107494. };
  107495. /**
  107496. * Build the uniform buffer used in the material.
  107497. */
  107498. BackgroundMaterial.prototype.buildUniformLayout = function () {
  107499. // Order is important !
  107500. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  107501. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  107502. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  107503. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  107504. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  107505. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  107506. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  107507. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  107508. this._uniformBuffer.addUniform("pointSize", 1);
  107509. this._uniformBuffer.addUniform("shadowLevel", 1);
  107510. this._uniformBuffer.addUniform("alpha", 1);
  107511. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  107512. this._uniformBuffer.addUniform("vReflectionControl", 4);
  107513. this._uniformBuffer.create();
  107514. };
  107515. /**
  107516. * Unbind the material.
  107517. */
  107518. BackgroundMaterial.prototype.unbind = function () {
  107519. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  107520. this._uniformBuffer.setTexture("diffuseSampler", null);
  107521. }
  107522. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  107523. this._uniformBuffer.setTexture("reflectionSampler", null);
  107524. }
  107525. _super.prototype.unbind.call(this);
  107526. };
  107527. /**
  107528. * Bind only the world matrix to the material.
  107529. * @param world The world matrix to bind.
  107530. */
  107531. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  107532. this._activeEffect.setMatrix("world", world);
  107533. };
  107534. /**
  107535. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  107536. * @param world The world matrix to bind.
  107537. * @param subMesh The submesh to bind for.
  107538. */
  107539. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  107540. var scene = this.getScene();
  107541. var defines = subMesh._materialDefines;
  107542. if (!defines) {
  107543. return;
  107544. }
  107545. var effect = subMesh.effect;
  107546. if (!effect) {
  107547. return;
  107548. }
  107549. this._activeEffect = effect;
  107550. // Matrices
  107551. this.bindOnlyWorldMatrix(world);
  107552. // Bones
  107553. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  107554. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  107555. if (mustRebind) {
  107556. this._uniformBuffer.bindToEffect(effect, "Material");
  107557. this.bindViewProjection(effect);
  107558. var reflectionTexture = this._reflectionTexture;
  107559. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  107560. // Texture uniforms
  107561. if (scene.texturesEnabled) {
  107562. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  107563. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  107564. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  107565. }
  107566. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  107567. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  107568. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  107569. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  107570. }
  107571. }
  107572. if (this.shadowLevel > 0) {
  107573. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  107574. }
  107575. this._uniformBuffer.updateFloat("alpha", this.alpha);
  107576. // Point size
  107577. if (this.pointsCloud) {
  107578. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  107579. }
  107580. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  107581. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  107582. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  107583. }
  107584. else {
  107585. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  107586. }
  107587. }
  107588. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  107589. // Textures
  107590. if (scene.texturesEnabled) {
  107591. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  107592. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  107593. }
  107594. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  107595. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  107596. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  107597. }
  107598. else if (!defines.REFLECTIONBLUR) {
  107599. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  107600. }
  107601. else {
  107602. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  107603. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  107604. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  107605. }
  107606. if (defines.REFLECTIONFRESNEL) {
  107607. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  107608. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  107609. }
  107610. }
  107611. }
  107612. // Clip plane
  107613. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  107614. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  107615. }
  107616. if (mustRebind || !this.isFrozen) {
  107617. if (scene.lightsEnabled) {
  107618. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  107619. }
  107620. // View
  107621. this.bindView(effect);
  107622. // Fog
  107623. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  107624. // image processing
  107625. if (this._imageProcessingConfiguration) {
  107626. this._imageProcessingConfiguration.bind(this._activeEffect);
  107627. }
  107628. }
  107629. this._uniformBuffer.update();
  107630. this._afterBind(mesh, this._activeEffect);
  107631. };
  107632. /**
  107633. * Dispose the material.
  107634. * @param forceDisposeEffect Force disposal of the associated effect.
  107635. * @param forceDisposeTextures Force disposal of the associated textures.
  107636. */
  107637. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  107638. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  107639. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  107640. if (forceDisposeTextures) {
  107641. if (this.diffuseTexture) {
  107642. this.diffuseTexture.dispose();
  107643. }
  107644. if (this.reflectionTexture) {
  107645. this.reflectionTexture.dispose();
  107646. }
  107647. }
  107648. this._renderTargets.dispose();
  107649. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  107650. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  107651. }
  107652. _super.prototype.dispose.call(this, forceDisposeEffect);
  107653. };
  107654. /**
  107655. * Clones the material.
  107656. * @param name The cloned name.
  107657. * @returns The cloned material.
  107658. */
  107659. BackgroundMaterial.prototype.clone = function (name) {
  107660. var _this = this;
  107661. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  107662. };
  107663. /**
  107664. * Serializes the current material to its JSON representation.
  107665. * @returns The JSON representation.
  107666. */
  107667. BackgroundMaterial.prototype.serialize = function () {
  107668. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  107669. serializationObject.customType = "BABYLON.BackgroundMaterial";
  107670. return serializationObject;
  107671. };
  107672. /**
  107673. * Gets the class name of the material
  107674. * @returns "BackgroundMaterial"
  107675. */
  107676. BackgroundMaterial.prototype.getClassName = function () {
  107677. return "BackgroundMaterial";
  107678. };
  107679. /**
  107680. * Parse a JSON input to create back a background material.
  107681. * @param source The JSON data to parse
  107682. * @param scene The scene to create the parsed material in
  107683. * @param rootUrl The root url of the assets the material depends upon
  107684. * @returns the instantiated BackgroundMaterial.
  107685. */
  107686. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  107687. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  107688. };
  107689. /**
  107690. * Standard reflectance value at parallel view angle.
  107691. */
  107692. BackgroundMaterial.StandardReflectance0 = 0.05;
  107693. /**
  107694. * Standard reflectance value at grazing angle.
  107695. */
  107696. BackgroundMaterial.StandardReflectance90 = 0.5;
  107697. __decorate([
  107698. BABYLON.serializeAsColor3()
  107699. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  107700. __decorate([
  107701. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  107702. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  107703. __decorate([
  107704. BABYLON.serializeAsColor3()
  107705. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  107706. __decorate([
  107707. BABYLON.serialize()
  107708. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  107709. __decorate([
  107710. BABYLON.serialize()
  107711. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  107712. __decorate([
  107713. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  107714. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  107715. __decorate([
  107716. BABYLON.serializeAsTexture()
  107717. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  107718. __decorate([
  107719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107720. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  107721. __decorate([
  107722. BABYLON.serialize()
  107723. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  107724. __decorate([
  107725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107726. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  107727. __decorate([
  107728. BABYLON.serializeAsTexture()
  107729. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  107730. __decorate([
  107731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107732. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  107733. __decorate([
  107734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107735. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  107736. __decorate([
  107737. BABYLON.serialize()
  107738. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  107739. __decorate([
  107740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107741. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  107742. __decorate([
  107743. BABYLON.serializeAsVector3()
  107744. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  107745. __decorate([
  107746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107747. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  107748. __decorate([
  107749. BABYLON.serialize()
  107750. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  107751. __decorate([
  107752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107753. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  107754. __decorate([
  107755. BABYLON.serialize()
  107756. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  107757. __decorate([
  107758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107759. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  107760. __decorate([
  107761. BABYLON.serialize()
  107762. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  107763. __decorate([
  107764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107765. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  107766. __decorate([
  107767. BABYLON.serialize()
  107768. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  107769. __decorate([
  107770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107771. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  107772. __decorate([
  107773. BABYLON.serialize()
  107774. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  107775. __decorate([
  107776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107777. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  107778. __decorate([
  107779. BABYLON.serialize()
  107780. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  107781. __decorate([
  107782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107783. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  107784. __decorate([
  107785. BABYLON.serialize()
  107786. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  107787. __decorate([
  107788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107789. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  107790. __decorate([
  107791. BABYLON.serialize()
  107792. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  107793. __decorate([
  107794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107795. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  107796. __decorate([
  107797. BABYLON.serialize()
  107798. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  107799. __decorate([
  107800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107801. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  107802. __decorate([
  107803. BABYLON.serializeAsImageProcessingConfiguration()
  107804. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  107805. return BackgroundMaterial;
  107806. }(BABYLON.PushMaterial));
  107807. BABYLON.BackgroundMaterial = BackgroundMaterial;
  107808. })(BABYLON || (BABYLON = {}));
  107809. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  107810. var __assign = (this && this.__assign) || function () {
  107811. __assign = Object.assign || function(t) {
  107812. for (var s, i = 1, n = arguments.length; i < n; i++) {
  107813. s = arguments[i];
  107814. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  107815. t[p] = s[p];
  107816. }
  107817. return t;
  107818. };
  107819. return __assign.apply(this, arguments);
  107820. };
  107821. var BABYLON;
  107822. (function (BABYLON) {
  107823. /**
  107824. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  107825. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  107826. * It also helps with the default setup of your imageProcessing configuration.
  107827. */
  107828. var EnvironmentHelper = /** @class */ (function () {
  107829. /**
  107830. * constructor
  107831. * @param options
  107832. * @param scene The scene to add the material to
  107833. */
  107834. function EnvironmentHelper(options, scene) {
  107835. var _this = this;
  107836. this._errorHandler = function (message, exception) {
  107837. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  107838. };
  107839. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  107840. this._scene = scene;
  107841. this.onErrorObservable = new BABYLON.Observable();
  107842. this._setupBackground();
  107843. this._setupImageProcessing();
  107844. }
  107845. /**
  107846. * Creates the default options for the helper.
  107847. */
  107848. EnvironmentHelper._getDefaultOptions = function () {
  107849. return {
  107850. createGround: true,
  107851. groundSize: 15,
  107852. groundTexture: this._groundTextureCDNUrl,
  107853. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  107854. groundOpacity: 0.9,
  107855. enableGroundShadow: true,
  107856. groundShadowLevel: 0.5,
  107857. enableGroundMirror: false,
  107858. groundMirrorSizeRatio: 0.3,
  107859. groundMirrorBlurKernel: 64,
  107860. groundMirrorAmount: 1,
  107861. groundMirrorFresnelWeight: 1,
  107862. groundMirrorFallOffDistance: 0,
  107863. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  107864. groundYBias: 0.00001,
  107865. createSkybox: true,
  107866. skyboxSize: 20,
  107867. skyboxTexture: this._skyboxTextureCDNUrl,
  107868. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  107869. backgroundYRotation: 0,
  107870. sizeAuto: true,
  107871. rootPosition: BABYLON.Vector3.Zero(),
  107872. setupImageProcessing: true,
  107873. environmentTexture: this._environmentTextureCDNUrl,
  107874. cameraExposure: 0.8,
  107875. cameraContrast: 1.2,
  107876. toneMappingEnabled: true,
  107877. };
  107878. };
  107879. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  107880. /**
  107881. * Gets the root mesh created by the helper.
  107882. */
  107883. get: function () {
  107884. return this._rootMesh;
  107885. },
  107886. enumerable: true,
  107887. configurable: true
  107888. });
  107889. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  107890. /**
  107891. * Gets the skybox created by the helper.
  107892. */
  107893. get: function () {
  107894. return this._skybox;
  107895. },
  107896. enumerable: true,
  107897. configurable: true
  107898. });
  107899. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  107900. /**
  107901. * Gets the skybox texture created by the helper.
  107902. */
  107903. get: function () {
  107904. return this._skyboxTexture;
  107905. },
  107906. enumerable: true,
  107907. configurable: true
  107908. });
  107909. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  107910. /**
  107911. * Gets the skybox material created by the helper.
  107912. */
  107913. get: function () {
  107914. return this._skyboxMaterial;
  107915. },
  107916. enumerable: true,
  107917. configurable: true
  107918. });
  107919. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  107920. /**
  107921. * Gets the ground mesh created by the helper.
  107922. */
  107923. get: function () {
  107924. return this._ground;
  107925. },
  107926. enumerable: true,
  107927. configurable: true
  107928. });
  107929. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  107930. /**
  107931. * Gets the ground texture created by the helper.
  107932. */
  107933. get: function () {
  107934. return this._groundTexture;
  107935. },
  107936. enumerable: true,
  107937. configurable: true
  107938. });
  107939. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  107940. /**
  107941. * Gets the ground mirror created by the helper.
  107942. */
  107943. get: function () {
  107944. return this._groundMirror;
  107945. },
  107946. enumerable: true,
  107947. configurable: true
  107948. });
  107949. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  107950. /**
  107951. * Gets the ground mirror render list to helps pushing the meshes
  107952. * you wish in the ground reflection.
  107953. */
  107954. get: function () {
  107955. if (this._groundMirror) {
  107956. return this._groundMirror.renderList;
  107957. }
  107958. return null;
  107959. },
  107960. enumerable: true,
  107961. configurable: true
  107962. });
  107963. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  107964. /**
  107965. * Gets the ground material created by the helper.
  107966. */
  107967. get: function () {
  107968. return this._groundMaterial;
  107969. },
  107970. enumerable: true,
  107971. configurable: true
  107972. });
  107973. /**
  107974. * Updates the background according to the new options
  107975. * @param options
  107976. */
  107977. EnvironmentHelper.prototype.updateOptions = function (options) {
  107978. var newOptions = __assign({}, this._options, options);
  107979. if (this._ground && !newOptions.createGround) {
  107980. this._ground.dispose();
  107981. this._ground = null;
  107982. }
  107983. if (this._groundMaterial && !newOptions.createGround) {
  107984. this._groundMaterial.dispose();
  107985. this._groundMaterial = null;
  107986. }
  107987. if (this._groundTexture) {
  107988. if (this._options.groundTexture != newOptions.groundTexture) {
  107989. this._groundTexture.dispose();
  107990. this._groundTexture = null;
  107991. }
  107992. }
  107993. if (this._skybox && !newOptions.createSkybox) {
  107994. this._skybox.dispose();
  107995. this._skybox = null;
  107996. }
  107997. if (this._skyboxMaterial && !newOptions.createSkybox) {
  107998. this._skyboxMaterial.dispose();
  107999. this._skyboxMaterial = null;
  108000. }
  108001. if (this._skyboxTexture) {
  108002. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  108003. this._skyboxTexture.dispose();
  108004. this._skyboxTexture = null;
  108005. }
  108006. }
  108007. if (this._groundMirror && !newOptions.enableGroundMirror) {
  108008. this._groundMirror.dispose();
  108009. this._groundMirror = null;
  108010. }
  108011. if (this._scene.environmentTexture) {
  108012. if (this._options.environmentTexture != newOptions.environmentTexture) {
  108013. this._scene.environmentTexture.dispose();
  108014. }
  108015. }
  108016. this._options = newOptions;
  108017. this._setupBackground();
  108018. this._setupImageProcessing();
  108019. };
  108020. /**
  108021. * Sets the primary color of all the available elements.
  108022. * @param color the main color to affect to the ground and the background
  108023. */
  108024. EnvironmentHelper.prototype.setMainColor = function (color) {
  108025. if (this.groundMaterial) {
  108026. this.groundMaterial.primaryColor = color;
  108027. }
  108028. if (this.skyboxMaterial) {
  108029. this.skyboxMaterial.primaryColor = color;
  108030. }
  108031. if (this.groundMirror) {
  108032. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  108033. }
  108034. };
  108035. /**
  108036. * Setup the image processing according to the specified options.
  108037. */
  108038. EnvironmentHelper.prototype._setupImageProcessing = function () {
  108039. if (this._options.setupImageProcessing) {
  108040. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  108041. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  108042. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  108043. this._setupEnvironmentTexture();
  108044. }
  108045. };
  108046. /**
  108047. * Setup the environment texture according to the specified options.
  108048. */
  108049. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  108050. if (this._scene.environmentTexture) {
  108051. return;
  108052. }
  108053. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  108054. this._scene.environmentTexture = this._options.environmentTexture;
  108055. return;
  108056. }
  108057. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  108058. this._scene.environmentTexture = environmentTexture;
  108059. };
  108060. /**
  108061. * Setup the background according to the specified options.
  108062. */
  108063. EnvironmentHelper.prototype._setupBackground = function () {
  108064. if (!this._rootMesh) {
  108065. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  108066. }
  108067. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  108068. var sceneSize = this._getSceneSize();
  108069. if (this._options.createGround) {
  108070. this._setupGround(sceneSize);
  108071. this._setupGroundMaterial();
  108072. this._setupGroundDiffuseTexture();
  108073. if (this._options.enableGroundMirror) {
  108074. this._setupGroundMirrorTexture(sceneSize);
  108075. }
  108076. this._setupMirrorInGroundMaterial();
  108077. }
  108078. if (this._options.createSkybox) {
  108079. this._setupSkybox(sceneSize);
  108080. this._setupSkyboxMaterial();
  108081. this._setupSkyboxReflectionTexture();
  108082. }
  108083. this._rootMesh.position.x = sceneSize.rootPosition.x;
  108084. this._rootMesh.position.z = sceneSize.rootPosition.z;
  108085. this._rootMesh.position.y = sceneSize.rootPosition.y;
  108086. };
  108087. /**
  108088. * Get the scene sizes according to the setup.
  108089. */
  108090. EnvironmentHelper.prototype._getSceneSize = function () {
  108091. var _this = this;
  108092. var groundSize = this._options.groundSize;
  108093. var skyboxSize = this._options.skyboxSize;
  108094. var rootPosition = this._options.rootPosition;
  108095. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  108096. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108097. }
  108098. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  108099. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  108100. });
  108101. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  108102. if (this._options.sizeAuto) {
  108103. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  108104. this._scene.activeCamera.upperRadiusLimit) {
  108105. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  108106. skyboxSize = groundSize;
  108107. }
  108108. var sceneDiagonalLenght = sceneDiagonal.length();
  108109. if (sceneDiagonalLenght > groundSize) {
  108110. groundSize = sceneDiagonalLenght * 2;
  108111. skyboxSize = groundSize;
  108112. }
  108113. // 10 % bigger.
  108114. groundSize *= 1.1;
  108115. skyboxSize *= 1.5;
  108116. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  108117. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  108118. }
  108119. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108120. };
  108121. /**
  108122. * Setup the ground according to the specified options.
  108123. */
  108124. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  108125. var _this = this;
  108126. if (!this._ground || this._ground.isDisposed()) {
  108127. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  108128. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  108129. this._ground.parent = this._rootMesh;
  108130. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  108131. }
  108132. this._ground.receiveShadows = this._options.enableGroundShadow;
  108133. };
  108134. /**
  108135. * Setup the ground material according to the specified options.
  108136. */
  108137. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  108138. if (!this._groundMaterial) {
  108139. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  108140. }
  108141. this._groundMaterial.alpha = this._options.groundOpacity;
  108142. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  108143. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  108144. this._groundMaterial.primaryColor = this._options.groundColor;
  108145. this._groundMaterial.useRGBColor = false;
  108146. this._groundMaterial.enableNoise = true;
  108147. if (this._ground) {
  108148. this._ground.material = this._groundMaterial;
  108149. }
  108150. };
  108151. /**
  108152. * Setup the ground diffuse texture according to the specified options.
  108153. */
  108154. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  108155. if (!this._groundMaterial) {
  108156. return;
  108157. }
  108158. if (this._groundTexture) {
  108159. return;
  108160. }
  108161. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  108162. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  108163. return;
  108164. }
  108165. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  108166. diffuseTexture.gammaSpace = false;
  108167. diffuseTexture.hasAlpha = true;
  108168. this._groundMaterial.diffuseTexture = diffuseTexture;
  108169. };
  108170. /**
  108171. * Setup the ground mirror texture according to the specified options.
  108172. */
  108173. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  108174. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108175. if (!this._groundMirror) {
  108176. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  108177. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  108178. this._groundMirror.anisotropicFilteringLevel = 1;
  108179. this._groundMirror.wrapU = wrapping;
  108180. this._groundMirror.wrapV = wrapping;
  108181. this._groundMirror.gammaSpace = false;
  108182. if (this._groundMirror.renderList) {
  108183. for (var i = 0; i < this._scene.meshes.length; i++) {
  108184. var mesh = this._scene.meshes[i];
  108185. if (mesh !== this._ground &&
  108186. mesh !== this._skybox &&
  108187. mesh !== this._rootMesh) {
  108188. this._groundMirror.renderList.push(mesh);
  108189. }
  108190. }
  108191. }
  108192. }
  108193. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  108194. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  108195. };
  108196. /**
  108197. * Setup the ground to receive the mirror texture.
  108198. */
  108199. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  108200. if (this._groundMaterial) {
  108201. this._groundMaterial.reflectionTexture = this._groundMirror;
  108202. this._groundMaterial.reflectionFresnel = true;
  108203. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  108204. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  108205. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  108206. }
  108207. };
  108208. /**
  108209. * Setup the skybox according to the specified options.
  108210. */
  108211. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  108212. var _this = this;
  108213. if (!this._skybox || this._skybox.isDisposed()) {
  108214. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  108215. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  108216. }
  108217. this._skybox.parent = this._rootMesh;
  108218. };
  108219. /**
  108220. * Setup the skybox material according to the specified options.
  108221. */
  108222. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  108223. if (!this._skybox) {
  108224. return;
  108225. }
  108226. if (!this._skyboxMaterial) {
  108227. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  108228. }
  108229. this._skyboxMaterial.useRGBColor = false;
  108230. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  108231. this._skyboxMaterial.enableNoise = true;
  108232. this._skybox.material = this._skyboxMaterial;
  108233. };
  108234. /**
  108235. * Setup the skybox reflection texture according to the specified options.
  108236. */
  108237. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  108238. if (!this._skyboxMaterial) {
  108239. return;
  108240. }
  108241. if (this._skyboxTexture) {
  108242. return;
  108243. }
  108244. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  108245. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  108246. return;
  108247. }
  108248. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  108249. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  108250. this._skyboxTexture.gammaSpace = false;
  108251. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  108252. };
  108253. /**
  108254. * Dispose all the elements created by the Helper.
  108255. */
  108256. EnvironmentHelper.prototype.dispose = function () {
  108257. if (this._groundMaterial) {
  108258. this._groundMaterial.dispose(true, true);
  108259. }
  108260. if (this._skyboxMaterial) {
  108261. this._skyboxMaterial.dispose(true, true);
  108262. }
  108263. this._rootMesh.dispose(false);
  108264. };
  108265. /**
  108266. * Default ground texture URL.
  108267. */
  108268. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  108269. /**
  108270. * Default skybox texture URL.
  108271. */
  108272. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  108273. /**
  108274. * Default environment texture URL.
  108275. */
  108276. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  108277. return EnvironmentHelper;
  108278. }());
  108279. BABYLON.EnvironmentHelper = EnvironmentHelper;
  108280. })(BABYLON || (BABYLON = {}));
  108281. //# sourceMappingURL=babylon.environmentHelper.js.map
  108282. var BABYLON;
  108283. (function (BABYLON) {
  108284. /** Internal class used to store shapes for emitters */
  108285. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  108286. function ParticleSystemSetEmitterCreationOptions() {
  108287. }
  108288. return ParticleSystemSetEmitterCreationOptions;
  108289. }());
  108290. /**
  108291. * Represents a set of particle systems working together to create a specific effect
  108292. */
  108293. var ParticleSystemSet = /** @class */ (function () {
  108294. function ParticleSystemSet() {
  108295. /**
  108296. * Gets the particle system list
  108297. */
  108298. this.systems = new Array();
  108299. }
  108300. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  108301. /**
  108302. * Gets the emitter node used with this set
  108303. */
  108304. get: function () {
  108305. return this._emitterNode;
  108306. },
  108307. enumerable: true,
  108308. configurable: true
  108309. });
  108310. /**
  108311. * Creates a new emitter mesh as a sphere
  108312. * @param options defines the options used to create the sphere
  108313. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  108314. * @param scene defines the hosting scene
  108315. */
  108316. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  108317. if (this._emitterNode) {
  108318. this._emitterNode.dispose();
  108319. }
  108320. this._emitterCreationOptions = {
  108321. kind: "Sphere",
  108322. options: options,
  108323. renderingGroupId: renderingGroupId
  108324. };
  108325. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  108326. emitterMesh.renderingGroupId = renderingGroupId;
  108327. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  108328. material.emissiveColor = options.color;
  108329. emitterMesh.material = material;
  108330. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108331. var system = _a[_i];
  108332. system.emitter = emitterMesh;
  108333. }
  108334. this._emitterNode = emitterMesh;
  108335. };
  108336. /**
  108337. * Starts all particle systems of the set
  108338. * @param emitter defines an optional mesh to use as emitter for the particle systems
  108339. */
  108340. ParticleSystemSet.prototype.start = function (emitter) {
  108341. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108342. var system = _a[_i];
  108343. if (emitter) {
  108344. system.emitter = emitter;
  108345. }
  108346. system.start();
  108347. }
  108348. };
  108349. /**
  108350. * Release all associated resources
  108351. */
  108352. ParticleSystemSet.prototype.dispose = function () {
  108353. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108354. var system = _a[_i];
  108355. system.dispose();
  108356. }
  108357. this.systems = [];
  108358. if (this._emitterNode) {
  108359. this._emitterNode.dispose();
  108360. this._emitterNode = null;
  108361. }
  108362. };
  108363. /**
  108364. * Serialize the set into a JSON compatible object
  108365. * @returns a JSON compatible representation of the set
  108366. */
  108367. ParticleSystemSet.prototype.serialize = function () {
  108368. var result = {};
  108369. result.systems = [];
  108370. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108371. var system = _a[_i];
  108372. result.systems.push(system.serialize());
  108373. }
  108374. if (this._emitterNode) {
  108375. result.emitter = this._emitterCreationOptions;
  108376. }
  108377. return result;
  108378. };
  108379. /**
  108380. * Parse a new ParticleSystemSet from a serialized source
  108381. * @param data defines a JSON compatible representation of the set
  108382. * @param scene defines the hosting scene
  108383. * @param gpu defines if we want GPU particles or CPU particles
  108384. * @returns a new ParticleSystemSet
  108385. */
  108386. ParticleSystemSet.Parse = function (data, scene, gpu) {
  108387. if (gpu === void 0) { gpu = false; }
  108388. var result = new ParticleSystemSet();
  108389. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  108390. scene = scene || BABYLON.Engine.LastCreatedScene;
  108391. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  108392. var system = _a[_i];
  108393. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  108394. }
  108395. if (data.emitter) {
  108396. var options = data.emitter.options;
  108397. switch (data.emitter.kind) {
  108398. case "Sphere":
  108399. result.setEmitterAsSphere({
  108400. diameter: options.diameter,
  108401. segments: options.segments,
  108402. color: BABYLON.Color3.FromArray(options.color)
  108403. }, data.emitter.renderingGroupId, scene);
  108404. break;
  108405. }
  108406. }
  108407. return result;
  108408. };
  108409. return ParticleSystemSet;
  108410. }());
  108411. BABYLON.ParticleSystemSet = ParticleSystemSet;
  108412. })(BABYLON || (BABYLON = {}));
  108413. //# sourceMappingURL=babylon.particleSystemSet.js.map
  108414. var BABYLON;
  108415. (function (BABYLON) {
  108416. /**
  108417. * This class is made for on one-liner static method to help creating particle system set.
  108418. */
  108419. var ParticleHelper = /** @class */ (function () {
  108420. function ParticleHelper() {
  108421. }
  108422. /**
  108423. * Create a default particle system that you can tweak
  108424. * @param emitter defines the emitter to use
  108425. * @param capacity defines the system capacity (default is 500 particles)
  108426. * @param scene defines the hosting scene
  108427. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  108428. * @returns the new Particle system
  108429. */
  108430. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  108431. if (capacity === void 0) { capacity = 500; }
  108432. if (useGPU === void 0) { useGPU = false; }
  108433. var system;
  108434. if (useGPU) {
  108435. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  108436. }
  108437. else {
  108438. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  108439. }
  108440. system.emitter = emitter;
  108441. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  108442. system.createConeEmitter(0.1, Math.PI / 4);
  108443. // Particle color
  108444. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  108445. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  108446. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  108447. // Particle Size
  108448. system.minSize = 0.1;
  108449. system.maxSize = 0.1;
  108450. // Emission speed
  108451. system.minEmitPower = 2;
  108452. system.maxEmitPower = 2;
  108453. // Update speed
  108454. system.updateSpeed = 1 / 60;
  108455. system.emitRate = 30;
  108456. return system;
  108457. };
  108458. /**
  108459. * This is the main static method (one-liner) of this helper to create different particle systems
  108460. * @param type This string represents the type to the particle system to create
  108461. * @param scene The scene where the particle system should live
  108462. * @param gpu If the system will use gpu
  108463. * @returns the ParticleSystemSet created
  108464. */
  108465. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  108466. if (gpu === void 0) { gpu = false; }
  108467. if (!scene) {
  108468. scene = BABYLON.Engine.LastCreatedScene;
  108469. ;
  108470. }
  108471. var token = {};
  108472. scene._addPendingData(token);
  108473. return new Promise(function (resolve, reject) {
  108474. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  108475. scene._removePendingData(token);
  108476. return reject("Particle system with GPU is not supported.");
  108477. }
  108478. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  108479. scene._removePendingData(token);
  108480. var newData = JSON.parse(data.toString());
  108481. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  108482. }, undefined, undefined, undefined, function (req, exception) {
  108483. scene._removePendingData(token);
  108484. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  108485. });
  108486. });
  108487. };
  108488. /**
  108489. * Static function used to export a particle system to a ParticleSystemSet variable.
  108490. * Please note that the emitter shape is not exported
  108491. * @param system defines the particle systems to export
  108492. */
  108493. ParticleHelper.ExportSet = function (systems) {
  108494. var set = new BABYLON.ParticleSystemSet();
  108495. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  108496. var system = systems_1[_i];
  108497. set.systems.push(system);
  108498. }
  108499. return set;
  108500. };
  108501. /**
  108502. * Gets or sets base Assets URL
  108503. */
  108504. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  108505. return ParticleHelper;
  108506. }());
  108507. BABYLON.ParticleHelper = ParticleHelper;
  108508. })(BABYLON || (BABYLON = {}));
  108509. //# sourceMappingURL=babylon.particleHelper.js.map
  108510. var BABYLON;
  108511. (function (BABYLON) {
  108512. /**
  108513. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  108514. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  108515. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  108516. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  108517. */
  108518. var VideoDome = /** @class */ (function (_super) {
  108519. __extends(VideoDome, _super);
  108520. /**
  108521. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  108522. * @param name Element's name, child elements will append suffixes for their own names.
  108523. * @param urlsOrVideo defines the url(s) or the video element to use
  108524. * @param options An object containing optional or exposed sub element properties
  108525. */
  108526. function VideoDome(name, urlsOrVideo, options, scene) {
  108527. var _this = _super.call(this, name, scene) || this;
  108528. _this._useDirectMapping = false;
  108529. // set defaults and manage values
  108530. name = name || "videoDome";
  108531. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  108532. options.clickToPlay = Boolean(options.clickToPlay);
  108533. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  108534. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  108535. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  108536. if (options.useDirectMapping === undefined) {
  108537. _this._useDirectMapping = true;
  108538. }
  108539. else {
  108540. _this._useDirectMapping = options.useDirectMapping;
  108541. }
  108542. _this._setReady(false);
  108543. // create
  108544. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  108545. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  108546. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  108547. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  108548. texture.onLoadObservable.addOnce(function () {
  108549. _this._setReady(true);
  108550. });
  108551. // configure material
  108552. material.useEquirectangularFOV = true;
  108553. material.fovMultiplier = 1.0;
  108554. material.opacityFresnel = false;
  108555. if (_this._useDirectMapping) {
  108556. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108557. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108558. material.diffuseTexture = texture;
  108559. }
  108560. else {
  108561. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  108562. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108563. material.reflectionTexture = texture;
  108564. }
  108565. // configure mesh
  108566. _this._mesh.material = material;
  108567. _this._mesh.parent = _this;
  108568. // optional configuration
  108569. if (options.clickToPlay) {
  108570. scene.onPointerUp = function () {
  108571. _this._videoTexture.video.play();
  108572. };
  108573. }
  108574. return _this;
  108575. }
  108576. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  108577. /**
  108578. * Gets the video texture being displayed on the sphere
  108579. */
  108580. get: function () {
  108581. return this._videoTexture;
  108582. },
  108583. enumerable: true,
  108584. configurable: true
  108585. });
  108586. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  108587. /**
  108588. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  108589. * Also see the options.resolution property.
  108590. */
  108591. get: function () {
  108592. return this._material.fovMultiplier;
  108593. },
  108594. set: function (value) {
  108595. this._material.fovMultiplier = value;
  108596. },
  108597. enumerable: true,
  108598. configurable: true
  108599. });
  108600. /**
  108601. * Releases resources associated with this node.
  108602. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  108603. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  108604. */
  108605. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  108606. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  108607. this._videoTexture.dispose();
  108608. this._mesh.dispose();
  108609. this._material.dispose();
  108610. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  108611. };
  108612. return VideoDome;
  108613. }(BABYLON.TransformNode));
  108614. BABYLON.VideoDome = VideoDome;
  108615. })(BABYLON || (BABYLON = {}));
  108616. //# sourceMappingURL=babylon.videoDome.js.map
  108617. var BABYLON;
  108618. (function (BABYLON) {
  108619. /**
  108620. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  108621. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  108622. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  108623. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  108624. */
  108625. var PhotoDome = /** @class */ (function (_super) {
  108626. __extends(PhotoDome, _super);
  108627. /**
  108628. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  108629. * @param name Element's name, child elements will append suffixes for their own names.
  108630. * @param urlsOfPhoto defines the url of the photo to display
  108631. * @param options defines an object containing optional or exposed sub element properties
  108632. * @param onError defines a callback called when an error occured while loading the texture
  108633. */
  108634. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  108635. if (onError === void 0) { onError = null; }
  108636. var _this = _super.call(this, name, scene) || this;
  108637. _this._useDirectMapping = false;
  108638. /**
  108639. * Observable raised when an error occured while loading the 360 image
  108640. */
  108641. _this.onLoadErrorObservable = new BABYLON.Observable();
  108642. // set defaults and manage values
  108643. name = name || "photoDome";
  108644. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  108645. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  108646. if (options.useDirectMapping === undefined) {
  108647. _this._useDirectMapping = true;
  108648. }
  108649. else {
  108650. _this._useDirectMapping = options.useDirectMapping;
  108651. }
  108652. _this._setReady(false);
  108653. // create
  108654. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  108655. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  108656. // configure material
  108657. material.opacityFresnel = false;
  108658. material.useEquirectangularFOV = true;
  108659. material.fovMultiplier = 1.0;
  108660. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  108661. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  108662. if (onError) {
  108663. onError(message, exception);
  108664. }
  108665. });
  108666. _this.photoTexture.onLoadObservable.addOnce(function () {
  108667. _this._setReady(true);
  108668. });
  108669. // configure mesh
  108670. _this._mesh.material = material;
  108671. _this._mesh.parent = _this;
  108672. return _this;
  108673. }
  108674. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  108675. /**
  108676. * Gets or sets the texture being displayed on the sphere
  108677. */
  108678. get: function () {
  108679. return this._photoTexture;
  108680. },
  108681. set: function (value) {
  108682. if (this._photoTexture === value) {
  108683. return;
  108684. }
  108685. this._photoTexture = value;
  108686. if (this._useDirectMapping) {
  108687. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108688. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108689. this._material.diffuseTexture = this._photoTexture;
  108690. }
  108691. else {
  108692. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  108693. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108694. this._material.reflectionTexture = this._photoTexture;
  108695. }
  108696. },
  108697. enumerable: true,
  108698. configurable: true
  108699. });
  108700. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  108701. /**
  108702. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  108703. * Also see the options.resolution property.
  108704. */
  108705. get: function () {
  108706. return this._material.fovMultiplier;
  108707. },
  108708. set: function (value) {
  108709. this._material.fovMultiplier = value;
  108710. },
  108711. enumerable: true,
  108712. configurable: true
  108713. });
  108714. /**
  108715. * Releases resources associated with this node.
  108716. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  108717. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  108718. */
  108719. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  108720. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  108721. this._photoTexture.dispose();
  108722. this._mesh.dispose();
  108723. this._material.dispose();
  108724. this.onLoadErrorObservable.clear();
  108725. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  108726. };
  108727. return PhotoDome;
  108728. }(BABYLON.TransformNode));
  108729. BABYLON.PhotoDome = PhotoDome;
  108730. })(BABYLON || (BABYLON = {}));
  108731. //# sourceMappingURL=babylon.photoDome.js.map
  108732. var BABYLON;
  108733. (function (BABYLON) {
  108734. BABYLON.Engine.prototype.createQuery = function () {
  108735. return this._gl.createQuery();
  108736. };
  108737. BABYLON.Engine.prototype.deleteQuery = function (query) {
  108738. this._gl.deleteQuery(query);
  108739. return this;
  108740. };
  108741. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  108742. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  108743. };
  108744. BABYLON.Engine.prototype.getQueryResult = function (query) {
  108745. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  108746. };
  108747. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  108748. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  108749. this._gl.beginQuery(glAlgorithm, query);
  108750. return this;
  108751. };
  108752. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  108753. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  108754. this._gl.endQuery(glAlgorithm);
  108755. return this;
  108756. };
  108757. BABYLON.Engine.prototype._createTimeQuery = function () {
  108758. var timerQuery = this.getCaps().timerQuery;
  108759. if (timerQuery.createQueryEXT) {
  108760. return timerQuery.createQueryEXT();
  108761. }
  108762. return this.createQuery();
  108763. };
  108764. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  108765. var timerQuery = this.getCaps().timerQuery;
  108766. if (timerQuery.deleteQueryEXT) {
  108767. timerQuery.deleteQueryEXT(query);
  108768. return;
  108769. }
  108770. this.deleteQuery(query);
  108771. };
  108772. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  108773. var timerQuery = this.getCaps().timerQuery;
  108774. if (timerQuery.getQueryObjectEXT) {
  108775. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  108776. }
  108777. return this.getQueryResult(query);
  108778. };
  108779. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  108780. var timerQuery = this.getCaps().timerQuery;
  108781. if (timerQuery.getQueryObjectEXT) {
  108782. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  108783. }
  108784. return this.isQueryResultAvailable(query);
  108785. };
  108786. BABYLON.Engine.prototype.startTimeQuery = function () {
  108787. var caps = this.getCaps();
  108788. var timerQuery = caps.timerQuery;
  108789. if (!timerQuery) {
  108790. return null;
  108791. }
  108792. var token = new BABYLON._TimeToken();
  108793. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  108794. if (caps.canUseTimestampForTimerQuery) {
  108795. token._startTimeQuery = this._createTimeQuery();
  108796. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  108797. }
  108798. else {
  108799. if (this._currentNonTimestampToken) {
  108800. return this._currentNonTimestampToken;
  108801. }
  108802. token._timeElapsedQuery = this._createTimeQuery();
  108803. if (timerQuery.beginQueryEXT) {
  108804. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  108805. }
  108806. else {
  108807. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  108808. }
  108809. this._currentNonTimestampToken = token;
  108810. }
  108811. return token;
  108812. };
  108813. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  108814. var caps = this.getCaps();
  108815. var timerQuery = caps.timerQuery;
  108816. if (!timerQuery || !token) {
  108817. return -1;
  108818. }
  108819. if (caps.canUseTimestampForTimerQuery) {
  108820. if (!token._startTimeQuery) {
  108821. return -1;
  108822. }
  108823. if (!token._endTimeQuery) {
  108824. token._endTimeQuery = this._createTimeQuery();
  108825. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  108826. }
  108827. }
  108828. else if (!token._timeElapsedQueryEnded) {
  108829. if (!token._timeElapsedQuery) {
  108830. return -1;
  108831. }
  108832. if (timerQuery.endQueryEXT) {
  108833. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  108834. }
  108835. else {
  108836. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  108837. }
  108838. token._timeElapsedQueryEnded = true;
  108839. }
  108840. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  108841. var available = false;
  108842. if (token._endTimeQuery) {
  108843. available = this._getTimeQueryAvailability(token._endTimeQuery);
  108844. }
  108845. else if (token._timeElapsedQuery) {
  108846. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  108847. }
  108848. if (available && !disjoint) {
  108849. var result = 0;
  108850. if (caps.canUseTimestampForTimerQuery) {
  108851. if (!token._startTimeQuery || !token._endTimeQuery) {
  108852. return -1;
  108853. }
  108854. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  108855. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  108856. result = timeEnd - timeStart;
  108857. this._deleteTimeQuery(token._startTimeQuery);
  108858. this._deleteTimeQuery(token._endTimeQuery);
  108859. token._startTimeQuery = null;
  108860. token._endTimeQuery = null;
  108861. }
  108862. else {
  108863. if (!token._timeElapsedQuery) {
  108864. return -1;
  108865. }
  108866. result = this._getTimeQueryResult(token._timeElapsedQuery);
  108867. this._deleteTimeQuery(token._timeElapsedQuery);
  108868. token._timeElapsedQuery = null;
  108869. token._timeElapsedQueryEnded = false;
  108870. this._currentNonTimestampToken = null;
  108871. }
  108872. return result;
  108873. }
  108874. return -1;
  108875. };
  108876. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  108877. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  108878. };
  108879. // We also need to update AbstractMesh as there is a portion of the code there
  108880. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  108881. if (this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  108882. this._isOccluded = false;
  108883. return;
  108884. }
  108885. var engine = this.getEngine();
  108886. if (engine.webGLVersion < 2) {
  108887. this._isOccluded = false;
  108888. return;
  108889. }
  108890. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  108891. this._isOccluded = false;
  108892. return;
  108893. }
  108894. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  108895. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  108896. if (isOcclusionQueryAvailable) {
  108897. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  108898. this._isOcclusionQueryInProgress = false;
  108899. this._occlusionInternalRetryCounter = 0;
  108900. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  108901. }
  108902. else {
  108903. this._occlusionInternalRetryCounter++;
  108904. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  108905. this._isOcclusionQueryInProgress = false;
  108906. this._occlusionInternalRetryCounter = 0;
  108907. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  108908. // if strict continue the last state of the object.
  108909. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  108910. }
  108911. else {
  108912. return;
  108913. }
  108914. }
  108915. }
  108916. var scene = this.getScene();
  108917. if (scene.getBoundingBoxRenderer) {
  108918. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  108919. if (!this._occlusionQuery) {
  108920. this._occlusionQuery = engine.createQuery();
  108921. }
  108922. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  108923. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  108924. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  108925. this._isOcclusionQueryInProgress = true;
  108926. }
  108927. };
  108928. })(BABYLON || (BABYLON = {}));
  108929. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  108930. var BABYLON;
  108931. (function (BABYLON) {
  108932. /**
  108933. * Class used to generate noise procedural textures
  108934. */
  108935. var NoiseProceduralTexture = /** @class */ (function (_super) {
  108936. __extends(NoiseProceduralTexture, _super);
  108937. /**
  108938. * Creates a new NoiseProceduralTexture
  108939. * @param name defines the name fo the texture
  108940. * @param size defines the size of the texture (default is 256)
  108941. * @param scene defines the hosting scene
  108942. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  108943. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  108944. */
  108945. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  108946. if (size === void 0) { size = 256; }
  108947. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  108948. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  108949. _this._time = 0;
  108950. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  108951. _this.brightness = 0.2;
  108952. /** Defines the number of octaves to process */
  108953. _this.octaves = 3;
  108954. /** Defines the level of persistence (0.8 by default) */
  108955. _this.persistence = 0.8;
  108956. /** Gets or sets animation speed factor (default is 1) */
  108957. _this.animationSpeedFactor = 1;
  108958. _this._updateShaderUniforms();
  108959. return _this;
  108960. }
  108961. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  108962. var scene = this.getScene();
  108963. if (!scene) {
  108964. return;
  108965. }
  108966. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  108967. this.setFloat("brightness", this.brightness);
  108968. this.setFloat("persistence", this.persistence);
  108969. this.setFloat("timeScale", this._time);
  108970. };
  108971. NoiseProceduralTexture.prototype._getDefines = function () {
  108972. return "#define OCTAVES " + this.octaves;
  108973. };
  108974. /** Generate the current state of the procedural texture */
  108975. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  108976. this._updateShaderUniforms();
  108977. _super.prototype.render.call(this, useCameraPostProcess);
  108978. };
  108979. /**
  108980. * Serializes this noise procedural texture
  108981. * @returns a serialized noise procedural texture object
  108982. */
  108983. NoiseProceduralTexture.prototype.serialize = function () {
  108984. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  108985. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  108986. return serializationObject;
  108987. };
  108988. /**
  108989. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  108990. * @param parsedTexture defines parsed texture data
  108991. * @param scene defines the current scene
  108992. * @param rootUrl defines the root URL containing noise procedural texture information
  108993. * @returns a parsed NoiseProceduralTexture
  108994. */
  108995. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  108996. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  108997. return texture;
  108998. };
  108999. return NoiseProceduralTexture;
  109000. }(BABYLON.ProceduralTexture));
  109001. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  109002. })(BABYLON || (BABYLON = {}));
  109003. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  109004. var __assign = (this && this.__assign) || function () {
  109005. __assign = Object.assign || function(t) {
  109006. for (var s, i = 1, n = arguments.length; i < n; i++) {
  109007. s = arguments[i];
  109008. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  109009. t[p] = s[p];
  109010. }
  109011. return t;
  109012. };
  109013. return __assign.apply(this, arguments);
  109014. };
  109015. var BABYLON;
  109016. (function (BABYLON) {
  109017. /**
  109018. * This can helps recording videos from BabylonJS.
  109019. * This is based on the available WebRTC functionalities of the browser.
  109020. *
  109021. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  109022. */
  109023. var VideoRecorder = /** @class */ (function () {
  109024. /**
  109025. * Create a new VideoCapture object which can help converting what you see in Babylon to
  109026. * a video file.
  109027. * @param engine Defines the BabylonJS Engine you wish to record
  109028. * @param options Defines options that can be used to customized the capture
  109029. */
  109030. function VideoRecorder(engine, options) {
  109031. if (options === void 0) { options = null; }
  109032. if (!VideoRecorder.IsSupported(engine)) {
  109033. throw "Your browser does not support recording so far.";
  109034. }
  109035. var canvas = engine.getRenderingCanvas();
  109036. if (!canvas) {
  109037. throw "The babylon engine must have a canvas to be recorded";
  109038. }
  109039. this._canvas = canvas;
  109040. this._canvas.isRecording = false;
  109041. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  109042. var stream = this._canvas.captureStream(this._options.fps);
  109043. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  109044. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  109045. this._mediaRecorder.onerror = this._handleError.bind(this);
  109046. this._mediaRecorder.onstop = this._handleStop.bind(this);
  109047. }
  109048. /**
  109049. * Returns wehther or not the VideoRecorder is available in your browser.
  109050. * @param engine Defines the Babylon Engine to check the support for
  109051. * @returns true if supported otherwise false
  109052. */
  109053. VideoRecorder.IsSupported = function (engine) {
  109054. var canvas = engine.getRenderingCanvas();
  109055. return (!!canvas && typeof canvas.captureStream === "function");
  109056. };
  109057. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  109058. /**
  109059. * True wether a recording is already in progress.
  109060. */
  109061. get: function () {
  109062. return !!this._canvas && this._canvas.isRecording;
  109063. },
  109064. enumerable: true,
  109065. configurable: true
  109066. });
  109067. /**
  109068. * Stops the current recording before the default capture timeout passed in the startRecording
  109069. * functions.
  109070. */
  109071. VideoRecorder.prototype.stopRecording = function () {
  109072. if (!this._canvas || !this._mediaRecorder) {
  109073. return;
  109074. }
  109075. if (!this.isRecording) {
  109076. return;
  109077. }
  109078. this._canvas.isRecording = false;
  109079. this._mediaRecorder.stop();
  109080. };
  109081. /**
  109082. * Starts recording the canvas for a max duration specified in parameters.
  109083. * @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.
  109084. * @param maxDuration Defines the maximum recording time in seconds.
  109085. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  109086. * @return a promise callback at the end of the recording with the video data in Blob.
  109087. */
  109088. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  109089. var _this = this;
  109090. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  109091. if (maxDuration === void 0) { maxDuration = 7; }
  109092. if (!this._canvas || !this._mediaRecorder) {
  109093. throw "Recorder has already been disposed";
  109094. }
  109095. if (this.isRecording) {
  109096. throw "Recording already in progress";
  109097. }
  109098. if (maxDuration > 0) {
  109099. setTimeout(function () {
  109100. _this.stopRecording();
  109101. }, maxDuration * 1000);
  109102. }
  109103. this._fileName = fileName;
  109104. this._recordedChunks = [];
  109105. this._resolve = null;
  109106. this._reject = null;
  109107. this._canvas.isRecording = true;
  109108. this._mediaRecorder.start(this._options.recordChunckSize);
  109109. return new Promise(function (resolve, reject) {
  109110. _this._resolve = resolve;
  109111. _this._reject = reject;
  109112. });
  109113. };
  109114. /**
  109115. * Releases internal resources used during the recording.
  109116. */
  109117. VideoRecorder.prototype.dispose = function () {
  109118. this._canvas = null;
  109119. this._mediaRecorder = null;
  109120. this._recordedChunks = [];
  109121. this._fileName = null;
  109122. this._resolve = null;
  109123. this._reject = null;
  109124. };
  109125. VideoRecorder.prototype._handleDataAvailable = function (event) {
  109126. if (event.data.size > 0) {
  109127. this._recordedChunks.push(event.data);
  109128. }
  109129. };
  109130. VideoRecorder.prototype._handleError = function (event) {
  109131. this.stopRecording();
  109132. if (this._reject) {
  109133. this._reject(event.error);
  109134. }
  109135. else {
  109136. throw new event.error;
  109137. }
  109138. };
  109139. VideoRecorder.prototype._handleStop = function () {
  109140. this.stopRecording();
  109141. var superBuffer = new Blob(this._recordedChunks);
  109142. if (this._resolve) {
  109143. this._resolve(superBuffer);
  109144. }
  109145. window.URL.createObjectURL(superBuffer);
  109146. if (this._fileName) {
  109147. BABYLON.Tools.Download(superBuffer, this._fileName);
  109148. }
  109149. };
  109150. VideoRecorder._defaultOptions = {
  109151. mimeType: "video/webm",
  109152. fps: 25,
  109153. recordChunckSize: 3000
  109154. };
  109155. return VideoRecorder;
  109156. }());
  109157. BABYLON.VideoRecorder = VideoRecorder;
  109158. })(BABYLON || (BABYLON = {}));
  109159. //# sourceMappingURL=babylon.videoRecorder.js.map
  109160. var BABYLON;
  109161. (function (BABYLON) {
  109162. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  109163. if (replace === void 0) { replace = false; }
  109164. // Dispose existing light in replace mode.
  109165. if (replace) {
  109166. if (this.lights) {
  109167. for (var i = 0; i < this.lights.length; i++) {
  109168. this.lights[i].dispose();
  109169. }
  109170. }
  109171. }
  109172. // Light
  109173. if (this.lights.length === 0) {
  109174. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  109175. }
  109176. };
  109177. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  109178. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  109179. if (replace === void 0) { replace = false; }
  109180. if (attachCameraControls === void 0) { attachCameraControls = false; }
  109181. // Dispose existing camera in replace mode.
  109182. if (replace) {
  109183. if (this.activeCamera) {
  109184. this.activeCamera.dispose();
  109185. this.activeCamera = null;
  109186. }
  109187. }
  109188. // Camera
  109189. if (!this.activeCamera) {
  109190. var worldExtends = this.getWorldExtends();
  109191. var worldSize = worldExtends.max.subtract(worldExtends.min);
  109192. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  109193. var camera;
  109194. var radius = worldSize.length() * 1.5;
  109195. // empty scene scenario!
  109196. if (!isFinite(radius)) {
  109197. radius = 1;
  109198. worldCenter.copyFromFloats(0, 0, 0);
  109199. }
  109200. if (createArcRotateCamera) {
  109201. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  109202. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  109203. arcRotateCamera.wheelPrecision = 100 / radius;
  109204. camera = arcRotateCamera;
  109205. }
  109206. else {
  109207. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  109208. freeCamera.setTarget(worldCenter);
  109209. camera = freeCamera;
  109210. }
  109211. camera.minZ = radius * 0.01;
  109212. camera.maxZ = radius * 1000;
  109213. camera.speed = radius * 0.2;
  109214. this.activeCamera = camera;
  109215. var canvas = this.getEngine().getRenderingCanvas();
  109216. if (attachCameraControls && canvas) {
  109217. camera.attachControl(canvas);
  109218. }
  109219. }
  109220. };
  109221. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  109222. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  109223. if (replace === void 0) { replace = false; }
  109224. if (attachCameraControls === void 0) { attachCameraControls = false; }
  109225. this.createDefaultLight(replace);
  109226. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  109227. };
  109228. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  109229. if (pbr === void 0) { pbr = false; }
  109230. if (scale === void 0) { scale = 1000; }
  109231. if (blur === void 0) { blur = 0; }
  109232. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  109233. if (!environmentTexture) {
  109234. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  109235. return null;
  109236. }
  109237. if (setGlobalEnvTexture) {
  109238. if (environmentTexture) {
  109239. this.environmentTexture = environmentTexture;
  109240. }
  109241. }
  109242. // Skybox
  109243. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  109244. if (pbr) {
  109245. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  109246. hdrSkyboxMaterial.backFaceCulling = false;
  109247. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  109248. if (hdrSkyboxMaterial.reflectionTexture) {
  109249. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  109250. }
  109251. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  109252. hdrSkyboxMaterial.disableLighting = true;
  109253. hdrSkyboxMaterial.twoSidedLighting = true;
  109254. hdrSkybox.infiniteDistance = true;
  109255. hdrSkybox.material = hdrSkyboxMaterial;
  109256. }
  109257. else {
  109258. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  109259. skyboxMaterial.backFaceCulling = false;
  109260. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  109261. if (skyboxMaterial.reflectionTexture) {
  109262. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  109263. }
  109264. skyboxMaterial.disableLighting = true;
  109265. hdrSkybox.infiniteDistance = true;
  109266. hdrSkybox.material = skyboxMaterial;
  109267. }
  109268. return hdrSkybox;
  109269. };
  109270. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  109271. if (BABYLON.EnvironmentHelper) {
  109272. return new BABYLON.EnvironmentHelper(options, this);
  109273. }
  109274. return null;
  109275. };
  109276. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  109277. if (webVROptions === void 0) { webVROptions = {}; }
  109278. return new BABYLON.VRExperienceHelper(this, webVROptions);
  109279. };
  109280. })(BABYLON || (BABYLON = {}));
  109281. //# sourceMappingURL=babylon.sceneHelpers.js.map
  109282. 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 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}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#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\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin 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}\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#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\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 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} 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(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\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"};
  109283. 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};"};
  109284. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  109285. globalObject["BABYLON"] = BABYLON;
  109286. //backwards compatibility
  109287. if(typeof earcut !== 'undefined') {
  109288. globalObject["Earcut"] = {
  109289. earcut: earcut
  109290. };
  109291. }
  109292. return BABYLON;
  109293. });